text
stringlengths
14
6.51M
unit SelOrden; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, AdoDb, Db; type TSelOrdenDlg = class(TForm) BitBtn1: TBitBtn; BitBtn2: TBitBtn; lbCampos: TListBox; rgMetodo: TRadioGroup; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BitBtn1Click(Sender: TObject); private FDataSet: TAdoDataSet; ACampos: TStringList; FCampoSel: string; FAscendente: boolean; procedure SetDataSet(const Value: TAdoDataSet); procedure CargarCampos; procedure SetCampoSel(const Value: string); procedure SetAscendente(const Value: boolean); { Private declarations } public { Public declarations } property DataSet: TAdoDataSet read FDataSet write SetDataSet; property CampoSel: string read FCampoSel write SetCampoSel; property Ascendente: boolean read FAscendente write SetAscendente; end; var SelOrdenDlg: TSelOrdenDlg; implementation {$R *.DFM} { TOrdenDlg } procedure TSelOrdenDlg.CargarCampos; var x: integer; begin lbCampos.Items.Clear; if Assigned( FDataSet ) then for x:=0 to FDataSet.FieldCount-1 do if FDataSet.Fields[ x ].FieldKind = fkData then begin lbCampos.Items.Add( FDataSet.Fields[ x ].DisplayLabel ); ACampos.Add( FDataSet.Fields[ x ].FieldName ); end; end; procedure TSelOrdenDlg.SetDataSet(const Value: TAdoDataSet); begin FDataSet := Value; if Value <> nil then Self.FreeNotification( Value ); CargarCampos; end; procedure TSelOrdenDlg.FormCreate(Sender: TObject); begin ACampos := TStringList.create; end; procedure TSelOrdenDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin ACampos.free; end; procedure TSelOrdenDlg.BitBtn1Click(Sender: TObject); begin if lbCampos.ItemIndex >= 0 then begin FCampoSel := ACampos[ lbCampos.ItemIndex ]; FAscendente := rgMetodo.ItemIndex = 0; end; end; procedure TSelOrdenDlg.SetCampoSel(const Value: string); begin FCampoSel := Value; end; procedure TSelOrdenDlg.SetAscendente(const Value: boolean); begin FAscendente := Value; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type HTTPTest = public class (Test) public method DownloadAsString; method DownloadAsBinary; method DownloadAsXml; end; implementation method HTTPTest.DownloadAsString; begin var Token := TokenProvider.CreateAwaitToken; Http.ExecuteRequestAsString(Encoding.UTF8, new HttpRequest(new Url("http://example.com")), Responce -> begin Token.Run(->begin Assert.IsNotNil(Responce); Assert.IsTrue(Responce.Success); Assert.IsNil(Responce.Exception); Assert.IsNotNil(Responce.Content); Assert.IsTrue(Responce.Content.StartsWith("<!doctype html>")); end) end); Token.WaitFor; Token := TokenProvider.CreateAwaitToken; Http.ExecuteRequestAsString(Encoding.UTF8, new HttpRequest(new Url("http://example.com/notexists")), Responce -> begin Token.Run(->begin Assert.IsNotNil(Responce); Assert.IsFalse(Responce.Success); Assert.IsNotNil(Responce.Exception); Assert.IsNil(Responce.Content); end) end); Token.WaitFor; end; method HTTPTest.DownloadAsBinary; begin var Token := TokenProvider.CreateAwaitToken; Http.ExecuteRequestAsBinary(new HttpRequest(new Url("http://example.com")), Responce -> begin Token.Run(->begin Assert.IsNotNil(Responce); Assert.IsTrue(Responce.Success); Assert.IsNil(Responce.Exception); Assert.IsNotNil(Responce.Content); var Line := new String(Responce.Content.Read(15), Encoding.UTF8); Assert.IsTrue(Line.StartsWith("<!doctype html>")); end) end); Token.WaitFor; end; method HTTPTest.DownloadAsXml; begin var Token := TokenProvider.CreateAwaitToken; Http.ExecuteRequestAsXml(new HttpRequest(new Url("http://images.apple.com/main/rss/hotnews/hotnews.rss")), Responce -> begin Token.Run(->begin Assert.IsNotNil(Responce); Assert.IsTrue(Responce.Success); Assert.IsNil(Responce.Exception); Assert.IsNotNil(Responce.Content); var Root := Responce.Content.Element["channel"]; Assert.IsNotNil(Root); Assert.AreEqual(Root.ChildNodes[0].Value, "Apple Hot News"); end) end); Token.WaitFor; end; end.
unit FolderNotifier_i; // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\FolderNotifier_i.pas" // Стереотип: "SimpleClass" // Элемент модели: "FolderNotifier_i" MUID: (45FFCCC9000F) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , FoldersUnit ; type // NotifierStatusConvertor FolderNotifier_i = class private current_user: ; external_folders_change_notifier: ; done_notifier: ; public constructor Make; reintroduce; virtual; stdcall; procedure SendNotify(status: TNotifyStatus; folder_id: Cardinal); virtual; stdcall; function Ready: ByteBool; virtual; stdcall; {* Возвращает true, если нотифаер готов обрабатывать нотификацию от сервера. } procedure SetExternalFoldersChangeNotifier(var notifier: IExternalFoldersChangeNotifier); virtual; stdcall; {* Установить оболочечный нотифайер } end;//FolderNotifier_i implementation uses l3ImplUses , ApplicationHelper , DoneNotifier_i //#UC START# *45FFCCC9000Fimpl_uses* //#UC END# *45FFCCC9000Fimpl_uses* ; constructor FolderNotifier_i.Make; //#UC START# *45FFD1B40251_45FFCCC9000F_var* //#UC END# *45FFD1B40251_45FFCCC9000F_var* begin //#UC START# *45FFD1B40251_45FFCCC9000F_impl* !!! Needs to be implemented !!! //#UC END# *45FFD1B40251_45FFCCC9000F_impl* end;//FolderNotifier_i.Make procedure FolderNotifier_i.SendNotify(status: TNotifyStatus; folder_id: Cardinal); //#UC START# *45FFD2C10203_45FFCCC9000F_var* //#UC END# *45FFD2C10203_45FFCCC9000F_var* begin //#UC START# *45FFD2C10203_45FFCCC9000F_impl* !!! Needs to be implemented !!! //#UC END# *45FFD2C10203_45FFCCC9000F_impl* end;//FolderNotifier_i.SendNotify function FolderNotifier_i.Ready: ByteBool; {* Возвращает true, если нотифаер готов обрабатывать нотификацию от сервера. } //#UC START# *49DEFD89010A_45FFCCC9000F_var* //#UC END# *49DEFD89010A_45FFCCC9000F_var* begin //#UC START# *49DEFD89010A_45FFCCC9000F_impl* !!! Needs to be implemented !!! //#UC END# *49DEFD89010A_45FFCCC9000F_impl* end;//FolderNotifier_i.Ready procedure FolderNotifier_i.SetExternalFoldersChangeNotifier(var notifier: IExternalFoldersChangeNotifier); {* Установить оболочечный нотифайер } //#UC START# *49DEFDAF0082_45FFCCC9000F_var* //#UC END# *49DEFDAF0082_45FFCCC9000F_var* begin //#UC START# *49DEFDAF0082_45FFCCC9000F_impl* !!! Needs to be implemented !!! //#UC END# *49DEFDAF0082_45FFCCC9000F_impl* end;//FolderNotifier_i.SetExternalFoldersChangeNotifier end.
unit uCadCargo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uTelaHeranca, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, Vcl.ExtCtrls, Vcl.ComCtrls,uEnum,cCadCargo,uDTMConexao; type TfrmCadCargo = class(TfrmTelaheranca) fdtncfldQryListagemcod_cargo: TFDAutoIncField; strngfldQryListagemcargo: TStringField; lbledtCargo: TLabeledEdit; lbledtCodigo: TLabeledEdit; intgrfldQryListagemnivel: TIntegerField; lbledtNivel: TLabeledEdit; procedure btnAlterarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure grdListagemTitleClick(Column: TColumn); private { Private declarations } oCargo: TCargo; function Apagar:Boolean; override; function Gravar(EstadodoCadastro:TEstadoDoCadastro):Boolean; override; public { Public declarations } end; var frmCadCargo: TfrmCadCargo; implementation {$R *.dfm} {$REGION 'Override'} function TfrmCadCargo.Apagar: Boolean; begin if oCargo.Selecionar(QryListagem.FieldByName('cod_cargo').AsInteger) then Result:=oCargo.Apagar; end; function TfrmCadCargo.Gravar(EstadodoCadastro: TEstadoDoCadastro): Boolean; begin if lbledtCodigo.Text<>EmptyStr then oCargo.cod_cargo:=StrToInt(lbledtCodigo.Text) else oCargo.cod_cargo :=0; oCargo.cargo:=lbledtCargo.Text; oCargo.nivel:=StrToInt(lbledtNivel.Text); if (EstadodoCadastro=ecInserir) then Result:=oCargo.Inserir else if (EstadodoCadastro=ecAlterar) then Result:=oCargo.Atualizar; end; procedure TfrmCadCargo.grdListagemTitleClick(Column: TColumn); begin inherited; end; {$endregion} procedure TfrmCadCargo.btnAlterarClick(Sender: TObject); begin if oCargo.Selecionar(QryListagem.FieldByName('cod_cargo').AsInteger) then begin lbledtCodigo.Text := IntToStr(oCargo.cod_cargo); lbledtCargo.Text := oCargo.cargo; lbledtNivel.Text:= oCargo.nivel.ToString(); end else begin btnCancelar.Click; Abort; end; inherited; end; procedure TfrmCadCargo.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if Assigned(oCargo) then FreeAndNil(oCargo); end; procedure TfrmCadCargo.FormCreate(Sender: TObject); begin inherited; oCargo:= TCargo.Create(dtmPrincipal.ConexaoDB); IndiceAtual:='cod_cargo'; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.1 2/23/2005 6:34:26 PM JPMugaas New property for displaying permissions ina GUI column. Note that this should not be used like a CHMOD because permissions are different on different platforms - you have been warned. Rev 1.0 11/24/2004 12:17:00 PM JPMugaas New parser for Stratus VOS. This will work with: } unit IdFTPListParseStratusVOS; { FTP server (FTP 1.0 for Stratus STCP) FTP server (OS TCP/IP) } interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdStratusVOSFTPListItem = class(TIdFTPListItem) protected FAccess : String; FNumberBlocks : Integer; FBlockSize : Integer; FFileFormat : String; FLinkedItemName : string; public property Access : String read FAccess write FAccess; property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks; property BlockSize : Integer read FBlockSize write FBlockSize; property FileFormat : String read FFileFormat write FFileFormat; //This results will look odd for symbolic links //Don't panic!!! // //Stratus VOS has an unusual path syntax such as: // //%phx_cac#m2_user>Stratus>Charles_Spitzer>junque>_edit.vterm1.1 // //where the > is a path separator property LinkedItemName : string read FLinkedItemName write FLinkedItemName; end; TIdFTPLPStratusVOS = class(TIdFTPListBase) protected class function IsValidFileEntry(const ALine : String) : Boolean; class function IsValidDirEntry(const ALine : String): Boolean; class function IsFilesHeader(const ALine : String): Boolean; class function IsDirsHeader(const ALine : String): Boolean; class function IsLinksHeader(const ALine : String): Boolean; class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseDirEntry(const AItem: TIdFTPListItem): Boolean; class function ParseFileEntry(const AItem : TIdFTPListItem): Boolean; class function ParseLinkEntry(const AItem : TIdFTPListItem): Boolean; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; class function ParseListing(AListing : TStrings; ADir : TIdFTPListItems) : Boolean; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseStratusVOS"'*) implementation { From: Manual Name: VOS Reference Manual Part Number: R002 Revision Number: 01 Printing Date: April 1990 Stratus Computer, Inc. Path Names The most important function of the directory hierarchy is to provide a way to uniquely but conveniently name any object in the I/O system. Any user on any processing module or system that can communicate with the module containing the object can then refer to the object. The unique name of an object is derived from the object's unique path in the I/O system. The unique name is called the path name of the object. A path name is constructed from the name of the object, the names of the directories in the path leading to the object, and the name of the system containing the root parent directory. The path name of a file or directory is a combination of the following names: 1. the name of the system containing the object preceded by a percent sign (%). 2. the name of the disk containing the object preceded by a number sign (#) 3. the names of the directories in the path of the object, in order, each preceded by the greater-than sign (>) 4. the name of the object preceded by the greater-than sign (>). The symbol > is used to separate directories and files in the path name. Its use is similar to the use of / or \ in other operating systems. For example, suppose you have a system named %s containing a disk named #d01. (The module containing the disk is %s#m1.) The following is an example of a full path name for the file named this_week. %s#d01>Administration>Jones>reports>this_week The file is immediately contained in the directory reports, which is subordinate to the directory Jones. The home directory Jones is a subdirectory of the group directory Administration which is a subdirectory of the disk #d01. Relative Path Names The path names defined so far are full path names. The full path name of an object is unique because the path of an object is unique. The operating system can also interpret relative path names. A relative path name is a combination of object names and pecial symbols, like a full path name, that identifies an object in the directory hierarchy. A relative path name of the object generally does not contain all the directory names that are in the full path name. When you use a relative path name, the operating system determines the missing information about the object's location rom the location of the current directory. If the operating system reads a string that it expects to be a path name and the leading character is not a percent sign, it interprets the string as a relative path name. The single character < can be used to refer to the parent directory of the current directory. For example, the command change_current_dir < moves you up one directory in the directory hierarchy. A single period (.) also refers to the current directory and two periods (..) refers to the parent directory. Thus, change_current_dir .. is the same as the change_current_dir <. } uses IdFTPCommon, IdGlobal, IdGlobalProtocols, SysUtils; { TIdFTPLPStratusVOS } class function TIdFTPLPStratusVOS.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var i : Integer; LMode : TIdDirItemType; begin Result := False; LMode := ditFile; for i := 0 to AListing.Count - 1 do begin if AListing[i] <> '' then begin if IsFilesHeader(AListing[i]) then begin LMode := ditFile; end else if IsDirsHeader(AListing[i]) then begin LMode := ditDirectory; end else if IsLinksHeader(AListing[i]) then begin LMode := ditSymbolicLink; end else begin case LMode of ditFile : begin if not IsValidFileEntry(AListing[i]) then begin Exit; end; end; ditDirectory : begin if not IsValidDirEntry(AListing[i]) then begin Exit; end; end; end; end; end; end; Result := True; end; class function TIdFTPLPStratusVOS.GetIdent: String; begin Result := 'Stratus VOS'; {do not localize} end; class function TIdFTPLPStratusVOS.IsDirsHeader(const ALine: String): Boolean; begin { Dirs: 0 } Result := TextStartsWith(ALine, 'Dirs: '); {do not localize} end; class function TIdFTPLPStratusVOS.IsFilesHeader(const ALine: String): Boolean; begin { Files: 4 Blocks: 609 } Result := TextStartsWith(ALine, 'Files: ') and (IndyPos('Blocks: ', ALine) > 8); {do not localize} end; class function TIdFTPLPStratusVOS.IsLinksHeader(const ALine: String): Boolean; begin { Links: 0 } Result := TextStartsWith(ALine, 'Links: '); {do not localize} end; class function TIdFTPLPStratusVOS.IsValidDirEntry(const ALine: String): Boolean; var s, s2 : String; begin Result := False; s := ALine; //a listing may start of with one space //permissions if TextStartsWith(s, ' ') then begin {do not localize} IdDelete(s, 1, 1); end; if Length(Fetch(s)) <> 1 then begin Exit; end; s := TrimLeft(s); //block count if not IsNumeric(Fetch(s)) then begin Exit; end; s := TrimLeft(s); s2 := Fetch(s); //date if not IsYYYYMMDD(s2) then begin Exit; end; s := TrimLeft(s); s2 := Fetch(s); //time Result := IsHHMMSS(s2, ':'); {do not localize} end; class function TIdFTPLPStratusVOS.IsValidFileEntry(const ALine: String): Boolean; var s, s2 : String; begin Result := False; s := ALine; //a listing may start of with one space if TextStartsWith(s, ' ') then begin {do not localize} IdDelete(s, 1, 1); end; if Length(Fetch(s)) <> 1 then begin Exit; end; s := TrimLeft(s); if not IsNumeric(Fetch(s)) then begin Exit; end; s := TrimLeft(s); s2 := Fetch(s); if not IsNumeric(s2, 2) then begin s := TrimLeft(s); s2 := Fetch(s); end; if not IsYYYYMMDD(s2) then begin Exit; end; s := TrimLeft(s); s2 := Fetch(s); Result := IsHHMMSS(s2, ':'); {do not localize} end; class function TIdFTPLPStratusVOS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdStratusVOSFTPListItem.Create(AOwner); end; class function TIdFTPLPStratusVOS.ParseDirEntry(const AItem: TIdFTPListItem): Boolean; var LV : TIdStratusVOSFTPListItem; LBuf, LPart : String; begin //w 158 stm 90-05-19 11:53:44 acctng.cobol { Files Access Access Description Right Code -------------------------------- undefined u Denies the user all access to the file. This code occurs only if the effective access list for the file does not contain any entry applicable to the given user name. nul n Denies the user all access to the file. execute e Allows the user to execute a program module or command macro, but not to read, modify, or delete it. read r Allows the user to read the file (or to execute it, if it is executable), but not to modify or delete it. write w Gives the user full access to the contents of the file. (However, to delete or write to the file, the user must have modify access to the directory in which the file is contained.) Directory Access Access Description Right Code -------------------------------- undefined u Denies the user all access to the directory. This code occurs only if the effective access list for the directory does not contain any entry applicable to the given user name. nul n Denies the user all access to the directory. status s Allows the user to list the contents of the directory and to see other status information, but not to change any of the contents. modify m Gives the user full access to the contents of the directory. } Result := False; LV := AItem as TIdStratusVOSFTPListItem; LBuf := AItem.Data; if TextStartsWith(LBuf, ' ') then begin {do not localize} IdDelete(LBuf, 1, 1); end; LV.FAccess := Fetch(LBuf); if Length(LV.FAccess) <> 1 then begin //invalid LV.FAccess := ''; Exit; end; LBuf := TrimLeft(LBuf); //block count LPart := Fetch(LBuf); if not IsNumeric(LPart) then begin Exit; end; LV.NumberBlocks := IndyStrToInt(LPart, 0); //size LV.Size := (LV.NumberBlocks * 4096); LV.SizeAvail := True; //Note that will NOT be accurate but it's the best you can do. //date LBuf := TrimLeft(LBuf); LPart := Fetch(LBuf); if not IsYYYYMMDD(LPart) then begin Exit; end; LV.ModifiedDate := DateYYMMDD(LPart); //time LBuf := TrimLeft(LBuf); LPart := Fetch(LBuf); if not IsHHMMSS(LPart, ':') then begin {do not localize} Exit; end; LV.ModifiedDate := LV.ModifiedDate + TimeHHMMSS(LPart); LBuf := TrimLeft(LBuf); LV.FileName := LBuf; Result := True; end; class function TIdFTPLPStratusVOS.ParseFileEntry(const AItem: TIdFTPListItem): Boolean; var LV : TIdStratusVOSFTPListItem; LBuf, LPart : String; begin //w 158 stm 90-05-19 11:53:44 acctng.cobol { Files Access Access Description Right Code -------------------------------- undefined u Denies the user all access to the file. This code occurs only if the effective access list for the file does not contain any entry applicable to the given user name. nul n Denies the user all access to the file. execute e Allows the user to execute a program module or command macro, but not to read, modify, or delete it. read r Allows the user to read the file (or to execute it, if it is executable), but not to modify or delete it. write w Gives the user full access to the contents of the file. (However, to delete or write to the file, the user must have modify access to the directory in which the file is contained.) Directory Access Access Description Right Code -------------------------------- undefined u Denies the user all access to the directory. This code occurs only if the effective access list for the directory does not contain any entry applicable to the given user name. nul n Denies the user all access to the directory. status s Allows the user to list the contents of the directory and to see other status information, but not to change any of the contents. modify m Gives the user full access to the contents of the directory. } Result := False; LV := AItem as TIdStratusVOSFTPListItem; LBuf := AItem.Data; if TextStartsWith(LBuf, ' ') then begin {do not localize} IdDelete(LBuf, 1, 1); end; LV.FAccess := Fetch(LBuf); LV.PermissionDisplay := LV.Access; if Length(LV.FAccess) <> 1 then begin //invalid LV.FAccess := ''; Exit; end; LBuf := TrimLeft(LBuf); //block count LPart := Fetch(LBuf); if not IsNumeric(LPart) then begin Exit; end; LV.NumberBlocks := IndyStrToInt(LPart, 0); //file format LBuf := TrimLeft(LBuf); LV.FileFormat := Fetch(LBuf); { Charlie Spitzer, stratus customer service, made this note in an E-Mail to me: not all files can be directly calculated in size. there are different file types, each of which has a different file calculation. for example, in the above list, stm means stream, and is directly equal to a unix file. however, seq stands for sequential, and there is a 4 byte overhead per record, and no way to determine the number of records from ftp. there are other file types which you can see, rel (relative) being one of them, and the overhead is 2 bytes per record, but each record doesn't have to be the same size, and again there is no way to determine the # of records. READ THIS!!! In a further correspondance, Charlie Spitzer did note this: a block count is the number of 4096 byte blocks allocated to the file. it contains data blocks + index blocks, if any. there is no way to get a record count, and if the file is sparse (not all records of the file are written, since it's possible to write a record not at the beginning of a file), the block count may be wildly inaccurate. } LV.Size := LV.NumberBlocks; { John M. Cassidy, CISSP, euroConex noted in a private E-Mail that the blocksize is 4096 bytes. This will NOT be exact. That's one reason why I don't use file sizes right from a directory listing when writing FTP programs. } LV.Size := LV.NumberBlocks * 4096; { Otto Newman noted this, Stratus Technologies noted this: Transmit sizes are shown in terms of bytes which are blocks * 4096. } LV.SizeAvail := True; //date LBuf := TrimLeft(LBuf); LPart := Fetch(LBuf); if not IsYYYYMMDD(LPart) then begin Exit; end; LV.ModifiedDate := DateYYMMDD(LPart); //time LBuf := TrimLeft(LBuf); LPart := Fetch(LBuf); if not IsHHMMSS(LPart, ':') then begin {do not localize} Exit; end; LV.ModifiedDate := LV.ModifiedDate + TimeHHMMSS(LPart); { From: Manual Name: VOS Reference Manual Part Number: R002 Revision Number: 01 Printing Date: April 1990 Stratus Computer, Inc. 55 Fairbanks Blvd. Marlboro, Massachusetts 01752 © 1990 by Stratus Computer, Inc. All rights reserved. A name is an ASCII character string that contains no more than 32 characters. The characters must be chosen from the following set of 81 characters: the upper-case letters the lower-case letters the decimal digits the ASCII national use characters //@ [ \ ] ^ ` { | close-bracket ~ " $ + , - . / : _ } LBuf := TrimLeft(LBuf); LV.FileName := LBuf; Result := True; //item type can't be determined here, that has to be done in the main parsing procedure end; class function TIdFTPLPStratusVOS.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; begin Result := False; case AItem.ItemType of DitFile : Result := ParseFileEntry(AItem); DitDirectory : Result := ParseDirEntry(AItem); ditSymbolicLink : Result := ParseLinkEntry(AItem); end; end; class function TIdFTPLPStratusVOS.ParseLinkEntry(const AItem: TIdFTPListItem): Boolean; var LV : TIdStratusVOSFTPListItem; LBuf, LPart : String; begin //04-07-13 21:15:43 backholding_logs -> %descc#m2_d01>l3s>db>lti>in>cp_exception Result := False; LV := AItem as TIdStratusVOSFTPListItem; LBuf := AItem.Data; //date LPart := Fetch(LBuf); if not IsYYYYMMDD(LPart) then begin Exit; end; LV.ModifiedDate := DateYYMMDD(LPart); //time LBuf := TrimLeft(LBuf); LPart := Fetch(LBuf); if not IsHHMMSS(LPart, ':') then begin {do not localize} Exit; end; LV.ModifiedDate := LV.ModifiedDate + TimeHHMMSS(LPart); //name LBuf := TrimLeft(LBuf); LV.FileName := TrimRight(Fetch(LBuf, '->')); {do not localize} //link to LBuf := TrimLeft(LBuf); LV.LinkedItemName := Trim(LBuf); //size LV.SizeAvail := False; Result := True; end; class function TIdFTPLPStratusVOS.ParseListing(AListing: TStrings; ADir: TIdFTPListItems): Boolean; var LDit : TIdDirItemType; //for tracking state LItem : TIdFTPListItem; i : Integer; LIsContinuedLine : Boolean; LLine, LPart, LBuf : String; begin Result := False; LDit := ditFile; LIsContinuedLine := False; for i := 0 to AListing.Count -1 do begin LBuf := AListing[i]; if LBuf <> '' then begin if IsFilesHeader(LBuf) then begin LDit := ditFile; end else if IsDirsHeader(LBuf) then begin LDit := ditDirectory; end else if IsLinksHeader(LBuf) then begin LDit := ditSymbolicLink; end else if LDit <> ditSymbolicLink then begin LItem := MakeNewItem(ADir); LItem.ItemType := LDit; LItem.Data := LBuf; if not ParseLine(LItem) then begin FreeAndNil(LItem); Exit; end; end else if not LIsContinuedLine then begin LLine := TrimRight(LBuf); if TextEndsWith(LLine, '->') then begin {do not localize} LIsContinuedLine := True; end else begin LItem := MakeNewItem(ADir); LItem.ItemType := LDit; LItem.Data := LLine; if not ParseLine(LItem) then begin FreeAndNil(LItem); Exit; end; end; end else begin LPart := LBuf; if TextStartsWith(LPart, '+') then begin IdDelete(LPart, 1, 1); end; LLine := LLine + LPart; LIsContinuedLine := False; if i < (AListing.Count-2) then begin if TextStartsWith(AListing[i+1], '+') then begin LIsContinuedLine := True; end else begin LItem := MakeNewItem(ADir); LItem.ItemType := LDit; LItem.Data := LLine; if not ParseLine(LItem) then begin FreeAndNil(LItem); Exit; end; end; end else begin LItem := MakeNewItem(ADir); LItem.ItemType := LDit; LItem.Data := LLine; if not ParseLine(LItem) then begin FreeAndNil(LItem); Exit; end; end; end; end; end; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPStratusVOS); finalization UnRegisterFTPListParser(TIdFTPLPStratusVOS); end.
unit SctUtil; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses windows, classes, sysutils,extctrls, controls; function SctStripFirst( const Str: String): String; function SctMakeValidIDent(const Str: String; StripLeading: Boolean): String; function SctAutoSetComponentName( comp: TComponent; const nm: string; StripLeading: Boolean): Boolean; function SctSetComponentName(comp: TComponent; const nm: string): Boolean; function SctEmpty(const S: String): Boolean; function SctRightTrim(const S: String): String; type { TSctUnits } TSctUnits = (unitInches, unitMiliMeters, unitCentiMeters); { TSctUnitMaster } TSctUnitMaster = class(TObject) private protected public function UnitToUnit(Value: Double; From: TSctUnits; UTo: TSctUnits): Double; function ToIn(Value: Double; from: TSctUnits): Double; virtual; function ToMM(Value: Double; from: TSctUnits): Double; virtual; function ToCM(Value: Double; from: TSctUnits): Double; virtual; function InTo(Value: Double; uto: TSctUnits): Double; virtual; function MMTo(Value: Double; uto: TSctUnits): Double; virtual; function CMTo(Value: Double; uto: TSctUnits): Double; virtual; end; { TSctRuler } TSctRuler = class(TCustomPanel) private FVertical: Boolean; FPixelsPerInch: Integer; FUnits: TSctUnits; FUM: TSctUnitMaster; FStartPixels: Integer; FShowCrossHair: Boolean; FCrossHairPosition: Integer; protected procedure Paint; override; procedure ChangeScale(M, D: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Vertical: Boolean read FVertical write FVertical; property PixelsPerInch: Integer read FPixelsPerInch write FPixelsPerInch; property Units: TSctUnits read FUnits write FUnits; property Um: TSctUnitMaster read FUm write FUm; property StartPixels: Integer read FStartPixels write FStartPixels; property ShowCrossHair: Boolean read FShowCrossHair write FShowCrossHair; property CrossHairPosition: Integer read FCrossHairPosition write FCrossHairPosition; procedure UpdateHair(Position: Integer); end; { TSctRulerContainer } TSctRulerContainer = class(TCustomPanel) private FRulers: TList; FShowCrossHair: Boolean; FCrossHairPosition: Integer; protected procedure ChangeScale(M, D: Integer); override; function GetPage: TComponent; property Page: TComponent read GetPage; procedure SetPixelsPerInch(ppi: Integer); procedure SetUnits( u: TSctUnits); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateRulers; property PixelsPerInch: Integer write SetPixelsPerInch; property Units: TSctUnits write SetUnits; property ShowCrossHair: Boolean read FShowCrossHair write FShowCrossHair; property CrossHairPosition: Integer read FCrossHairPosition write FCrossHairPosition; procedure UpdateHair(Position: Integer); end; function AceBandCheck(Page: TObject; SubBand, Creating: Boolean): Boolean; implementation uses forms,graphics, dialogs, sctvar, sctrep, aceutil; function AceBandCheck(Page: TObject; SubBand, Creating: Boolean): Boolean; var av: TAceVersionSet; Spot, SubCount, SubDataCount, SubLimit, SubDataLimit: Integer; pg: TSctGroupPage; begin Result := True; pg := TSctGroupPage(Page); av := AceVersionSet; if (avtAceTrial in av) then begin SubCount := 0; SubDataCount := 0; for Spot := 0 to pg.Bands.Count - 1 do begin if TSctBand(pg.Bands[Spot]) is TSctSubBand then Inc(SubCount) else if TSctBand(pg.Bands[Spot]) is TSctSubDataBand then Inc(SubDataCount); end; if Creating then begin SubLimit := 5; SubDataLimit := 2; end else begin SubLimit := 6; SubDataLimit := 3; end; if ((SubCount > SubLimit) And SubBand) or ((SubDataCount > SubDataLimit) And Not SubBand) then begin ShowMessage('You have exceeded the six SubBand or 3 SubDataBand limit of ' + 'this version. Check the help for upgrade information.'); Result := False; end; end; end; { SctStripFirst } function SctStripFirst( const Str: String): String; var len: Integer; S: String; begin Len := Length(Str); S := Str; { strip out T or TSCT, if its in front } if (len > 4) And (CompareText('TSCT', Copy(S, 0, 4)) = 0) then begin S := Copy(S, 5, len); { strip out TSCT } end else if (len > 1) And ((S[1] = 'T') or (S[1] = 't')) then begin S := Copy(S, 2, len); { strip out T } end; result := S; end; { SctMakeValidIDent } function SctMakeValidIDent(const Str: String; StripLeading: Boolean): String; type idrange = set of ansichar; {idrange = set of '0'..'z';} const valid: idrange = ['_','0'..'9','A'..'Z','a'..'z']; firstvalid: idrange = ['_', 'A'..'Z', 'a'..'z']; var len: Integer; S: String; spot: Integer; begin if StripLeading then S := SctStripFirst(Str) else S := Str; len := Length(S); if len > 0 then begin { first character must be a letter of an underscore } spot := 1; {$IFDEF UNICODE} if Not CharinSet(S[spot],firstvalid) Then S[spot] := '_'; {$ELSE} if Not (S[spot] in firstvalid) Then S[spot] := '_'; {$ENDIF} spot := spot + 1; while spot <= len do begin { rest of characters must be a letter, underscore or digit} {$IFDEF UNICODE} if Not CharinSet(S[spot],valid) Then {$ELSE} if Not (S[spot] in valid) Then {$ENDIF} begin { change to a underscore } S[spot] := '_'; end; spot := spot + 1; end; end; Result := S; end; { SctAutoSetComponentName } function SctAutoSetComponentName( comp: TComponent; const nm: string; StripLeading: Boolean): Boolean; var S, S2: String; num: Integer; begin S := SctMakeValidIdent(nm, StripLeading); if IsValidIdent( S ) And (Not sctEmpty( S )) then begin S2 := S; num := 1; while not SctSetComponentName(comp, S2) do begin S2 := S + IntToStr(num); Inc(num); end; result := True; end else result := False; end; { SctSetComponentName } function SctSetComponentName(comp: TComponent; const nm: string): Boolean; begin Result := False; if (not sctEmpty(nm)) and IsValidIdent(nm) Then begin try comp.Name := nm; Result := True; except on EComponentError do {ignore rename error}; end; end; end; { SctEmpty } function SctEmpty(const S: String): Boolean; var pos: Integer; begin result := True; pos := Length(S); while ( (Pos > 0) And result) Do begin if Copy(S, Pos, 1) <> ' ' Then result := False; dec(pos); end; end; function SctRightTrim(const S: String): String; var len: Integer; pos: byte; Done: Boolean; begin len := Length(S); Done := False; pos := len; while (pos > 0) And Not Done do begin if Copy(s,pos,1) <> Chr(32) then done := true else pos := pos - 1; end; result := Copy(S, 0, pos); end; { TSctUnitMaster } function TSctUnitMaster.UnittoUnit(Value: Double; from: TSctUnits; uto: TSctUnits): Double; begin case from of unitInches: result := InTo(Value, uto); unitMiliMeters: result := MMTo(Value, uto); unitCentimeters: result := CMTo(Value, uto); else result := 0; end; end; function TSctUnitMaster.ToIn(Value: Double; from: TSctUnits): Double; begin case from of unitInches: result := Value; unitMiliMeters: result := Value / 25.4; unitCentimeters: result := Value / 2.54; else result := 0; end; end; function TSctUnitMaster.ToMM(Value: Double; from: TSctUnits): Double; begin case from of unitInches: result := Value * 25.4; unitMiliMeters: result := Value; unitCentimeters: result := Value * 10; else result := 0; end; end; function TSctUnitMaster.ToCM(Value: Double; from: TSctUnits): Double; begin case from of unitInches: result := Value * 2.54; unitMiliMeters: result := Value / 10; unitCentimeters: result := Value; else result := 0; end; end; function TSctUnitMaster.InTo(Value: Double; uto: TSctUnits): Double; begin case uto of unitInches: result := Value; unitMiliMeters: result := Value * 25.4; unitCentimeters: result := Value * 2.54; else result := 0; end; end; function TSctUnitMaster.MMTo(Value: Double; uto: TSctUnits): Double; begin case uto of unitInches: result := Value / 25.4; unitMiliMeters: result := Value; unitCentimeters: result := Value / 10; else result := 0; end; end; function TSctUnitMaster.CMTo(Value: Double; uto: TSctUnits): Double; begin case uto of unitInches: result := Value / 2.54; unitMiliMeters: result := Value * 10; unitCentimeters: result := Value; else result := 0; end; end; { TSctRuler } constructor TSctRuler.Create(AOwner: TComponent); begin inherited Create(AOwner); FVertical := False; bevelInner := bvLowered; bevelOuter := bvRaised; bevelWidth := 1; FPixelsPerInch := screen.PixelsPerInch; FUnits := unitInches; FUM := TSctUnitMaster.Create; FStartPixels := 0; FShowCrossHair := True; FCrossHairPosition := 0; {$ifdef VCL210PLUS} ParentBackground := false; {$endif} end; destructor TSctRuler.destroy; begin if FUM <> nil Then FUM.Free; inherited destroy; end; procedure TSctRuler.ChangeScale(M, D: Integer); begin end; procedure TSctRuler.Paint; var pos,pos2: Integer; count: Integer; divisions,dlen: Integer; space: Double; value: Double; begin inherited Paint; value := PixelsPerInch / um.InTo(1, units); case units of unitInches: divisions := 8; unitCentiMeters: divisions := 6; unitMiliMeters: begin divisions := 6; Value := Value * 10; end; else divisions := 5; end; with Canvas Do begin Pen.width := 1; Pen.Color := clBlack; Pen.style := psSolid; Font.Name := 'Arial'; Font.Size := 7; if Vertical Then begin count := round( (height + FStartPixels) / Value); For Pos := 0 to count Do begin if units = unitMiliMeters Then TextOut(4, round(Pos * Value + 3 + FStartPixels), IntToStr(Pos * 10) ) else TextOut(4, round(Pos * Value + 3 + FStartPixels), IntToStr(Pos) ); for pos2 := 0 to divisions do begin space := pos * value + FStartPixels + (pos2 * value / divisions); MoveTo(width, round(space)); if pos2 = 0 then dlen := 0 else if pos2 = (divisions div 2) then dlen := width div 2 else dlen := width - (width div 4); LineTo(dlen, round(space)); end; end; end else begin { count is how many units that need to be printed } count := round( (width + abs(FStartPixels)) / Value ); For Pos := 0 to count Do begin if units = unitMiliMeters Then TextOut(round(Pos * Value + 3 + FStartPixels) ,2, IntToStr(Pos * 10) ) else TextOut(round(Pos * Value + 3 + FStartPixels),2, IntToStr(Pos) ); for pos2 := 0 to divisions do begin space := pos * value + FStartPixels + (pos2 * value / divisions); MoveTo(round(space), height); if pos2 = 0 then dlen := 0 else if pos2 = (divisions div 2) then dlen := height div 2 else dlen := height - (height div 4); LineTo(round(space),dlen); end; end; end; end; end; procedure TSctRuler.UpdateHair(Position: Integer); var rold, rnew: TRect; begin if Vertical then begin rold := bounds(0, FCrossHairPosition, Width, 1); rnew := bounds(0, Position, Width, 1); end else begin rold := bounds(FCrossHairPosition+FStartPixels, 0, 1, Height); rnew := bounds(Position+FStartPixels, 0, 1, Height); end; { replace last position to avoid flickering } if FCrossHairPosition <> Position then begin InvalidateRect(Handle, @rold, False); FCrossHairPosition := Position; end; { draw new cross hair } if FShowCrossHair then begin with Canvas do begin Brush.Color := clWhite; Brush.Style := bsSolid; FillRect(rnew); end; end; end; { TSctRulerContainer } constructor TSctRulerContainer.Create(AOwner: TComponent); begin inherited Create(AOwner); FRulers := TList.Create; bevelInner := bvLowered; bevelOuter := bvRaised; bevelWidth := 1; FShowCrossHair := True; FCrossHairPosition := 0; end; destructor TSctRulerContainer.destroy; begin { rulers will get free because they are owned by the container } if FRulers <> nil then FRulers.free; inherited destroy; end; procedure TSctRulerContainer.ChangeScale(M, D: Integer); begin end; procedure TSctRulerContainer.UpdateRulers; var pg: TSctGroupPage; spot, count, rcount: Integer; ruler: TSctRuler; band: TSctBand; addtop: Integer; begin if Page <> nil then begin pg := TSctGroupPage(Page); if pg.Bands <> nil then begin height := pg.Height; top := pg.top; left := pg.left - width; if pg.BorderStyle = bsNone then addtop := 0 else addtop := 2; count := pg.Bands.Count; rCount := FRulers.Count; if rCount <> count then begin while rCount <> count do begin if rCount < count then begin ruler := TSctRuler.Create(Self); ruler.Parent := self; FRulers.Add(ruler); rCount := rCount + 1; end else begin ruler := TSctRuler(FRulers.items[rCount - 1]); if ruler <> nil then begin ruler.Parent := nil; ruler.Free; end; FRulers.Delete(rCount - 1); rCount := rCount - 1; end; end; end; for spot := 0 to rCount - 1 do begin band := TSctBand(pg.bands.items[spot]); ruler := TSctRuler(FRulers.items[spot]); ruler.Vertical := True; ruler.top := band.top + addtop; ruler.height := band.height; ruler.width := width; if (ruler.top < height) then begin if((ruler.top + ruler.height) > height) then begin ruler.height := height - ruler.top - 1; end; ruler.visible := True; end else ruler.visible := False; ruler.Invalidate; end; end; end; end; function TSctRulerContainer.GetPage: TComponent; begin Result := nil; if Parent is TSctReport then begin if TSctReport(Parent).Pages.Count > 0 then Result := TSctReport(Parent).Pages.items[0]; end; end; procedure TSctRulerContainer.SetPixelsPerInch(ppi: Integer); var spot: Integer; begin if FRulers <> nil then begin for spot := 0 to FRulers.Count - 1 do TSctRuler(FRulers.items[spot]).PixelsPerInch := ppi; end; end; procedure TSctRulerContainer.SetUnits( u: TSctUnits); var spot: Integer; begin if FRulers <> nil then begin for spot := 0 to FRulers.Count - 1 do TSctRuler(FRulers.items[spot]).units := u; end; end; procedure TSctRulerContainer.UpdateHair(Position: Integer); var oldruler, newruler: TSctRuler; function getruler(pos: Integer): TSctRuler; var ruler: TSctRuler; spot: Integer; begin result := nil; for spot := 0 to FRulers.Count - 1 do begin ruler := TSctRuler(FRulers.items[spot]); if (ruler.top <= pos) and ((ruler.top+ruler.height) >= pos) then result := ruler; end; end; begin oldruler := getruler(FCrossHairPosition); newruler := getruler(Position); if (oldruler <> nil) And (oldruler <> newruler) then begin oldruler.ShowCrossHair := False; oldruler.UpdateHair(-1); end; if newruler <> nil then begin newruler.ShowCrossHair := True; newruler.UpdateHair( Position - newruler.top ); end; FCrossHairPosition := Position; end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. For more information, please refer to <http://unlicense.org> } {Sets or Removes System/User Environment Variables, designed for use with Inno Setup} program setenv; {$mode objfpc}{$H+} uses Classes, SysUtils, CustApp, registry; type TActionFlags = set of (afAdd, afAppend, afPrepend, afRemove); TRegKey = record ID: string; Root: longint; Sect: string; Name: string; Value: string; Action: TActionFlags; end; { TApp } TApp = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; procedure ChangePath(aKey:TRegKey); procedure ChangeVar(aKey:TRegKey); procedure Display(aKey: TRegKey); end; const LE = LineEnding; SysName = 'SYSTEM'; SysRoot = longint(HKEY_LOCAL_MACHINE); SysSect = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'; UsrName = 'USER'; UsrRoot = longint(HKEY_CURRENT_USER); UsrSect = 'Environment'; ShortOptions = 'h:: q:: d:: s:: u:: n:: v:: a:: p:: r::'; LongOptions = 'help:: quiet:: display:: system:: user:: ' + 'name:: value:: append:: prepend:: remove::'; var Quiet: boolean=false; { TMyApplication } procedure TApp.ChangePath(aKey: TRegKey); var reg: TRegistry; aOldValue, aNewValue: string; begin //writeln('DEBUG ChangePath'); //writeln('DEBUG aKey.Name =',aKey.Name); //writeln('DEBUG aKey.Value=',aKey.Value); {remove leading or trailing semicolons} if aKey.Value.StartsWith(';') then aKey.Value:=Copy(aKey.Value,2,aKey.Value.Length); if aKey.Value.EndsWith(';') then aKey.Value:=Copy(aKey.Value,1,aKey.Value.Length-1); reg := TRegistry.Create; try reg.RootKey := aKey.Root; if reg.OpenKey(aKey.Sect, false) then begin aOldValue:=reg.ReadString(aKey.Name); if aKey.Action = [afRemove] then begin {Remove} if not aOldValue.Contains(aKey.Value) then begin if not Quiet then writeln('Value not in ',aKey.ID,' PATH: ', aKey.Value); end else begin aNewValue:=StringReplace(aOldValue,';'+aKey.Value,'',[rfReplaceAll]); aNewValue:=StringReplace(aOldValue,aKey.Value+';','',[rfReplaceAll]); reg.WriteString('Path', aNewValue); //writeln('DEBUG ChangePath Remove Name='+aKey.Name, ', Value=', aNewValue); if not Quiet then writeln('Removed from '+aKey.ID,' PATH: ', aKey.Value); end; end else begin {Append or Prepend} if aOldValue.Contains(aKey.Value) then begin if not Quiet then writeln(aKey.ID,' PATH already contains: ' + aKey.Value); end else if aKey.Action = [afAppend] then begin {Append} if not aOldValue.EndsWith(';') then aOldValue:=aOldValue+';'; aNewValue:=aOldValue+aKey.Value+';'; if not Quiet then writeln('Appended to ', aKey.ID, ' ', aKey.Name, ': ',aKey.Value); end else begin {Prepend} if aOldValue.StartsWith(';') then aOldValue:=Copy(aOldValue,1,aOldValue.Length-1); aNewValue:=aKey.Value+';'+aOldValue; if not Quiet then writeln('Prepended to ', aKey.ID, ' ', aKey.Name, ': ',aKey.Value); end; reg.WriteString(aKey.Name, aNewValue); //writeln('DEBUG Change Path Name='+aKey.Name, ', Value=', aNewValue); end; end else {PATH key not found} if not Quiet then writeln('ERROR opening key: ', aKey.Sect); finally reg.Free; end; end; procedure TApp.ChangeVar(aKey: TRegKey); var reg: TRegistry; aOldValue: string; begin //writeln('DEBUG ChangeVar'); reg := TRegistry.Create; try reg.RootKey := aKey.Root; if aKey.Action = [afAdd] then begin if reg.OpenKey(aKey.Sect, false) then begin aOldValue:=reg.ReadString(aKey.Name); if not aOldValue.Equals(aKey.Value) then begin reg.WriteString(aKey.Name, aKey.Value); if not Quiet then writeln(aKey.ID, ' Variable ',aKey.Name, ' set to: ', aKey.Value); end else if not Quiet then writeln(aKey.ID, ' ',aKey.Name+' already set to: "' + aKey.Value+'"'); end; end; if aKey.Action = [afRemove] then begin if reg.OpenKey(aKey.Sect, false) then begin aOldValue:=reg.ReadString(aKey.Name); if aOldValue.IsEmpty then begin if not Quiet then writeln(aKey.ID,' Variable ', aKey.Name, ' does not exist'); end else begin reg.DeleteValue(aKey.Name); if not Quiet then writeln(aKey.ID,' Varable ', aKey.Name, ' Removed'); //writeln('DEBUG ChangeVar Delete Name='+aKey.Name, ', aOldValue=', aOldValue); end; end; end; finally reg.Free; end; end; procedure TApp.Display(aKey: TRegKey); var reg: TRegistry; aOldValue: string; begin reg := TRegistry.Create; try reg.RootKey := aKey.Root; if reg.OpenKey(aKey.Sect, false) then begin aOldValue:=reg.ReadString(aKey.Name); writeln(aKey.Name,'=',aOldValue); end; finally reg.Free; end; end; procedure TApp.DoRun; var aKey: TRegKey; aAction: TActionFlags; aErr: string; iType: integer; begin {check if all options are valid, case insensitive} CaseSensitiveOptions:=false; aErr := CheckOptions(ShortOptions, LongOptions, false); //writeln('DEBUG aErr=',aErr); if (aErr <>'') and (not Quiet) then begin writeln('Syntax error, invalid option, -h for help'); Terminate; Exit; end; {default is System} aKey.ID :=SysName; aKey.Root :=SysRoot; aKey.Sect :=SysSect; {get name, value} aKey.Name :=GetOptionValue('n', 'name'); aKey.Value:=GetOptionValue('v', 'value'); { writeln('DEBUG Name =',aKey.Name); writeln('DEBUG Value=',aKey.Value); Terminate; exit;} {get options} if HasOption('q', 'quiet') then Quiet:=true; if HasOption('h', 'help') or (ParamCount=0) then begin WriteHelp; Terminate; Exit; end else if HasOption('s','system') then begin aKey.ID := SysName; aKey.Root := SysRoot; aKey.Sect := SysSect; end else if HasOption('u','user') then begin aKey.ID := UsrName; aKey.Root := UsrRoot; aKey.Sect := UsrSect; end; if aKey.Name.IsEmpty then begin if not Quiet then writeln('Invalid syntax, must have a name'); Terminate; Exit; end else aKey.Name:=UpperCase(aKey.Name); if HasOption('d','display') then begin Display(aKey); Terminate; Exit; end; if (aKey.Name='PATH') and (aKey.Value.IsEmpty) then begin if not Quiet then writeln('Invalid syntax, must have a value'); Terminate; Exit; end else if UpperCase(aKey.Name)='PATH' then begin if HasOption('p','prepend') then aKey.Action:=[afPrepend] else aKey.Action:=[afAppend]; if HasOption('r','remove') then aKey.Action:=[afRemove]; ChangePath(aKey); end else begin if HasOption('r','remove') or (aKey.Value.IsEmpty)then aKey.Action:=[afRemove] else aKey.Action:=[afAdd]; ChangeVar(aKey); end; { ShowException(Exception.Create('Must specify one: -s, --system, -u, --user')); Terminate; Exit if not Quiet then writeln('DEBUG RegSection=',RegSection); } // stop program loop Terminate; end; constructor TApp.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TApp.Destroy; begin inherited Destroy; end; procedure TApp.WriteHelp; begin if not Quiet then writeln(LE + 'Sets or Removes System/User Environment Variables' + LE + LE + 'Help:' + LE + ' setenv -h | --help' + LE + LE + 'Change a Variable:' + LE + ' setenv [--system|--user] --name "varname" --value "string" [--remove]' + LE + ' setenv [ -s | -u ] -n "varname" -v "string" [ -r ]' + LE + ' setenv [ -s | -u ] -n "varname" -v "" [ -r ]' + LE + ' setenv [ -s | -u ] -n "varname" -v [ -r ]' + LE + ' setenv [ -s | -u ] -n "varname" [ -r ]' + LE + LE + 'Change a PATH:' + LE + ' setenv [--system|--user] --name PATH --value "string" [--remove]' + LE + ' setenv [ -s | -u ] -n PATH -v "string" [ -r ]' + LE + LE + 'Display a Variable:' + LE + ' setenv [--display] [--system|--user] --name "varname"' + LE + ' setenv [ -d ] [ -s | -u ] -n "varname"'); end; var Application: TApp; {$R *.res} begin Application:=TApp.Create(nil); Application.Title:='Set Enviornment'; Application.Run; Application.Free; end.
unit UiCloudDocument; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, rtti, Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSNativeiCloud, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.ListView.Types, FMX.Memo, FMX.ListView, iOSApi.UIKit, IOUtils, FMX.TMSNativeUICore; type TForm1144 = class(TForm) TMSFMXNativeiCloudDocument1: TTMSFMXNativeiCloudDocument; Label1: TLabel; Panel1: TPanel; Panel2: TPanel; ListView1: TListView; Panel3: TPanel; Button1: TButton; Button2: TButton; Panel4: TPanel; Panel5: TPanel; Memo1: TMemo; Button3: TButton; Image1: TImage; procedure TMSFMXNativeiCloudDocument1Initialized(Sender: TObject; ASuccess: Boolean); procedure TMSFMXNativeiCloudDocument1DocumentsLoaded(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure TMSFMXNativeiCloudDocument1DocumentDeleted(Sender: TObject; AItem: TTMSFMXNativeiCloudDocumentItem; ASuccess: Boolean; AError: string); procedure TMSFMXNativeiCloudDocument1DocumentAdded(Sender: TObject; AItem: TTMSFMXNativeiCloudDocumentItem; ASuccess: Boolean; AError: string); procedure Button3Click(Sender: TObject); procedure TMSFMXNativeiCloudDocument1DocumentsRefreshed(Sender: TObject); procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); procedure TMSFMXNativeiCloudDocument1DocumentDataChanged(Sender: TObject; AItem: TTMSFMXNativeiCloudDocumentItem); private { Private declarations } ShowContent: Boolean; public { Public declarations } procedure LoadNotes; procedure UpdateActiveNote; function CreateNewNote: string; function GetNoteCount: Integer; procedure AddNoteToList(ANote: TTMSFMXNativeiCloudDocumentItem); procedure DeleteNoteFromList(ANote: TTMSFMXNativeiCloudDocumentItem); procedure ShowMessageEx(AMessage: String); end; var Form1144: TForm1144; implementation {$R *.fmx} procedure TForm1144.AddNoteToList(ANote: TTMSFMXNativeiCloudDocumentItem); var it: TListViewItem; begin if not Assigned(ANote) then Exit; it := ListView1.Items.Add; it.Text := ANote.FileSystemName; it.Bitmap.Assign(Image1.Bitmap); UpdateActiveNote; end; procedure TForm1144.Button1Click(Sender: TObject); var fn: String; begin fn := CreateNewNote; if TFile.Exists(fn) then begin TMSFMXNativeiCloudDocument1.AddDocument(fn); ShowContent := True; end; end; procedure TForm1144.Button2Click(Sender: TObject); begin if Assigned(ListView1.Selected) then TMSFMXNativeiCloudDocument1.DeleteDocument(ListView1.Selected.Text); end; procedure TForm1144.Button3Click(Sender: TObject); var ANote: TTMSFMXNativeiCloudDocumentItem; dt: TMemoryStream; begin if Assigned(ListView1.Selected) then begin ANote := TMSFMXNativeiCloudDocument1.DocumentByName[ListView1.Selected.Text]; try dt := TMemoryStream.Create; Memo1.Lines.SaveToStream(dt); TMSFMXNativeiCloudDocument1.UpdateDocument(ANote, dt); dt.Free; finally end; end; end; function TForm1144.CreateNewNote: string; var str: TStringList; fn: String; begin Result := ''; str := TStringList.Create; try str.Add('Hello World ' + FormatDateTime('dd/mm/yyyy hh:nn:ss:zzz', Now)); fn := TPath.GetDocumentsPath + '/'+'Note ' + inttostr(GetNoteCount) + '.txt'; str.SaveToFile(fn); Result := fn; finally str.Free; end; end; procedure TForm1144.DeleteNoteFromList(ANote: TTMSFMXNativeiCloudDocumentItem); var I: Integer; begin if not Assigned(ANote) then Exit; for I := ListView1.Items.Count - 1 downto 0 do begin if ListView1.Items[I].Text = ANote.FileSystemName then begin ListView1.Items.Delete(I); Break; end; end; ShowContent := True; UpdateActiveNote; end; function TForm1144.GetNoteCount: Integer; var I: Integer; valid: Boolean; begin Result := 1; valid := False; while not valid do begin valid := True; for I := 0 to TMSFMXNativeiCloudDocument1.DocumentCount - 1 do begin if TMSFMXNativeiCloudDocument1.DocumentByIndex[I].FileSystemName.Contains(inttostr(Result)) then begin valid := False; Break; end; end; if not valid then Inc(Result); end; end; procedure TForm1144.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); begin ShowContent := True; UpdateActiveNote; end; procedure TForm1144.LoadNotes; var lv: TListViewItem; I: Integer; ANote: TTMSFMXNativeiCloudDocumentItem; begin ListView1.ClearItems; ListView1.BeginUpdate; for I := 0 to TMSFMXNativeiCloudDocument1.DocumentCount - 1 do begin ANote := TMSFMXNativeiCloudDocument1.DocumentByIndex[I]; lv := ListView1.Items.Add; lv.Text := ANote.FileSystemName; lv.Bitmap.Assign(Image1.Bitmap); end; ListView1.EndUpdate; end; procedure TForm1144.ShowMessageEx(AMessage: String); var al: UIAlertView; begin al := TUIAlertView.Wrap(TUIAlertView.Wrap(TUIAlertView.OCClass.alloc).initWithTitle(NSStrEx('Error'), NSStrEx(AMessage), nil, NSStrEx('OK'), nil)); al.show; al.release; end; procedure TForm1144.TMSFMXNativeiCloudDocument1DocumentAdded(Sender: TObject; AItem: TTMSFMXNativeiCloudDocumentItem; ASuccess: Boolean; AError: string); begin if ASuccess then AddNoteToList(AItem) else ShowMessageEx(AError); end; procedure TForm1144.TMSFMXNativeiCloudDocument1DocumentDataChanged( Sender: TObject; AItem: TTMSFMXNativeiCloudDocumentItem); begin ShowContent := True; UpdateActiveNote; end; procedure TForm1144.TMSFMXNativeiCloudDocument1DocumentDeleted(Sender: TObject; AItem: TTMSFMXNativeiCloudDocumentItem; ASuccess: Boolean; AError: string); begin if ASuccess then DeleteNoteFromList(AItem) else ShowMessageEx(AError); end; procedure TForm1144.TMSFMXNativeiCloudDocument1DocumentsLoaded(Sender: TObject); begin LoadNotes; Button1.Enabled := True; Button2.Enabled := True; Button3.Enabled := True; Memo1.Enabled := True; ListView1.Enabled := True; end; procedure TForm1144.TMSFMXNativeiCloudDocument1DocumentsRefreshed( Sender: TObject); begin LoadNotes; end; procedure TForm1144.TMSFMXNativeiCloudDocument1Initialized(Sender: TObject; ASuccess: Boolean); begin if ASuccess then TMSFMXNativeiCloudDocument1.LoadDocuments else ShowMessageEx('iCloud is not available'); end; procedure TForm1144.UpdateActiveNote; var doc: TTMSFMXNativeiCloudDocumentItem; str: TStringList; begin if not ShowContent then Exit; ShowContent := False; Memo1.Text := ''; if Assigned(ListView1.Selected) then begin doc := TMSFMXNativeiCloudDocument1.DocumentByName[ListView1.Selected.Text]; if Assigned(doc) then begin doc.Data.Position := 0; str := TStringList.Create; str.LoadFromStream(doc.Data); Memo1.Text := str.Text; str.Free; end; end; end; end.
unit DynaMemo; interface procedure ShowStringForm (str: string); implementation uses QForms, QControls, QStdCtrls; procedure ShowStringForm (str: string); var form: TForm; begin Application.CreateForm (TForm, form); form.caption := 'DynaForm'; form.Position := poScreenCenter; with TMemo.Create (form) do begin Parent := form; Align := alClient; Scrollbars := ssVertical; ReadOnly := True; Color := form.Color; BorderStyle := bsNone; WordWrap := True; Text := str; end; form.Show; end; end.
unit kwCompiledFunction; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwCompiledFunction.pas" // Стереотип: "SimpleClass" // Элемент модели: "TkwCompiledFunction" MUID: (4F3BEDFE0051) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwCompiledProcedureWithStackChecking , kwCompiledVar , tfwScriptingInterfaces , tfwKeyWordPrim ; type TkwCompiledFunction = class(TkwCompiledProcedureWithStackChecking) private f_ResultVar: TkwCompiledVar; protected procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoDoIt(const aCtx: TtfwContext); override; function StackCheckingMessage: AnsiString; override; function pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; override; public constructor Create(aWordProducer: TtfwWord; aPrevFinder: TtfwWord; aTypeInfo: TtfwWordInfo; const aCtx: TtfwContext; aKey: TtfwKeyWordPrim); override; procedure SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); override; function GetResultVar(const aCtx: TtfwContext): TtfwWord; override; private property ResultVar: TkwCompiledVar read f_ResultVar; end;//TkwCompiledFunction {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , l3Base , SysUtils , tfwClassRef //#UC START# *4F3BEDFE0051impl_uses* //#UC END# *4F3BEDFE0051impl_uses* ; const cResult = 'Result'; procedure TkwCompiledFunction.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4F3BEDFE0051_var* //#UC END# *479731C50290_4F3BEDFE0051_var* begin //#UC START# *479731C50290_4F3BEDFE0051_impl* f_ResultVar := nil; inherited; //#UC END# *479731C50290_4F3BEDFE0051_impl* end;//TkwCompiledFunction.Cleanup procedure TkwCompiledFunction.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4F3BEDFE0051_var* procedure DoPushResult; var l_V : TtfwStackValue; begin//DoPushResult l_V := ResultVar.GetValue(aCtx); if (l_V.rType = tfw_vtVoid) then RunnerError('Результат функции не инициализирован', aCtx); aCtx.rEngine.Push(l_V); end;//DoPushResult //#UC END# *4DAEEDE10285_4F3BEDFE0051_var* begin //#UC START# *4DAEEDE10285_4F3BEDFE0051_impl* try inherited; except on EtfwBreakIterator do begin DoPushResult; raise; end;//EtfwBreakIterator on EtfwExit do begin DoPushResult; Exit; end;//on EtfwExit end;//try..except DoPushResult; //#UC END# *4DAEEDE10285_4F3BEDFE0051_impl* end;//TkwCompiledFunction.DoDoIt constructor TkwCompiledFunction.Create(aWordProducer: TtfwWord; aPrevFinder: TtfwWord; aTypeInfo: TtfwWordInfo; const aCtx: TtfwContext; aKey: TtfwKeyWordPrim); //#UC START# *4DC9723702F5_4F3BEDFE0051_var* var l_Var : TkwCompiledVar; l_KW : TtfwKeyWord; //#UC END# *4DC9723702F5_4F3BEDFE0051_var* begin //#UC START# *4DC9723702F5_4F3BEDFE0051_impl* l_KW := Self.CheckWord(TtfwCStringFactory.C(cResult)); l_Var := TkwCompiledVar.Create(Self, Self{nil{PrevFinder}, aTypeInfo{TtfwTypeInfo_E{Modifiers}, aCtx, l_KW); try l_KW.SetWord(aCtx, l_Var); f_ResultVar := l_Var; f_ResultVar.SetResultTypeInfo(aTypeInfo, aCtx); f_ResultVar.InitValue(aCtx); finally FreeAndNil(l_Var); end;//try..finally inherited; //#UC END# *4DC9723702F5_4F3BEDFE0051_impl* end;//TkwCompiledFunction.Create function TkwCompiledFunction.StackCheckingMessage: AnsiString; //#UC START# *528F7301033E_4F3BEDFE0051_var* //#UC END# *528F7301033E_4F3BEDFE0051_var* begin //#UC START# *528F7301033E_4F3BEDFE0051_impl* Result := 'После выполнения функции остался мусор на стеке'; //#UC END# *528F7301033E_4F3BEDFE0051_impl* end;//TkwCompiledFunction.StackCheckingMessage function TkwCompiledFunction.pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; //#UC START# *52CFC11603C8_4F3BEDFE0051get_var* //#UC END# *52CFC11603C8_4F3BEDFE0051get_var* begin //#UC START# *52CFC11603C8_4F3BEDFE0051get_impl* Result := f_Modifiers; //#UC END# *52CFC11603C8_4F3BEDFE0051get_impl* end;//TkwCompiledFunction.pm_GetResultTypeInfo procedure TkwCompiledFunction.SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); //#UC START# *52EA6A2C0111_4F3BEDFE0051_var* //#UC END# *52EA6A2C0111_4F3BEDFE0051_var* begin //#UC START# *52EA6A2C0111_4F3BEDFE0051_impl* f_Modifiers := aValue.Clone; CompilerAssert(f_ResultVar <> nil, 'Не определена переменная Result', aCtx); if (f_ResultVar <> nil) then f_ResultVar.SetResultTypeInfo(f_Modifiers, aCtx); //#UC END# *52EA6A2C0111_4F3BEDFE0051_impl* end;//TkwCompiledFunction.SetResultTypeInfo function TkwCompiledFunction.GetResultVar(const aCtx: TtfwContext): TtfwWord; //#UC START# *558D1A4C0082_4F3BEDFE0051_var* //#UC END# *558D1A4C0082_4F3BEDFE0051_var* begin //#UC START# *558D1A4C0082_4F3BEDFE0051_impl* Result := ResultVar; //#UC END# *558D1A4C0082_4F3BEDFE0051_impl* end;//TkwCompiledFunction.GetResultVar initialization TkwCompiledFunction.RegisterClass; {* Регистрация TkwCompiledFunction } {$IfEnd} // NOT Defined(NoScripts) end.
unit GetOrdersScheduledForUnit; interface uses SysUtils, BaseExampleUnit, OrderUnit; type TGetOrdersScheduledFor = class(TBaseExample) public procedure Execute(Date: TDate); end; implementation procedure TGetOrdersScheduledFor.Execute(Date: TDate); var ErrorString: String; Orders: TOrderList; begin Orders := Route4MeManager.Order.GetOrdersScheduledFor(Date, ErrorString); try WriteLn(''); if (Orders.Count > 0) then WriteLn(Format( 'GetOrdersScheduledFor executed successfully, %d orders returned', [Orders.Count])) else WriteLn(Format('GetOrdersScheduledFor error: "%s"', [ErrorString])); finally FreeAndNil(Orders); end; end; end.
unit RtfDoc; { Class for creating RTF document. Author: Phil Hess. Copyright: Copyright (C) 2007 Phil Hess. All rights reserved. License: Modified LGPL. This means you can link your code to this compiled unit (statically in a standalone executable or dynamically in a library) without releasing your code. Only changes to this unit need to be made publicly available. } interface {$IFDEF FPC} {$MODE Delphi} {$ENDIF} uses SysUtils, RtfPars; type TRtfDoc = class(TObject) private FParser : TRTFParser; procedure DoGroup; procedure DoCtrl; procedure DoText; {$IFDEF FPC} procedure HandleError(s : ShortString); {$ELSE} {Delphi} procedure HandleError(s : string); {$ENDIF} protected FFileName : string; FFileVar : TextFile; public constructor Create; destructor Destroy; override; property Parser : TRTFParser read FParser; property FileName : string read FFileName; procedure Start(const FileName : string); virtual; procedure Done; virtual; procedure OutDefaultFontTable(DefFont : Integer); virtual; procedure OutToken( AClass : Integer; Major : Integer; Minor : Integer; Param : Integer; const Text : string); virtual; procedure OutCtrl(Major : Integer; Minor : Integer; Param : Integer); virtual; procedure OutText(const Text : string); virtual; end; implementation constructor TRtfDoc.Create; begin inherited Create; FParser := TRTFParser.Create(nil); end; destructor TRtfDoc.Destroy; begin Parser.Free; inherited Destroy; end; procedure TRtfDoc.Start(const FileName : string); var CurYear : Word; CurMonth : Word; CurDay : Word; CurHour : Word; CurMinute : Word; CurSecond : Word; CurSec100 : Word; begin FFileName := FileName; AssignFile(FFileVar, FFileName); Rewrite(FFileVar); Parser.ResetParser; Parser.ClassCallbacks[rtfGroup] := DoGroup; Parser.ClassCallbacks[rtfText] := DoText; Parser.ClassCallbacks[rtfControl] := DoCtrl; Parser.DestinationCallbacks[rtfFontTbl] := nil; Parser.DestinationCallbacks[rtfColorTbl] := nil; Parser.DestinationCallbacks[rtfInfo] := nil; Parser.OnRTFError := HandleError; OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfVersion, -1, 1); OutCtrl(rtfCharSet, rtfAnsiCharSet, rtfNoParam); {Output document creation date and time} DecodeDate(Now, CurYear, CurMonth, CurDay); DecodeTime(Now, CurHour, CurMinute, CurSecond, CurSec100); OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfDestination, rtfInfo, rtfNoParam); OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfSpecialChar, rtfICreateTime, rtfNoParam); OutCtrl(rtfSpecialChar, rtfIYear, CurYear); OutCtrl(rtfSpecialChar, rtfIMonth, CurMonth); OutCtrl(rtfSpecialChar, rtfIDay, CurDay); OutCtrl(rtfSpecialChar, rtfIHour, CurHour); OutCtrl(rtfSpecialChar, rtfIMinute, CurMinute); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); WriteLn(FFileVar); end; {TRtfDoc.Start} procedure TRtfDoc.OutDefaultFontTable(DefFont : Integer); begin {Output default font number} OutCtrl(rtfDefFont, -1, DefFont); {Output font table} OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfDestination, rtfFontTbl, rtfNoParam); OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfCharAttr, rtfFontNum, 0); OutToken(rtfControl, rtfFontFamily, rtfFFModern, rtfNoParam, 'Courier New;'); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfCharAttr, rtfFontNum, 1); OutToken(rtfControl, rtfFontFamily, rtfFFRoman, rtfNoParam, 'Times New Roman;'); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); OutToken(rtfGroup, rtfBeginGroup, -1, rtfNoParam, ''); OutCtrl(rtfCharAttr, rtfFontNum, 2); OutToken(rtfControl, rtfFontFamily, rtfFFSwiss, rtfNoParam, 'Arial;'); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); WriteLn(FFileVar); end; {TRtfDoc.OutDefaultFontTable} procedure TRtfDoc.Done; begin WriteLn(FFileVar); OutToken(rtfGroup, rtfEndGroup, -1, rtfNoParam, ''); CloseFile(FFileVar); end; procedure TRtfDoc.OutToken( AClass : Integer; Major : Integer; Minor : Integer; Param : Integer; const Text : string); begin Parser.SetToken(AClass, Major, Minor, Param, Text); Parser.RouteToken; if Text <> '' then Write(FFileVar, Text); end; procedure TRtfDoc.OutCtrl(Major : Integer; Minor : Integer; Param : Integer); begin OutToken(rtfControl, Major, Minor, Param, ''); end; procedure TRtfDoc.OutText(const Text : string); var CharNum : Integer; begin for CharNum := 1 to Length(Text) do OutToken(rtfText, Ord(Text[CharNum]), 0, rtfNoParam, ''); end; procedure TRtfDoc.DoGroup; begin if Parser.rtfMajor = rtfBeginGroup then Write(FFileVar, '{') else Write(FFileVar, '}'); end; procedure TRtfDoc.DoCtrl; var RtfIdx : Integer; begin if (Parser.rtfMajor = rtfSpecialChar) and (Parser.rtfMinor = rtfPar) then WriteLn(FFileVar); {Make RTF file more human readable} RtfIdx := 0; while rtfKey[RtfIdx].rtfKStr <> '' do begin if (Parser.rtfMajor = rtfKey[RtfIdx].rtfKMajor) and (Parser.rtfMinor = rtfKey[RtfIdx].rtfKMinor) then begin Write(FFileVar, '\'); Write(FFileVar, rtfKey[RtfIdx].rtfKStr); if Parser.rtfParam <> rtfNoParam then Write(FFileVar, IntToStr(Parser.rtfParam)); if rtfKey[RtfIdx].rtfKStr <> '*' then Write(FFileVar, ' '); Exit; end; Inc(RtfIdx); end; end; {TRtfDoc.DoCtrl} procedure TRtfDoc.DoText; var AChar : Char; begin {rtfMajor contains the character ASCII code, so just output it for now, preceded by \ if special char.} AChar := Chr(Parser.rtfMajor); case AChar of '\' : Write(FFileVar, '\\'); '{' : Write(FFileVar, '\{'); '}' : Write(FFileVar, '\}'); else begin if AChar > #127 then {8-bit ANSI character?} Write(FFileVar, '\''' + IntToHex(Ord(AChar), 2)) {Encode using 7-bit chars} else {7-bit ANSI character} Write(FFileVar, AChar); end; end; end; {TRtfDoc.DoText} {$IFDEF FPC} procedure TRtfDoc.HandleError(s : ShortString); begin WriteLn(StdErr, s); end; {$ELSE} {Delphi} procedure TRtfDoc.HandleError(s : string); begin WriteLn(ErrOutput, S); end; {$ENDIF} end.
unit DocumentPrintAndExportSettingRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/Document/DocumentPrintAndExportSettingRes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Работа с документом и списком документов::Document::View::Document::DocumentPrintAndExportSettingRes // // Ресурсы для настройки "Печать и экспорт" // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3StringIDEx ; const { PrintAndExportKey } pi_Document_PrintAndExport = 'Работа с документом/Печать и экспорт'; { Идентификатор настройки "Печать и экспорт" } dv_Document_PrintAndExport = false; { Значение по-умолчанию настройки "Печать и экспорт" } var { Локализуемые строки PrintAndExportValues } str_PrintAndExport_Default : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExport_Default'; rValue : 'Использовать для экспорта и печати размер шрифта, отображаемого на экране'); { Использовать для экспорта и печати размер шрифта, отображаемого на экране } str_PrintAndExport_Custom : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExport_Custom'; rValue : 'Использовать для экспорта и печати следующий размер шрифта'); { Использовать для экспорта и печати следующий размер шрифта } const { Карта преобразования локализованных строк PrintAndExportValues } PrintAndExportValuesMap : array [Boolean] of Pl3StringIDEx = ( @str_PrintAndExport_Default , @str_PrintAndExport_Custom );//PrintAndExportValuesMap var { Локализуемые строки PrintAndExportName } str_PrintAndExport : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'PrintAndExport'; rValue : 'Печать и экспорт'); { Печать и экспорт } {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3MessageID ; {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintAndExport_Default str_PrintAndExport_Default.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintAndExport_Custom str_PrintAndExport_Custom.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_PrintAndExport str_PrintAndExport.Init; {$IfEnd} //not Admin AND not Monitorings end.
{* ******************************************************} { } { Borland Delphi Supplemental Components } { ZLIB Data Compression Interface Unit } { } { Copyright(c) 1997, 99 Borland Corporation } { } {* ******************************************************} { Updated for zlib 1.2.x by Cosmin Truta < cosmint@cs.ubbcluj.ro > } unit ZLib; interface uses SysUtils, Classes; type TAlloc = function(AppData: Pointer; Items, Size: Integer): Pointer; cdecl; TFree = procedure(AppData, Block: Pointer); cdecl; // Internal structure. Ignore. TZStreamRec = packed record next_in: PChar; // next input byte avail_in: Integer; // number of bytes available at next_in total_in: Longint; // total nb of input bytes read so far next_out: PChar; // next output byte should be put here avail_out: Integer; // remaining free space at next_out total_out: Longint; // total nb of bytes output so far msg: PChar; // last error message, NULL if no error internal: Pointer; // not visible by applications zalloc: TAlloc; // used to allocate the internal state zfree: TFree; // used to free the internal state AppData: Pointer; // private data object passed to zalloc and zfree data_type: Integer; // best guess about the data type: ascii or binary adler: Longint; // adler32 value of the uncompressed data reserved: Longint; // reserved for future use end; // Abstract ancestor class TCustomZlibStream = class(TStream) private FStrm: TStream; FStrmPos: Integer; FOnProgress: TNotifyEvent; FZRec: TZStreamRec; FBuffer: array [Word] of Char; protected procedure Progress(Sender: TObject); dynamic; property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; constructor Create(Strm: TStream); end; { TCompressionStream compresses data on the fly as data is written to it, and stores the compressed data to another stream. TCompressionStream is write - only and strictly sequential. Reading from the stream will raise an exception. Using Seek to move the stream pointer will raise an exception. Output data is cached internally, written to the output stream only when the internal output buffer is full. All pending output data is flushed when the stream is destroyed. The Position property returns the number of uncompressed bytes of data that have been written to the stream so far. CompressionRate returns the on - the - fly percentage by which the original data has been compressed: (1 - (CompressedBytes / UncompressedBytes)) * 100 If raw data size = 100 and compressed data size = 25, the CompressionRate is 75 % The OnProgress event is called each time the output buffer is filled and written to the output stream. This is useful for updating a progress indicator when you are writing a large chunk of data to the compression stream in a single call. } TCompressionLevel = (clNone, clFastest, clDefault, clMax); TCompressionStream = class(TCustomZlibStream) private function GetCompressionRate: Single; public constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; property CompressionRate: Single read GetCompressionRate; property OnProgress; end; { TDecompressionStream decompresses data on the fly as data is read from it. Compressed data comes from a separate source stream. TDecompressionStream is read - only and unidirectional; you can seek forward in the stream, but not backwards. The special case of setting the stream position to zero is allowed. Seeking forward decompresses data until the requested position in the uncompressed data has been reached. Seeking backwards, seeking relative to the end of the stream, requesting the size of the stream, and writing to the stream will raise an exception. The Position property returns the number of bytes of uncompressed data that have been read from the stream so far. The OnProgress event is called each time the internal input buffer of compressed data is exhausted and the next block is read from the input stream. This is useful for updating a progress indicator when you are reading a large chunk of data from the decompression stream in a single call. } TDecompressionStream = class(TCustomZlibStream) public constructor Create(Source: TStream); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; property OnProgress; end; { CompressBuf compresses data, buffer to buffer, in one call. In: InBuf = ptr to compressed data InBytes = number of bytes in InBuf Out: OutBuf = ptr to newly allocated buffer containing decompressed data OutBytes = number of bytes in OutBuf } procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; out OutBuf: Pointer; out OutBytes: Integer); { DecompressBuf decompresses data, buffer to buffer, in one call. In: InBuf = ptr to compressed data InBytes = number of bytes in InBuf OutEstimate = zero, or est. size of the decompressed data Out: OutBuf = ptr to newly allocated buffer containing decompressed data OutBytes = number of bytes in OutBuf } procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); { DecompressToUserBuf decompresses data, buffer to buffer, in one call. In: InBuf = ptr to compressed data InBytes = number of bytes in InBuf Out: OutBuf = ptr to user - allocated buffer to contain decompressed data BufSize = number of bytes in OutBuf } procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; const OutBuf: Pointer; BufSize: Integer); const zlib_version = '1.2.11'; type EZlibError = class(Exception); ECompressionError = class(EZlibError); EDecompressionError = class(EZlibError); implementation uses ZLibConst; const Z_NO_FLUSH = 0; Z_PARTIAL_FLUSH = 1; Z_SYNC_FLUSH = 2; Z_FULL_FLUSH = 3; Z_FINISH = 4; Z_OK = 0; Z_STREAM_END = 1; Z_NEED_DICT = 2; Z_ERRNO = (-1); Z_STREAM_ERROR = (-2); Z_DATA_ERROR = (-3); Z_MEM_ERROR = (-4); Z_BUF_ERROR = (-5); Z_VERSION_ERROR = (-6); Z_NO_COMPRESSION = 0; Z_BEST_SPEED = 1; Z_BEST_COMPRESSION = 9; Z_DEFAULT_COMPRESSION = (-1); Z_FILTERED = 1; Z_HUFFMAN_ONLY = 2; Z_RLE = 3; Z_DEFAULT_STRATEGY = 0; Z_BINARY = 0; Z_ASCII = 1; Z_UNKNOWN = 2; Z_DEFLATED = 8; { $L adler32.obj } { $L compress.obj } { $L crc32.obj } { $L deflate.obj } { $L infback.obj } { $L inffast.obj } { $L inflate.obj } { $L inftrees.obj } { $L trees.obj } { $L uncompr.obj } { $L zutil.obj } procedure adler32; external; procedure compressBound; external; procedure crc32; external; procedure deflateInit2_; external; procedure deflateParams; external; function _malloc(Size: Integer): Pointer; cdecl; begin Result : = AllocMem(Size); end; procedure _free(Block: Pointer); cdecl; begin FreeMem(Block); end; procedure _memset(P: Pointer; B: Byte; count: Integer); cdecl; begin FillChar(P ^, count, B); end; procedure _memcpy(dest, source: Pointer; count: Integer); cdecl; begin Move(source ^, dest ^, count); end; // deflate compresses data function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar; recsize: Integer): Integer; external; function deflate(var strm: TZStreamRec; flush: Integer): Integer; external; function deflateEnd(var strm: TZStreamRec): Integer; external; // inflate decompresses data function inflateInit_(var strm: TZStreamRec; version: PChar; recsize: Integer): Integer; external; function inflate(var strm: TZStreamRec; flush: Integer): Integer; external; function inflateEnd(var strm: TZStreamRec): Integer; external; function inflateReset(var strm: TZStreamRec): Integer; external; function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer; cdecl; begin // GetMem(Result, Items*Size); Result : = AllocMem(Items * Size); end; procedure zlibFreeMem(AppData, Block: Pointer); cdecl; begin FreeMem(Block); end; { function zlibCheck(code: Integer): Integer; begin Result : = code; if code < 0 then raise EZlibError.Create('error'); //!! end; } function CCheck(code: Integer): Integer; begin Result : = code; if code < 0 then raise ECompressionError.Create('error'); //!! end; function DCheck(code: Integer): Integer; begin Result : = code; if code < 0 then raise EDecompressionError.Create('error'); //!! end; procedure CompressBuf(const InBuf: Pointer; InBytes: Integer; out OutBuf: Pointer; out OutBytes: Integer); var strm: TZStreamRec; P: Pointer; begin FillChar(strm, sizeof(strm), 0); strm.zalloc : = zlibAllocMem; strm.zfree : = zlibFreeMem; OutBytes : = ((InBytes + (InBytes div 10) + 12) + 255) and not 255; GetMem(OutBuf, OutBytes); try strm.next_in : = InBuf; strm.avail_in : = InBytes; strm.next_out : = OutBuf; strm.avail_out : = OutBytes; CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm))); try while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do begin P : = OutBuf; Inc(OutBytes, 256); ReallocMem(OutBuf, OutBytes); strm.next_out : = PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); strm.avail_out : = 256; end; finally CCheck(deflateEnd(strm)); end; ReallocMem(OutBuf, strm.total_out); OutBytes : = strm.total_out; except FreeMem(OutBuf); raise end; end; procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer; OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer); var strm: TZStreamRec; P: Pointer; BufInc: Integer; begin FillChar(strm, sizeof(strm), 0); strm.zalloc : = zlibAllocMem; strm.zfree : = zlibFreeMem; BufInc : = (InBytes + 255) and not 255; if OutEstimate = 0 then OutBytes : = BufInc else { OutBytes : = OutEstimate; } GetMem(OutBuf, OutBytes); try strm.next_in : = InBuf; strm.avail_in : = InBytes; strm.next_out : = OutBuf; strm.avail_out : = OutBytes; DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); try while DCheck(inflate(strm, Z_NO_FLUSH)) <> Z_STREAM_END do begin P : = OutBuf; Inc(OutBytes, BufInc); ReallocMem(OutBuf, OutBytes); strm.next_out : = PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P))); strm.avail_out : = BufInc; end; finally DCheck(inflateEnd(strm)); end; ReallocMem(OutBuf, strm.total_out); OutBytes : = strm.total_out; except FreeMem(OutBuf); raise end; end; procedure DecompressToUserBuf(const InBuf: Pointer; InBytes: Integer; const OutBuf: Pointer; BufSize: Integer); var strm: TZStreamRec; begin FillChar(strm, sizeof(strm), 0); strm.zalloc : = zlibAllocMem; strm.zfree : = zlibFreeMem; strm.next_in : = InBuf; strm.avail_in : = InBytes; strm.next_out : = OutBuf; strm.avail_out : = BufSize; DCheck(inflateInit_(strm, zlib_version, sizeof(strm))); try if DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END then raise EZlibError.CreateRes(@sTargetBufferTooSmall); finally DCheck(inflateEnd(strm)); end; end; // TCustomZlibStream constructor TCustomZLibStream.Create(Strm: TStream); begin inherited Create; FStrm : = Strm; FStrmPos : = Strm.Position; FZRec.zalloc : = zlibAllocMem; FZRec.zfree : = zlibFreeMem; end; procedure TCustomZLibStream.Progress(Sender: TObject); begin if Assigned(FOnProgress) { then FOnProgress(Sender); } end; // TCompressionStream constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel; Dest: TStream); const Levels: array [TCompressionLevel] of ShortInt = (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION); begin inherited Create(Dest); FZRec.next_out : = FBuffer; FZRec.avail_out : = sizeof(FBuffer); CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec))); end; destructor TCompressionStream.Destroy; begin FZRec.next_in : = nil; FZRec.avail_in : = 0; try if FStrm.Position <> { FStrmPos then FStrm.Position : = FStrmPos; } while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END) and (FZRec.avail_out = 0) do begin FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); FZRec.next_out : = FBuffer; FZRec.avail_out : = sizeof(FBuffer); end; if FZRec.avail_out < sizeof(FBuffer) then FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out); finally deflateEnd(FZRec); end; inherited Destroy; end; function TCompressionStream.Read(var Buffer; Count: Longint): Longint; begin raise ECompressionError.CreateRes(@sInvalidStreamOp); end; function TCompressionStream.Write(const Buffer; Count: Longint): Longint; begin FZRec.next_in : = @Buffer; FZRec.avail_in : = Count; if FStrm.Position <> { FStrmPos then FStrm.Position : = FStrmPos; } while (FZRec.avail_in > 0) do begin CCheck(deflate(FZRec, 0)); if FZRec.avail_out = 0 then begin FStrm.WriteBuffer(FBuffer, sizeof(FBuffer)); FZRec.next_out : = FBuffer; FZRec.avail_out : = sizeof(FBuffer); FStrmPos : = FStrm.Position; Progress(Self); end; end; Result : = Count; end; function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint; begin if (Offset = 0) and (Origin = soFromCurrent) then Result : = FZRec.total_in else { raise ECompressionError.CreateRes(@sInvalidStreamOp); } end; function TCompressionStream.GetCompressionRate: Single; begin if FZRec.total_in = 0 then Result : = 0 else { Result : = (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0; } end; // TDecompressionStream constructor TDecompressionStream.Create(Source: TStream); begin inherited Create(Source); FZRec.next_in : = FBuffer; FZRec.avail_in : = 0; DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec))); end; destructor TDecompressionStream.Destroy; begin FStrm.Seek(-FZRec.avail_in, 1); inflateEnd(FZRec); inherited Destroy; end; function TDecompressionStream.Read(var Buffer; Count: Longint): Longint; begin FZRec.next_out : = @Buffer; FZRec.avail_out : = Count; if FStrm.Position <> { FStrmPos then FStrm.Position : = FStrmPos; } while (FZRec.avail_out > 0) do begin if FZRec.avail_in = 0 then begin FZRec.avail_in : = FStrm.Read(FBuffer, sizeof(FBuffer)); if FZRec.avail_in = 0 then begin Result : = Count - FZRec.avail_out; Exit; end; FZRec.next_in : = FBuffer; FStrmPos : = FStrm.Position; Progress(Self); end; CCheck(inflate(FZRec, 0)); end; Result : = Count; end; function TDecompressionStream.Write(const Buffer; Count: Longint): Longint; begin raise EDecompressionError.CreateRes(@sInvalidStreamOp); end; function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint; var I: Integer; Buf: array [0..4095] of Char; begin if (Offset = 0) and (Origin = soFromBeginning) then begin DCheck(inflateReset(FZRec)); FZRec.next_in : = FBuffer; FZRec.avail_in : = 0; FStrm.Position : = 0; FStrmPos : = 0; end else if ((Offset >= 0) and (Origin = soFromCurrent)) or (((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then begin if Origin = soFromBeginning then Dec(Offset, FZRec.total_out); if Offset > 0 then begin for I : = 1 to Offset div sizeof(Buf) do { ReadBuffer(Buf, sizeof(Buf)); } ReadBuffer(Buf, Offset mod sizeof(Buf)); end; end else { raise EDecompressionError.CreateRes(@sInvalidStreamOp); } Result : = FZRec.total_out; end; end.
unit l3ControlsTypes; // Модуль: "w:\common\components\rtl\Garant\L3\l3ControlsTypes.pas" // Стереотип: "Interfaces" // Элемент модели: "l3ControlsTypes" MUID: (47D036150077) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses {$If NOT Defined(NoVCL)} , ImgList {$IfEnd} // NOT Defined(NoVCL) ; const {* Item Hit Type } ihtNone = 0; ihtText = 1; ihtIcon = 2; ihtPickIcon = 3; ihtOpenChip = 4; ihtFooter = 5; type TvtViewOption = ( {* настройки отображения. } voShowInterRowSpace , voShowIcons , voShowExpandable , voShowRoot , voShowLines , voShowOpenChip , voVariableItemHeight , voWithoutImages {* ImageList не используется, и не создается фиктивный из ресурса. } , voShowItemEdgeLine , voShowSelectAsArrow , voDoNotShowFocusRect , voFullLineSelect );//TvtViewOption TvtViewOptions = set of TvtViewOption; Tl3GetItemImage = function(Sender: TObject; Index: Integer; var aImages: TCustomImageList): Integer of object; {* Event to get Index of Bitmap in ImageIndex. } Tl3ActionElementMode = ( l3_amDoubleClick , l3_amSingleClick , l3_amSecondSingleClick );//Tl3ActionElementMode TvlViewOption = voShowInterRowSpace .. voShowInterRowSpace; TvlViewOptions = set of TvlViewOption; TvlOption = ( vlMouseTrack , vlTooltips );//TvlOption TvlOptions = set of TvlOption; implementation uses l3ImplUses ; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { *********************************************************** } unit tfRandoms; {$I TFL.inc} interface uses SysUtils, tfTypes, tfConsts, tfExceptions, {$IFDEF TFL_DLL} tfImport {$ELSE} tfRandEngines {$ENDIF}; type TRandom = record private FRandom: IRandom; public procedure GetRand(var Buf; BufSize: LongWord); procedure Burn; procedure Free; end; implementation { TRandom } procedure TRandom.Burn; begin if FRandom <> nil then begin {$IFDEF TFL_INTFCALL} FRandom.Burn; {$ELSE} TRandEngine.Burn(PRandEngine(FRandom)); {$ENDIF} end; end; procedure TRandom.Free; begin FRandom:= nil; end; procedure TRandom.GetRand(var Buf; BufSize: LongWord); var ErrCode: TF_RESULT; begin if FRandom = nil then begin {$IFDEF TFL_DLL} ErrCode:= GetRandInstance(FRandom); {$ELSE} ErrCode:= GetRandInstance(PRandEngine(FRandom)); {$ENDIF} if ErrCode <> TF_S_OK then raise ERandError.Create(ErrCode); end; {$IFDEF TFL_INTFCALL} ErrCode:= FRandom.GetRand(@Buf, BufSize); {$ELSE} ErrCode:= TRandEngine.GetRand(PRandEngine(FRandom), @Buf, BufSize); {$ENDIF} if ErrCode <> TF_S_OK then raise ERandError.Create(ErrCode, SRandFailure); end; end.
unit ufTarefa1; interface uses Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, uspQuery, Vcl.ExtCtrls, FireDAC.Phys.MySQLDef, FireDAC.Phys, FireDAC.Phys.MySQL; type TfTarefa1 = class(TForm) pnMain: TPanel; pnQuery: TPanel; lbColunas: TLabel; lbTabela: TLabel; lbCondicoes: TLabel; pnResultado: TPanel; meColunas: TMemo; meTabela: TMemo; meCondicoes: TMemo; btGeraSql: TButton; spQuery: TspQuery; FDPhysMySQLDriverLink1: TFDPhysMySQLDriverLink; meResultado: TMemo; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btGeraSqlClick(Sender: TObject); private { Private declarations } procedure GeraResposta; public { Public declarations } end; var fTarefa1: TfTarefa1; implementation {$R *.dfm} procedure TfTarefa1.btGeraSqlClick(Sender: TObject); begin spQuery.spColunas := meColunas.Lines; spQuery.spTabelas := meTabela.Lines; spQuery.spCondicoes := meCondicoes.Lines; spQuery.GeraSQL; GeraResposta; end; procedure TfTarefa1.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; Release; fTarefa1 := nil; end; procedure TfTarefa1.GeraResposta; begin meResultado.Clear; meResultado.Lines := spQuery.SQL; end; end.
//Exercício 11: Reescreva o exercício anterior para que seu algoritmo leia o comprimento e a altura da //parede a ser pintada (essas medidas deverão ser números inteiros). { Solução em Portugol Algoritmo Exercicio11; Const consumo_tinta = 3; volume_lata = 2; Var quantidade_latas: real; altura,largura: inteiro; Inicio exiba("Programa que diz quantas latas são necessárias para pintar uma parede."); exiba("Digite a altura da parede:"); leia(altura); exiba("Digite a largura da parede:"); leia(largura); quantidade_latas <- (consumo_tinta * altura * largura)/volume_lata; exiba("A quantidade de latas para pintar a parede é: ",quantidade_latas); Fim. } // Solução em Pascal Program Exercicio; uses crt; const consumo_tinta = 3; volume_lata = 2; var quantidade_latas: real; altura,largura: integer; begin clrscr; writeln('Programa que diz quantas latas são necessárias para pintar uma parede.'); writeln('Digite a altura da parede:'); readln(altura); writeln('Digite a largura da parede:'); readln(largura); quantidade_latas := (consumo_tinta * altura * largura)/volume_lata; writeln('A quantidade de latas para pintar a parede é: ',quantidade_latas:0:0); repeat until keypressed; end.
{ * CGWindowLevel.h * CoreGraphics * * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. * } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGWindowLevels; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGBase; {$ALIGN POWER} { * Windows may be assigned to a particular level. When assigned to a level, * the window is ordered relative to all other windows in that level. * Windows with a higher level are sorted in front of windows with a lower * level. * * A common set of window levels is defined here for use within higher * level frameworks. The levels are accessed via a key and function, * so that levels may be changed or adjusted in future releases without * breaking binary compatability. } type CGWindowLevel = SInt32; type CGWindowLevelKey = SInt32; type _CGCommonWindowLevelKey = SInt32; const kCGBaseWindowLevelKey = 0; kCGMinimumWindowLevelKey = 1; kCGDesktopWindowLevelKey = 2; kCGBackstopMenuLevelKey = 3; kCGNormalWindowLevelKey = 4; kCGFloatingWindowLevelKey = 5; kCGTornOffMenuWindowLevelKey = 6; kCGDockWindowLevelKey = 7; kCGMainMenuWindowLevelKey = 8; kCGStatusWindowLevelKey = 9; kCGModalPanelWindowLevelKey = 10; kCGPopUpMenuWindowLevelKey = 11; kCGDraggingWindowLevelKey = 12; kCGScreenSaverWindowLevelKey = 13; kCGMaximumWindowLevelKey = 14; kCGOverlayWindowLevelKey = 15; kCGHelpWindowLevelKey = 16; kCGUtilityWindowLevelKey = 17; kCGDesktopIconWindowLevelKey = 18; kCGCursorWindowLevelKey = 19; kCGAssistiveTechHighWindowLevelKey = 20; kCGNumberOfWindowLevelKeys = 21; { Internal bookkeeping; must be last } function CGWindowLevelForKey( key: CGWindowLevelKey ): CGWindowLevel; external name '_CGWindowLevelForKey'; { number of levels above kCGMaximumWindowLevel reserved for internal use } const kCGNumReservedWindowLevels = 16; (* { Definitions of older constant values as calls } #define kCGBaseWindowLevel CGWindowLevelForKey(kCGBaseWindowLevelKey) { LONG_MIN } #define kCGMinimumWindowLevel CGWindowLevelForKey(kCGMinimumWindowLevelKey) { (kCGBaseWindowLevel + 1) } #define kCGDesktopWindowLevel CGWindowLevelForKey(kCGDesktopWindowLevelKey) { kCGMinimumWindowLevel } #define kCGDesktopIconWindowLevel CGWindowLevelForKey(kCGDesktopIconWindowLevelKey) { kCGMinimumWindowLevel + 20 } #define kCGBackstopMenuLevel CGWindowLevelForKey(kCGBackstopMenuLevelKey) { -20 } #define kCGNormalWindowLevel CGWindowLevelForKey(kCGNormalWindowLevelKey) { 0 } #define kCGFloatingWindowLevel CGWindowLevelForKey(kCGFloatingWindowLevelKey) { 3 } #define kCGTornOffMenuWindowLevel CGWindowLevelForKey(kCGTornOffMenuWindowLevelKey) { 3 } #define kCGDockWindowLevel CGWindowLevelForKey(kCGDockWindowLevelKey) { 20 } #define kCGMainMenuWindowLevel CGWindowLevelForKey(kCGMainMenuWindowLevelKey) { 24 } #define kCGStatusWindowLevel CGWindowLevelForKey(kCGStatusWindowLevelKey) { 25 } #define kCGModalPanelWindowLevel CGWindowLevelForKey(kCGModalPanelWindowLevelKey) { 8 } #define kCGPopUpMenuWindowLevel CGWindowLevelForKey(kCGPopUpMenuWindowLevelKey) { 101 } #define kCGDraggingWindowLevel CGWindowLevelForKey(kCGDraggingWindowLevelKey) { 500 } #define kCGScreenSaverWindowLevel CGWindowLevelForKey(kCGScreenSaverWindowLevelKey) { 1000 } #define kCGCursorWindowLevel CGWindowLevelForKey(kCGCursorWindowLevelKey) { 2000 } #define kCGOverlayWindowLevel CGWindowLevelForKey(kCGOverlayWindowLevelKey) { 102 } #define kCGHelpWindowLevel CGWindowLevelForKey(kCGHelpWindowLevelKey) { 102 } #define kCGUtilityWindowLevel CGWindowLevelForKey(kCGUtilityWindowLevelKey) { 19 } #define kCGAssistiveTechHighWindowLevel CGWindowLevelForKey(kCGAssistiveTechHighWindowLevelKey) { 1500 } #define kCGMaximumWindowLevel CGWindowLevelForKey(kCGMaximumWindowLevelKey) { LONG_MAX - kCGNumReservedWindowLevels } *) end.
unit ZMExtrLZ7719; (* ZMExtrLZ7719.pas - LZ77 stream expander Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip modified 2007-11-05 ---------------------------------------------------------------------------*) interface uses Classes; // expects src at orig_size (integer), data (bytes) function LZ77Extract(dst, src: TStream; size: integer): integer; implementation const N = 4096; NMask = $FFF; //(N-1) F = 16; function GetByte(var bytes: Integer; Src: TStream): Integer; var cb: Byte; begin Result := -1; if (bytes > 4) and (Src.Size > Src.Position) then begin dec(bytes); if Src.Read(cb, 1) = 1 then Result := Integer(cb) else bytes := 0; end; end; function LZ77Extract(dst, src: TStream; size: integer): integer; var bits: Integer; Buffer: array of Byte; bytes: integer; ch: Integer; File_Size: integer; i: Integer; j: Integer; len: Integer; mask: Integer; written: integer; begin bytes := size; if bytes < 0 then bytes := HIGH(Integer); src.ReadBuffer(File_Size, sizeof(integer)); written := 0; SetLength(Buffer, N); i := N - F; while True do begin bits := GetByte(bytes, src); if (bits < 0) then break; mask := 1; while mask < 256 do begin if (bits and mask) = 0 then begin j := GetByte(bytes, src); if j < 0 then break; len := GetByte(bytes, src); inc(j, (len and $F0) shl 4); len := (len and 15) + 3; while len > 0 do begin Buffer[i] := Buffer[j]; dst.WriteBuffer(Buffer[i], 1); inc(written); j := succ(j) and NMask; i := succ(i) and NMask; dec(len); end; end else begin ch := GetByte(bytes, src); if ch < 0 then break; Buffer[i] := Byte(ch {and 255}); dst.WriteBuffer(ch, 1); inc(written); i := succ(i) and NMask; end; inc(mask, mask); end; end; if (File_Size = written) and (bytes = 4) then Result := 0 // good else if bytes = 4 then Result := -2 // wrong length else Result := -1; // invalid data Buffer := nil; end; end.
{******************************************************************************} { Projeto: Componentes ACBr } { Biblioteca multiplataforma de componentes Delphi para interação com equipa- } { mentos de Automação Comercial utilizados no Brasil } { Direitos Autorais Reservados (c) 2018 Daniel Simoes de Almeida } { Colaboradores nesse arquivo: Rafael Teno Dias } { Você pode obter a última versão desse arquivo na pagina do Projeto ACBr } { Componentes localizado em http://www.sourceforge.net/projects/acbr } { Esta biblioteca é software livre; você pode redistribuí-la e/ou modificá-la } { sob os termos da Licença Pública Geral Menor do GNU conforme publicada pela } { Free Software Foundation; tanto a versão 2.1 da Licença, ou (a seu critério) } { qualquer versão posterior. } { Esta biblioteca é distribuída na expectativa de que seja útil, porém, SEM } { NENHUMA GARANTIA; nem mesmo a garantia implícita de COMERCIABILIDADE OU } { ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA. Consulte a Licença Pública Geral Menor} { do GNU para mais detalhes. (Arquivo LICENÇA.TXT ou LICENSE.TXT) } { Você deve ter recebido uma cópia da Licença Pública Geral Menor do GNU junto} { com esta biblioteca; se não, escreva para a Free Software Foundation, Inc., } { no endereço 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. } { Você também pode obter uma copia da licença em: } { http://www.opensource.org/licenses/gpl-license.php } { Daniel Simões de Almeida - daniel@djsystem.com.br - www.djsystem.com.br } { Rua Cel.Aureliano de Camargo, 973 - Tatuí - SP - 18270-170 } {******************************************************************************} {$I ACBr.inc} unit ACBrLibSATClass; interface uses Classes, SysUtils, typinfo, ACBrLibComum, ACBrLibSATDataModule; type { TACBrLibPosPrinter } TACBrLibSAT = class(TACBrLib) private FSatDM: TLibSatDM; protected procedure Inicializar; override; procedure CriarConfiguracao(ArqConfig: string = ''; ChaveCrypt: ansistring = ''); override; procedure Executar; override; public constructor Create(ArqConfig: string = ''; ChaveCrypt: ansistring = ''); override; destructor Destroy; override; property SatDM: TLibSatDM read FSatDM; end; {%region Declaração da funções} {%region Redeclarando Métodos de ACBrLibComum, com nome específico} function SAT_Inicializar(const eArqConfig, eChaveCrypt: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_Finalizar: longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_Nome(const sNome: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_Versao(const sVersao: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_UltimoRetorno(const sMensagem: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_ConfigLer(const eArqConfig: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_ConfigGravar(const eArqConfig: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_ConfigLerValor(const eSessao, eChave: PChar; sValor: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_ConfigGravarValor(const eSessao, eChave, eValor: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; {%endregion} {%region Ativar} function SAT_InicializarSAT: longint;{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; function SAT_DesInicializar: longint;{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; {%endregion} {%endregion} implementation uses ACBrLibConsts, ACBrLibSATConsts, ACBrLibConfig, ACBrLibSATConfig; { TACBrLibSAT } constructor TACBrLibSAT.Create(ArqConfig: string; ChaveCrypt: ansistring); begin inherited Create(ArqConfig, ChaveCrypt); fpNome := CLibSATNome; fpVersao := CLibSATVersao; FSatDM := TLibSatDM.Create(nil); end; destructor TACBrLibSAT.Destroy; begin FSatDM.Free; inherited Destroy; end; procedure TACBrLibSAT.Inicializar; begin inherited Inicializar; GravarLog('TACBrLibSAT.Inicializar - Feito', logParanoico); end; procedure TACBrLibSAT.CriarConfiguracao(ArqConfig: string; ChaveCrypt: ansistring); begin fpConfig := TLibSATConfig.Create(Self, ArqConfig, ChaveCrypt); end; procedure TACBrLibSAT.Executar; begin inherited Executar; FSatDM.AplicarConfiguracoes; end; { ACBrLibSAT } {%region Redeclarando Métodos de ACBrLibComum, com nome específico} function SAT_Inicializar(const eArqConfig, eChaveCrypt: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_Inicializar(eArqConfig, eChaveCrypt); end; function SAT_Finalizar: longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_Finalizar; end; function SAT_Nome(const sNome: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_Nome(sNome, esTamanho); end; function SAT_Versao(const sVersao: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_Versao(sVersao, esTamanho); end; function SAT_UltimoRetorno(const sMensagem: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_UltimoRetorno(sMensagem, esTamanho); end; function SAT_ConfigLer(const eArqConfig: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_ConfigLer(eArqConfig); end; function SAT_ConfigGravar(const eArqConfig: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_ConfigGravar(eArqConfig); end; function SAT_ConfigLerValor(const eSessao, eChave: PChar; sValor: PChar; var esTamanho: longint): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_ConfigLerValor(eSessao, eChave, sValor, esTamanho); end; function SAT_ConfigGravarValor(const eSessao, eChave, eValor: PChar): longint; {$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin Result := LIB_ConfigGravarValor(eSessao, eChave, eValor); end; {%endregion} {%region Ativar} function SAT_InicializarSAT: longint;{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin try VerificarLibInicializada; pLib.GravarLog('POS_Ativar', logNormal); with TACBrLibSAT(pLib) do begin SatDM.Travar; try SatDM.ACBrSAT1.Inicializar; Result := SetRetorno(ErrOK); finally SatDM.Destravar; end; end; except on E: EACBrLibException do Result := SetRetorno(E.Erro, E.Message); on E: Exception do Result := SetRetorno(ErrExecutandoMetodo, E.Message); end; end; function SAT_DesInicializar: longint;{$IfDef STDCALL} stdcall{$Else} cdecl{$EndIf}; begin try VerificarLibInicializada; pLib.GravarLog('SAT_DesInicializar', logNormal); with TACBrLibSAT(pLib) do begin SatDM.Travar; try SatDM.ACBrSAT1.DesInicializar; Result := SetRetorno(ErrOK); finally SatDM.Destravar; end; end; except on E: EACBrLibException do Result := SetRetorno(E.Erro, E.Message); on E: Exception do Result := SetRetorno(ErrExecutandoMetodo, E.Message); end; end; {%endregion} end.
unit uCRUDConfiguracao; interface uses FireDAC.Comp.Client, System.SysUtils; type TRetornoConfiguracao = record CONFIG_ANO : String; CONFIG_PORCENTAGEMISENTO : Double; CONFIG_VALORDECLARARIR : Double; end; type TCRUDConfiguracao = class(TObject) private FConexao : TFDConnection; FQuery : TFDQuery; FCONFIG_VALORDECLARARIR: Double; FCONFIG_ANO: String; FCONFIG_PORCENTAGEMISENTO: Double; FpoRetornoConfig: TRetornoConfiguracao; procedure SetCONFIG_ANO(const Value: String); procedure SetCONFIG_PORCENTAGEMISENTO(const Value: Double); procedure SetCONFIG_VALORDECLARARIR(const Value: Double); procedure SetpoRetornoConfig(const Value: TRetornoConfiguracao); public constructor Create(poConexao : TFDConnection); destructor Destroy; override; procedure pcdGravaConfiguracao; procedure pcdExcluiConfiguracao; procedure pcdRetornaValorFaturadoANO(pdAno:String); published property CONFIG_ANO : String read FCONFIG_ANO write SetCONFIG_ANO; property CONFIG_PORCENTAGEMISENTO : Double read FCONFIG_PORCENTAGEMISENTO write SetCONFIG_PORCENTAGEMISENTO; property CONFIG_VALORDECLARARIR : Double read FCONFIG_VALORDECLARARIR write SetCONFIG_VALORDECLARARIR; property poRetornoConfig : TRetornoConfiguracao read FpoRetornoConfig write SetpoRetornoConfig; end; implementation { TCRUDConfiguracao } constructor TCRUDConfiguracao.Create(poConexao: TFDConnection); begin FConexao := poConexao; FQuery := TFDQuery.Create(nil); FQuery.Connection := FConexao; FQuery.Close; end; destructor TCRUDConfiguracao.Destroy; begin if Assigned(FQuery) then FreeAndNil(FQuery); inherited; end; procedure TCRUDConfiguracao.pcdRetornaValorFaturadoANO(pdAno: String); begin FpoRetornoConfig.CONFIG_ANO := ''; FpoRetornoConfig.CONFIG_PORCENTAGEMISENTO := 0; FpoRetornoConfig.CONFIG_VALORDECLARARIR := 0; FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('SELECT CONFIG_ANO, CONFIG_PORCENTAGEMISENTO, CONFIG_VALORDECLARARIR FROM CONFIGURACAO WHERE CONFIG_ANO = :CONFIG_ANO'); FQuery.ParamByName('CONFIG_ANO').AsString := pdAno; FQuery.Open; FpoRetornoConfig.CONFIG_ANO := FQuery.FieldByName('CONFIG_ANO').AsString; FpoRetornoConfig.CONFIG_PORCENTAGEMISENTO := FQuery.FieldByName('CONFIG_PORCENTAGEMISENTO').AsFloat; FpoRetornoConfig.CONFIG_VALORDECLARARIR := FQuery.FieldByName('CONFIG_VALORDECLARARIR').AsFloat; end; procedure TCRUDConfiguracao.pcdExcluiConfiguracao; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('DELETE FROM CONFIGURACAO WHERE CONFIG_ANO = :CONFIG_ANO'); FQuery.ParamByName('CONFIG_ANO').AsString := FCONFIG_ANO; FQuery.ExecSQL; end; procedure TCRUDConfiguracao.pcdGravaConfiguracao; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('INSERT INTO CONFIGURACAO (CONFIG_ANO, CONFIG_PORCENTAGEMISENTO, CONFIG_VALORDECLARARIR) VALUES (:CONFIG_ANO, :CONFIG_PORCENTAGEMISENTO, :CONFIG_VALORDECLARARIR)'); FQuery.ParamByName('CONFIG_ANO').AsString := FCONFIG_ANO; FQuery.ParamByName('CONFIG_PORCENTAGEMISENTO').AsFloat := FCONFIG_PORCENTAGEMISENTO; FQuery.ParamByName('CONFIG_VALORDECLARARIR').AsFloat := FCONFIG_VALORDECLARARIR; FQuery.ExecSQL; end; procedure TCRUDConfiguracao.SetCONFIG_ANO(const Value: String); begin FCONFIG_ANO := Value; end; procedure TCRUDConfiguracao.SetCONFIG_PORCENTAGEMISENTO(const Value: Double); begin FCONFIG_PORCENTAGEMISENTO := Value; end; procedure TCRUDConfiguracao.SetCONFIG_VALORDECLARARIR(const Value: Double); begin FCONFIG_VALORDECLARARIR := Value; end; procedure TCRUDConfiguracao.SetpoRetornoConfig( const Value: TRetornoConfiguracao); begin FpoRetornoConfig := Value; end; end.
unit kwSubPanelGetPopupMenuForSub; {* *Описание*: возвращает меню для саба на сабпанели. *Формат:* [code] aSubPanel aSubPanelSub SubPanel:GetPopupMenuForSub [code] aSubPanel - контрол саб панели. aSubPanelSub - объект класса TevSubPanelSub } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwSubPanelGetPopupMenuForSub.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "SubPanel_GetPopupMenuForSub" MUID: (53EE014B03AC) // Имя типа: "TkwSubPanelGetPopupMenuForSub" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwSubPanelFromStackWord , evSubPn , tfwScriptingInterfaces ; type TkwSubPanelGetPopupMenuForSub = {final} class(TkwSubPanelFromStackWord) {* *Описание*: возвращает меню для саба на сабпанели. *Формат:* [code] aSubPanel aSubPanelSub SubPanel:GetPopupMenuForSub [code] aSubPanel - контрол саб панели. aSubPanelSub - объект класса TevSubPanelSub } protected procedure DoWithSubPanel(aControl: TevCustomSubPanel; const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//TkwSubPanelGetPopupMenuForSub {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , evSubPanelSub , nevFacade , l3Interfaces , Types {$If NOT Defined(NoVCL)} , l3PopupMenuHelper {$IfEnd} // NOT Defined(NoVCL) , Windows {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) //#UC START# *53EE014B03ACimpl_uses* //#UC END# *53EE014B03ACimpl_uses* ; procedure TkwSubPanelGetPopupMenuForSub.DoWithSubPanel(aControl: TevCustomSubPanel; const aCtx: TtfwContext); //#UC START# *52D6471802DC_53EE014B03AC_var* var l_SPoint : Tl3_SPoint; l_SubPanelSub: TevSubPanelSub; //#UC END# *52D6471802DC_53EE014B03AC_var* begin //#UC START# *52D6471802DC_53EE014B03AC_impl* //aControl.PopupMenu; RunnerAssert(aCtx.rEngine.IsTopObj, 'Не задан объект класса aSubPanelSub!', aCtx); l_SubPanelSub := aCtx.rEngine.PopObj as TevSubPanelSub; l_SPoint := nev.CrtIC.LP2DP(l_SubPanelSub.DrawRect.TopLeft); aCtx.rEngine.PushObj(Tl3PopupMenuHelper.Instance.GetPopupMenu(aControl, Point(l_SPoint.X, l_SPoint.Y))); //#UC END# *52D6471802DC_53EE014B03AC_impl* end;//TkwSubPanelGetPopupMenuForSub.DoWithSubPanel class function TkwSubPanelGetPopupMenuForSub.GetWordNameForRegister: AnsiString; begin Result := 'SubPanel:GetPopupMenuForSub'; end;//TkwSubPanelGetPopupMenuForSub.GetWordNameForRegister initialization TkwSubPanelGetPopupMenuForSub.RegisterInEngine; {* Регистрация SubPanel_GetPopupMenuForSub } {$IfEnd} // NOT Defined(NoScripts) end.
unit uDataDisplay; interface uses Classes, CheckLst, IdGlobal, uProjectData, XMLIntf, XMLDoc, uBehaviorInterfaces, uUpdateListObserverInterface; type TSelectedProjectsDisplay = class(TProjectsDataDisplay, IDisplay) private FProjectItemsList: TStringList; FDoc: IXMLDocument; function FindProjectNode(const NodeIdx: Integer): IXMLNode; protected procedure UpdateCheckListBox(const Values: TStrings); override; public constructor Create(aProjectData: TComponent); override; destructor Destroy; override; procedure DisplayData; override; procedure InitializeDisplayGrid; override; procedure DoOnProjectItemChange(const Value: string); property ProjectItemsList: TStringList read FProjectItemsList write FProjectItemsList; end; implementation uses MainForm, uProjectConstants; { TSelectedProjectsDisplay } constructor TSelectedProjectsDisplay.Create(aProjectData: TComponent); begin inherited; FProjectItemsList := TStringList.Create; FDoc := FSubject.Doc; end; destructor TSelectedProjectsDisplay.Destroy; begin FreeAndNil(FProjectItemsList); inherited; end; procedure TSelectedProjectsDisplay.DisplayData; var I, Count : Integer; lstrProjName: String; Node: IXmlNode; begin inherited; Count := 1; for I := 0 to Pred(ProjectItemsList.Count) do begin with frmTeamCityMonitor.StringGrid , Node do begin lstrProjName := FProjectItemsList.Strings[I]; Cells[Ord(xfnName), Count] := lstrProjName; Node := FindProjectNode(FProjectItemsList.IndexOf(lstrProjName)); Cells[Ord(xfnLastBuildStatus), Count] := Attributes[LIST_OF_XML_FIELD_NAMES[xfnLastBuildStatus]]; Cells[Ord(xfnLastBuildLabel) , Count] := Attributes[LIST_OF_XML_FIELD_NAMES[xfnLastBuildLabel]]; Cells[Ord(xfnactivity) , Count] := Attributes[LIST_OF_XML_FIELD_NAMES[xfnactivity]]; Cells[Ord(xfnLastBuildTime) , Count] := Attributes[LIST_OF_XML_FIELD_NAMES[xfnLastBuildTime]]; Cells[Ord(xfnwebUrl) , Count] := Attributes[LIST_OF_XML_FIELD_NAMES[xfnwebUrl]]; end; Inc(Count); end; end; procedure TSelectedProjectsDisplay.DoOnProjectItemChange(const Value: string); var Idx: Integer; begin Idx := FProjectItemsList.IndexOf(Value); if (Idx = -1) then FProjectItemsList.Add(Value) else FProjectItemsList.Delete(Idx); end; function TSelectedProjectsDisplay.FindProjectNode(const NodeIdx: Integer): IXMLNode; begin Result := FDoc.DocumentElement.ChildNodes.Get(NodeIdx); end; procedure TSelectedProjectsDisplay.InitializeDisplayGrid; var Cntr :Integer; begin inherited; with frmTeamCityMonitor.StringGrid do begin RowCount := ProjectItemsList.Count + 1; ColCount := MAX_SG_COL_COUNT_INT + 1; for Cntr := MIN_SG_COL_COUNT_INT to MAX_SG_COL_COUNT_INT do begin Cells[Cntr, 0] := LIST_OF_COLUMNS[TXMLFldNames(Cntr)]; if Cntr = Ord(xfnName) then ColWidths[Cntr] := SG_COL_WIDTH_NAME; if Cntr = Ord(xfnLastBuildTime) then ColWidths[Cntr] := SG_COL_WIDTH_TIME; end; end; end; procedure TSelectedProjectsDisplay.UpdateCheckListBox(const Values: TStrings); begin FSubject.FCheckLBItems.Clear; inherited; end; end.
unit ItemDetailsFRM; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, System.UITypes, ItemController; type TItemMode = (smEdit, smNew); type TfrmItemDetails = class(TForm) Label1: TLabel; Label5: TLabel; Label7: TLabel; edtItemName: TEdit; btnOK: TButton; btnCancel: TButton; edtItemId: TEdit; edtItemDescription: TEdit; procedure FormShow(Sender: TObject); procedure btnOKClick(Sender: TObject); private FItem: TItem; FItemMode: TItemMode; procedure LoadItemDetails; function PerformValidations: boolean; procedure CopyItemDetails; { Private declarations } public { Public declarations } property Item: TItem read FItem write FItem; property ItemMode: TItemMode read FItemMode write FItemMode; end; implementation {$R *.dfm} procedure TfrmItemDetails.btnOKClick(Sender: TObject); begin if PerformValidations then begin CopyItemDetails; ModalResult := mrOk; end; end; function TfrmItemDetails.PerformValidations: boolean; begin result := true; if trim(edtItemName.Text) = '' then begin MessageDlg('Please enter a valid Item Name.', mtError, [mbOK], 0); result := false; end; end; procedure TfrmItemDetails.CopyItemDetails; begin FItem.ItemName := edtItemName.Text; FItem.ItemDescription := edtItemDescription.Text; end; procedure TfrmItemDetails.FormShow(Sender: TObject); begin LoadItemDetails; end; procedure TfrmItemDetails.LoadItemDetails; begin if ItemMode = smEdit then begin edtItemId.Text := IntToStr(FItem.ItemId); edtItemName.Text := FItem.ItemName; edtItemDescription.Text := FItem.ItemDescription; end; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit Test; interface //class Test; //struct Settings; // //typedef Test* TestCreateFcn(); // //#define RAND_LIMIT 32767 //#define DRAW_STRING_NEW_LINE 16 // ///// Random number in range [-1,1] //inline float32 RandomFloat() //{ // float32 r = (float32)(std::rand() & (RAND_LIMIT)); // r /= RAND_LIMIT; // r = 2.0f * r - 1.0f; // return r; //} // ///// Random floating point number in range [lo, hi] //inline float32 RandomFloat(float32 lo, float32 hi) //{ // float32 r = (float32)(std::rand() & (RAND_LIMIT)); // r /= RAND_LIMIT; // r = (hi - lo) * r + lo; // return r; //} // ///// Test settings. Some can be controlled in the GUI. //struct Settings //{ // Settings() // { // hz = 60.0f; // velocityIterations = 8; // positionIterations = 3; // drawShapes = true; // drawJoints = true; // drawAABBs = false; // drawContactPoints = false; // drawContactNormals = false; // drawContactImpulse = false; // drawFrictionImpulse = false; // drawCOMs = false; // drawStats = false; // drawProfile = false; // enableWarmStarting = true; // enableContinuous = true; // enableSubStepping = false; // enableSleep = true; // pause = false; // singleStep = false; // } // // float32 hz; // int32 velocityIterations; // int32 positionIterations; // bool drawShapes; // bool drawJoints; // bool drawAABBs; // bool drawContactPoints; // bool drawContactNormals; // bool drawContactImpulse; // bool drawFrictionImpulse; // bool drawCOMs; // bool drawStats; // bool drawProfile; // bool enableWarmStarting; // bool enableContinuous; // bool enableSubStepping; // bool enableSleep; // bool pause; // bool singleStep; //}; type PSettings = ^TSettings; TSettings = record hz: single; velocityIterations: Int32; positionIterations: Int32; drawShapes: Boolean; drawJoints: Boolean; drawAABBs: Boolean; drawContactPoints: Boolean; drawContactNormals: Boolean; drawContactImpulse: Boolean; drawFrictionImpulse: Boolean; drawCOMs: Boolean; drawStats: Boolean; drawProfile: Boolean; enableWarmStarting: Boolean; enableContinuous: Boolean; enableSubStepping: Boolean; enableSleep: Boolean; pause: Boolean; singleStep: Boolean; end; //struct TestEntry //{ // const char *name; // TestCreateFcn *createFcn; //}; // TTest = class; PTest = ^TTest; TTest = record end; // // TTestCreateFunction = function(): TTest; // PTestEntry = ^TTestEntry; TTestEntry = record Name: string; //CreateFunction: TTestCreateFunction; end; // //extern TestEntry g_testEntries[]; //// This is called when a joint in the world is implicitly destroyed //// because an attached body is destroyed. This gives us a chance to //// nullify the mouse joint. //class DestructionListener : public b2DestructionListener //{ //public: // void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } // void SayGoodbye(b2Joint* joint); // // Test* test; //}; // //const int32 k_maxContactPoints = 2048; // //struct ContactPoint //{ // b2Fixture* fixtureA; // b2Fixture* fixtureB; // b2Vec2 normal; // b2Vec2 position; // b2PointState state; // float32 normalImpulse; // float32 tangentImpulse; // float32 separation; //}; // //class Test : public b2ContactListener //{ //public: // // Test(); // virtual ~Test(); // // void DrawTitle(const char *string); // virtual void Step(Settings* settings); // virtual void Keyboard(int key) { B2_NOT_USED(key); } // virtual void KeyboardUp(int key) { B2_NOT_USED(key); } // void ShiftMouseDown(const b2Vec2& p); // virtual void MouseDown(const b2Vec2& p); // virtual void MouseUp(const b2Vec2& p); // void MouseMove(const b2Vec2& p); // void LaunchBomb(); // void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); // // void SpawnBomb(const b2Vec2& worldPt); // void CompleteBombSpawn(const b2Vec2& p); // // // Let derived tests know that a joint was destroyed. // virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } // // // Callbacks for derived classes. // virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } // virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } // virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold); // virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) // { // B2_NOT_USED(contact); // B2_NOT_USED(impulse); // } // // void ShiftOrigin(const b2Vec2& newOrigin); // //protected: // friend class DestructionListener; // friend class BoundaryListener; // friend class ContactListener; // // b2Body* m_groundBody; // b2AABB m_worldAABB; // ContactPoint m_points[k_maxContactPoints]; // int32 m_pointCount; // DestructionListener m_destructionListener; // int32 m_textLine; // b2World* m_world; // b2Body* m_bomb; // b2MouseJoint* m_mouseJoint; // b2Vec2 m_bombSpawnPoint; // bool m_bombSpawning; // b2Vec2 m_mouseWorld; // int32 m_stepCount; // // b2Profile m_maxProfile; // b2Profile m_totalProfile; //}; implementation // //void DestructionListener::SayGoodbye(b2Joint* joint) //{ // if (test->m_mouseJoint == joint) // { // test->m_mouseJoint = NULL; // } // else // { // test->JointDestroyed(joint); // } //} // //Test::Test() //{ // b2Vec2 gravity; // gravity.Set(0.0f, -10.0f); // m_world = new b2World(gravity); // m_bomb = NULL; // m_textLine = 30; // m_mouseJoint = NULL; // m_pointCount = 0; // // m_destructionListener.test = this; // m_world->SetDestructionListener(&m_destructionListener); // m_world->SetContactListener(this); // m_world->SetDebugDraw(&g_debugDraw); // // m_bombSpawning = false; // // m_stepCount = 0; // // b2BodyDef bodyDef; // m_groundBody = m_world->CreateBody(&bodyDef); // // memset(&m_maxProfile, 0, sizeof(b2Profile)); // memset(&m_totalProfile, 0, sizeof(b2Profile)); //} // //Test::~Test() //{ // // By deleting the world, we delete the bomb, mouse joint, etc. // delete m_world; // m_world = NULL; //} // //void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) //{ // const b2Manifold* manifold = contact->GetManifold(); // // if (manifold->pointCount == 0) // { // return; // } // // b2Fixture* fixtureA = contact->GetFixtureA(); // b2Fixture* fixtureB = contact->GetFixtureB(); // // b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints]; // b2GetPointStates(state1, state2, oldManifold, manifold); // // b2WorldManifold worldManifold; // contact->GetWorldManifold(&worldManifold); // // for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i) // { // ContactPoint* cp = m_points + m_pointCount; // cp->fixtureA = fixtureA; // cp->fixtureB = fixtureB; // cp->position = worldManifold.points[i]; // cp->normal = worldManifold.normal; // cp->state = state2[i]; // cp->normalImpulse = manifold->points[i].normalImpulse; // cp->tangentImpulse = manifold->points[i].tangentImpulse; // cp->separation = worldManifold.separations[i]; // ++m_pointCount; // } //} // //void Test::DrawTitle(const char *string) //{ // g_debugDraw.DrawString(5, DRAW_STRING_NEW_LINE, string); // m_textLine = 3 * DRAW_STRING_NEW_LINE; //} // //class QueryCallback : public b2QueryCallback //{ //public: // QueryCallback(const b2Vec2& point) // { // m_point = point; // m_fixture = NULL; // } // // bool ReportFixture(b2Fixture* fixture) // { // b2Body* body = fixture->GetBody(); // if (body->GetType() == b2_dynamicBody) // { // bool inside = fixture->TestPoint(m_point); // if (inside) // { // m_fixture = fixture; // // // We are done, terminate the query. // return false; // } // } // // // Continue the query. // return true; // } // // b2Vec2 m_point; // b2Fixture* m_fixture; //}; // //void Test::MouseDown(const b2Vec2& p) //{ // m_mouseWorld = p; // // if (m_mouseJoint != NULL) // { // return; // } // // // Make a small box. // b2AABB aabb; // b2Vec2 d; // d.Set(0.001f, 0.001f); // aabb.lowerBound = p - d; // aabb.upperBound = p + d; // // // Query the world for overlapping shapes. // QueryCallback callback(p); // m_world->QueryAABB(&callback, aabb); // // if (callback.m_fixture) // { // b2Body* body = callback.m_fixture->GetBody(); // b2MouseJointDef md; // md.bodyA = m_groundBody; // md.bodyB = body; // md.target = p; // md.maxForce = 1000.0f * body->GetMass(); // m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&md); // body->SetAwake(true); // } //} // //void Test::SpawnBomb(const b2Vec2& worldPt) //{ // m_bombSpawnPoint = worldPt; // m_bombSpawning = true; //} // //void Test::CompleteBombSpawn(const b2Vec2& p) //{ // if (m_bombSpawning == false) // { // return; // } // // const float multiplier = 30.0f; // b2Vec2 vel = m_bombSpawnPoint - p; // vel *= multiplier; // LaunchBomb(m_bombSpawnPoint,vel); // m_bombSpawning = false; //} // //void Test::ShiftMouseDown(const b2Vec2& p) //{ // m_mouseWorld = p; // // if (m_mouseJoint != NULL) // { // return; // } // // SpawnBomb(p); //} // //void Test::MouseUp(const b2Vec2& p) //{ // if (m_mouseJoint) // { // m_world->DestroyJoint(m_mouseJoint); // m_mouseJoint = NULL; // } // // if (m_bombSpawning) // { // CompleteBombSpawn(p); // } //} // //void Test::MouseMove(const b2Vec2& p) //{ // m_mouseWorld = p; // // if (m_mouseJoint) // { // m_mouseJoint->SetTarget(p); // } //} // //void Test::LaunchBomb() //{ // b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f); // b2Vec2 v = -5.0f * p; // LaunchBomb(p, v); //} // //void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity) //{ // if (m_bomb) // { // m_world->DestroyBody(m_bomb); // m_bomb = NULL; // } // // b2BodyDef bd; // bd.type = b2_dynamicBody; // bd.position = position; // bd.bullet = true; // m_bomb = m_world->CreateBody(&bd); // m_bomb->SetLinearVelocity(velocity); // // b2CircleShape circle; // circle.m_radius = 0.3f; // // b2FixtureDef fd; // fd.shape = &circle; // fd.density = 20.0f; // fd.restitution = 0.0f; // // b2Vec2 minV = position - b2Vec2(0.3f,0.3f); // b2Vec2 maxV = position + b2Vec2(0.3f,0.3f); // // b2AABB aabb; // aabb.lowerBound = minV; // aabb.upperBound = maxV; // // m_bomb->CreateFixture(&fd); //} // //void Test::Step(Settings* settings) //{ // float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f); // // if (settings->pause) // { // if (settings->singleStep) // { // settings->singleStep = 0; // } // else // { // timeStep = 0.0f; // } // // g_debugDraw.DrawString(5, m_textLine, "****PAUSED****"); // m_textLine += DRAW_STRING_NEW_LINE; // } // // uint32 flags = 0; // flags += settings->drawShapes * b2Draw::e_shapeBit; // flags += settings->drawJoints * b2Draw::e_jointBit; // flags += settings->drawAABBs * b2Draw::e_aabbBit; // flags += settings->drawCOMs * b2Draw::e_centerOfMassBit; // g_debugDraw.SetFlags(flags); // // m_world->SetAllowSleeping(settings->enableSleep); // m_world->SetWarmStarting(settings->enableWarmStarting); // m_world->SetContinuousPhysics(settings->enableContinuous); // m_world->SetSubStepping(settings->enableSubStepping); // // m_pointCount = 0; // // m_world->Step(timeStep, settings->velocityIterations, settings->positionIterations); // // m_world->DrawDebugData(); // g_debugDraw.Flush(); // // if (timeStep > 0.0f) // { // ++m_stepCount; // } // // if (settings->drawStats) // { // int32 bodyCount = m_world->GetBodyCount(); // int32 contactCount = m_world->GetContactCount(); // int32 jointCount = m_world->GetJointCount(); // g_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount); // m_textLine += DRAW_STRING_NEW_LINE; // // int32 proxyCount = m_world->GetProxyCount(); // int32 height = m_world->GetTreeHeight(); // int32 balance = m_world->GetTreeBalance(); // float32 quality = m_world->GetTreeQuality(); // g_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality); // m_textLine += DRAW_STRING_NEW_LINE; // } // // // Track maximum profile times // { // const b2Profile& p = m_world->GetProfile(); // m_maxProfile.step = b2Max(m_maxProfile.step, p.step); // m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide); // m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve); // m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit); // m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity); // m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition); // m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI); // m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase); // // m_totalProfile.step += p.step; // m_totalProfile.collide += p.collide; // m_totalProfile.solve += p.solve; // m_totalProfile.solveInit += p.solveInit; // m_totalProfile.solveVelocity += p.solveVelocity; // m_totalProfile.solvePosition += p.solvePosition; // m_totalProfile.solveTOI += p.solveTOI; // m_totalProfile.broadphase += p.broadphase; // } // // if (settings->drawProfile) // { // const b2Profile& p = m_world->GetProfile(); // // b2Profile aveProfile; // memset(&aveProfile, 0, sizeof(b2Profile)); // if (m_stepCount > 0) // { // float32 scale = 1.0f / m_stepCount; // aveProfile.step = scale * m_totalProfile.step; // aveProfile.collide = scale * m_totalProfile.collide; // aveProfile.solve = scale * m_totalProfile.solve; // aveProfile.solveInit = scale * m_totalProfile.solveInit; // aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity; // aveProfile.solvePosition = scale * m_totalProfile.solvePosition; // aveProfile.solveTOI = scale * m_totalProfile.solveTOI; // aveProfile.broadphase = scale * m_totalProfile.broadphase; // } // // g_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI); // m_textLine += DRAW_STRING_NEW_LINE; // g_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase); // m_textLine += DRAW_STRING_NEW_LINE; // } // // if (m_mouseJoint) // { // b2Vec2 p1 = m_mouseJoint->GetAnchorB(); // b2Vec2 p2 = m_mouseJoint->GetTarget(); // // b2Color c; // c.Set(0.0f, 1.0f, 0.0f); // g_debugDraw.DrawPoint(p1, 4.0f, c); // g_debugDraw.DrawPoint(p2, 4.0f, c); // // c.Set(0.8f, 0.8f, 0.8f); // g_debugDraw.DrawSegment(p1, p2, c); // } // // if (m_bombSpawning) // { // b2Color c; // c.Set(0.0f, 0.0f, 1.0f); // g_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c); // // c.Set(0.8f, 0.8f, 0.8f); // g_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c); // } // // if (settings->drawContactPoints) // { // const float32 k_impulseScale = 0.1f; // const float32 k_axisScale = 0.3f; // // for (int32 i = 0; i < m_pointCount; ++i) // { // ContactPoint* point = m_points + i; // // if (point->state == b2_addState) // { // // Add // g_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f)); // } // else if (point->state == b2_persistState) // { // // Persist // g_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f)); // } // // if (settings->drawContactNormals == 1) // { // b2Vec2 p1 = point->position; // b2Vec2 p2 = p1 + k_axisScale * point->normal; // g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f)); // } // else if (settings->drawContactImpulse == 1) // { // b2Vec2 p1 = point->position; // b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal; // g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); // } // // if (settings->drawFrictionImpulse == 1) // { // b2Vec2 tangent = b2Cross(point->normal, 1.0f); // b2Vec2 p1 = point->position; // b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent; // g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f)); // } // } // } //} // //void Test::ShiftOrigin(const b2Vec2& newOrigin) //{ // m_world->ShiftOrigin(newOrigin); //} end.
unit RemoveOptimizationUnit; interface uses SysUtils, BaseExampleUnit; type TRemoveOptimization = class(TBaseExample) public procedure Execute(OptimizationProblemId: String); end; implementation procedure TRemoveOptimization.Execute(OptimizationProblemId: String); var ErrorString: String; Removed: boolean; begin Removed := Route4MeManager.Optimization.Remove(OptimizationProblemID, ErrorString); WriteLn(''); if (Removed) then begin WriteLn('RemoveOptimization executed successfully'); WriteLn(Format('Optimization Problem ID: %s', [OptimizationProblemID])); end else WriteLn(Format('RemoveOptimization error: "%s"', [ErrorString])); end; end.
{******************************************************************************* 作者: dmzn@163.com 2009-6-24 描述: 摄像头设置 *******************************************************************************} unit UFormCameraSetup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, DSUtil, DirectShow9, UFormNormal, cxGraphics, DSPack, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, dxLayoutControl, StdCtrls, cxControls; type TfFormCameraSetup = class(TfFormNormal) VideoWindow1: TVideoWindow; dxLayout1Item3: TdxLayoutItem; EditSysDev: TcxComboBox; dxLayout1Item4: TdxLayoutItem; BtnSetup: TButton; dxLayout1Item5: TdxLayoutItem; dxLayout1Group2: TdxLayoutGroup; EditSize: TcxComboBox; dxLayout1Item6: TdxLayoutItem; VideoFilter1: TFilter; FilterGraph1: TFilterGraph; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EditSysDevPropertiesChange(Sender: TObject); procedure BtnSetupClick(Sender: TObject); procedure EditSizePropertiesChange(Sender: TObject); procedure BtnOKClick(Sender: TObject); protected { Private declarations } FSaveToDB: Boolean; //是否保存 FSysDev: TSysDevEnum; //设备对象 FMediaTypes: TEnumMediaType; //媒体类型 procedure OpenCamera; procedure CloseCamera; //开&关摄像头 procedure ConfigWithDB(const nSave: Boolean); //载入&保存配置 function GetMediaTypeOfSize(const nMediaType: TAMMediaType): TPoint; //屏幕尺寸 public { Public declarations } class function CreateForm(const nPopedom: string = ''; const nParam: Pointer = nil): TWinControl; override; class function FormID: integer; override; end; function ShowCameraSetupForm(const nSaveToDB: Boolean): Boolean; //入口函数 implementation {$R *.dfm} uses IniFiles, ULibFun, UMgrControl, UDataModule, USysDB, USysConst; //------------------------------------------------------------------------------ //Date: 2009-6-24 //Parm: 是否需要保存到数据库 //Desc: 显示摄像头设置窗口 function ShowCameraSetupForm(const nSaveToDB: Boolean): Boolean; begin with TfFormCameraSetup.Create(Application) do try Caption := '硬件设置'; FSaveToDB := nSaveToDB; Result := ShowModal = mrOK; finally Free; end; end; class function TfFormCameraSetup.CreateForm(const nPopedom: string; const nParam: Pointer): TWinControl; begin Result := nil; with TfFormCameraSetup.Create(Application) do try Caption := '硬件设置'; FSaveToDB := (gSysDBType <> dtAccess) and gSysParam.FIsAdmin; ConfigWithDB(False); ShowModal; finally Free; end; end; class function TfFormCameraSetup.FormID: integer; begin Result := CFI_FormHardware; end; //------------------------------------------------------------------------------ procedure TfFormCameraSetup.FormCreate(Sender: TObject); var nIdx: integer; begin EditSize.Enabled := False; BtnSetup.Enabled := False; EditSysDev.Properties.Items.Clear; FMediaTypes := TEnumMediaType.Create; FSysDev := TSysDevEnum.Create(CLSID_VideoInputDeviceCategory); nIdx := 0; while nIdx < FSysDev.CountFilters do begin EditSysDev.Properties.Items.Add(FSysDev.Filters[nIdx].FriendlyName); Inc(nIdx); end; if nIdx = 0 then dxGroup1.Caption := '预览 - 没有视频设备' else dxGroup1.Caption := '预览 - 未启动'; end; procedure TfFormCameraSetup.FormClose(Sender: TObject; var Action: TCloseAction); begin CloseCamera; FMediaTypes.Free; FSysDev.Free; end; //------------------------------------------------------------------------------ //Desc: 打开摄像头 procedure TfFormCameraSetup.OpenCamera; begin FilterGraph1.Active := True; if VideoFilter1.BaseFilter.DataLength > 0 then with FilterGraph1 as ICaptureGraphBuilder2 do RenderStream(@PIN_CATEGORY_PREVIEW, nil, VideoFilter1 as IBaseFilter, nil, VideoWindow1 as IBaseFilter); //xxxxx FilterGraph1.Play; dxGroup1.Caption := '预览'; end; //Desc: 关闭摄像头 procedure TfFormCameraSetup.CloseCamera; begin FilterGraph1.ClearGraph; FilterGraph1.Active := False; FilterGraph1.Mode := gmCapture; dxGroup1.Caption := '预览 - 未启动'; end; //Desc: 获取nMediaType画面比例的屏幕尺寸 function TfFormCameraSetup.GetMediaTypeOfSize(const nMediaType: TAMMediaType): TPoint; begin if IsEqualGUID(nMediaType.formattype, FORMAT_VideoInfo) or IsEqualGUID(nMediaType.formattype, FORMAT_VideoInfo2) or IsEqualGUID(nMediaType.formattype, FORMAT_MPEGVideo) or IsEqualGUID(nMediaType.formattype, FORMAT_MPEG2Video) then begin if ((nMediaType.cbFormat > 0) and Assigned(nMediaType.pbFormat)) then with PVideoInfoHeader(nMediaType.pbFormat)^.bmiHeader do Result := Point(biWidth, biHeight); end else Result := Point(0, 0); end; //Desc: 读取&保存配置 procedure TfFormCameraSetup.ConfigWithDB(const nSave: Boolean); var nStr: string; nIni: TIniFile; begin nIni := nil; try if nSave then begin if FSaveToDB then begin nStr := 'Update %s Set H_Dev=''%s'',H_Size=''%s'' Where H_ID=''%s'''; nStr := Format(nStr, [sTable_Hardware, EditSysDev.Text, EditSize.Text, sFlag_Hardware]); if FDM.ExecuteSQL(nStr) < 1 then begin nStr := 'Insert Into %s(H_ID,H_Dev,H_Size) Values(''%s'',''%s'',''%s'')'; nStr := Format(nStr, [sTable_Hardware, sFlag_Hardware, EditSysDev.Text, EditSize.Text]); FDM.ExecuteSQL(nStr); end; end else begin nIni := TIniFile.Create(gPath + sFormConfig); nIni.WriteString(Name, 'SysDevName', EditSysDev.Text); nIni.WriteString(Name, 'SysDevSize', EditSize.Text); end; ShowMsg('保存成功', sHint); end else begin if FSaveToDB then begin nStr := 'Select H_Dev,H_Size From %s Where H_ID=''%s'''; nStr := Format(nStr, [sTable_Hardware, sFlag_Hardware]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin nStr := Fields[0].AsString; EditSysDev.ItemIndex := EditSysDev.Properties.Items.IndexOf(nStr); Application.ProcessMessages; nStr := Fields[1].AsString; EditSize.ItemIndex := EditSize.Properties.Items.IndexOf(nStr); end; end else begin nIni := TIniFile.Create(gPath + sFormConfig); nStr := nIni.ReadString(Name, 'SysDevName', ''); EditSysDev.ItemIndex := EditSysDev.Properties.Items.IndexOf(nStr); Application.ProcessMessages; nStr := nIni.ReadString(Name, 'SysDevSize', ''); EditSize.ItemIndex := EditSize.Properties.Items.IndexOf(nStr); end; end; finally FreeAndNil(nIni); end; end; //------------------------------------------------------------------------------ //Desc: 设备变动 procedure TfFormCameraSetup.EditSysDevPropertiesChange(Sender: TObject); var nStr: string; nIdx: integer; nList: TPinList; begin EditSize.Enabled := False; BtnSetup.Enabled := False; if EditSysDev.ItemIndex < 0 then Exit; nList := nil; try CloseCamera; FSysDev.SelectGUIDCategory(CLSID_VideoInputDeviceCategory); VideoFilter1.BaseFilter.Moniker := FSysDev.GetMoniker(EditSysDev.ItemIndex); VideoFilter1.FilterGraph := FilterGraph1; FilterGraph1.Active := True; nList := TPinList.Create(VideoFilter1 as IBaseFilter); EditSize.Properties.Items.Clear; FMediaTypes.Assign(nList.First); for nIdx:=0 to FMediaTypes.Count - 1 do begin nStr := FMediaTypes.MediaDescription[nIdx]; System.Delete(nStr, 1, Pos('VideoInfo', nStr) - 1); EditSize.Properties.Items.Add(nStr); end; FreeAndNil(nList); EditSize.Enabled := EditSize.Properties.Items.Count > 0; BtnSetup.Enabled := EditSize.Enabled; except CloseCamera; FreeAndNil(nList); end; end; //Desc: 修改屏幕尺寸 procedure TfFormCameraSetup.EditSizePropertiesChange(Sender: TObject); var nP: TPoint; nList: TPinList; begin nList := nil; if EditSize.ItemIndex > -1 then try CloseCamera; FilterGraph1.Active := True; nP := GetMediaTypeOfSize(FMediaTypes.Items[EditSize.ItemIndex].AMMediaType^); if nP.X > 0 then VideoWindow1.Width := nP.X; if nP.Y > 0 then VideoWindow1.Height := nP.Y; Application.ProcessMessages; Self.ClientWidth := BtnExit.Left + BtnExit.Width + 15; Self.ClientHeight := BtnExit.Top + BtnExit.Height + 15; nList := TPinList.Create(VideoFilter1 as IBaseFilter); with (nList.First as IAMStreamConfig) do SetFormat(FMediaTypes.Items[EditSize.ItemIndex].AMMediaType^); FreeAndNil(nList); OpenCamera; except CloseCamera; FreeAndNil(nList); end; end; //Desc: 设置 procedure TfFormCameraSetup.BtnSetupClick(Sender: TObject); begin try if FilterGraph1.State <> gsPlaying then OpenCamera; ShowFilterPropertyPage(Self.Handle, VideoFilter1 as IBaseFilter); except //ignor any error end; end; //Desc: 保存 procedure TfFormCameraSetup.BtnOKClick(Sender: TObject); begin if EditSysDev.ItemIndex < 0 then begin EditSysDev.SetFocus; ShowMsg('请选择设备', sHint); Exit; end; if EditSize.ItemIndex < 0 then begin EditSize.SetFocus; ShowMsg('请选择画面比例', sHint); Exit; end; ConfigWithDB(True); ModalResult := mrOk; end; initialization gControlManager.RegCtrl(TfFormCameraSetup, TfFormCameraSetup.FormID); end.
unit TestThermostatClasses; interface uses Thermostat.Classes, TestFramework, SysUtils, Generics.Collections; type // Test methods for class TThermostatState TestTThermostatState = class(TTestCase) strict private FThermostatState: TThermostatState; public procedure SetUp; override; procedure TearDown; override; published procedure TestChangeState; end; // Test methods for class TThermostat // TestTThermostat = class(TTestCase) // strict private // FThermostat: TThermostat; // public // procedure SetUp; override; // procedure TearDown; override; // end; implementation type TTestThermostatState = class(TThermostatState) end; { TestTThermostatState } procedure TestTThermostatState.SetUp; begin FThermostatState := TThermostatState.Create; end; procedure TestTThermostatState.TearDown; begin FThermostatState.Free; FThermostatState := nil; end; procedure TestTThermostatState.TestChangeState; var state : TThermostatState; testState: TThermostatState; begin state := FThermostatState.GetStateClass(TThermostatState); FThermostatState.State := state; Assert(state.ClassType = TThermostatState); Assert(state.Parent = FThermostatState); Assert(FThermostatState.State = state); state.ChangeState(TTestThermostatState); testState := FThermostatState.State; Assert(testState is TTestThermostatState); Assert(testState.ClassType = TTestThermostatState); end; { TestTThermostat } //procedure TestTThermostat.SetUp; //begin // FThermostat := TThermostat.Create; //end; // //procedure TestTThermostat.TearDown; //begin // FThermostat.Free; // FThermostat := nil; //end; initialization RegisterTest(TestTThermostatState.Suite); // RegisterTest(TestTThermostat.Suite); end.
unit FCT.Connection; /// Factory ERP /// Date: 01-26-2020 /// Author: Marcio Silva /// Git: github.com/marciosdev /// Mail: marciosdev@icloud.com interface uses System.SysUtils, System.Variants, System.Classes, System.Win.Registry, Uni, PostgreSQLUniProvider, FCT.Setting; type TFCTConnection = class private FoSetting: TFCTSetting; FoConnection: TUniConnection; class var FoFCTConnection: TFCTConnection; procedure DoBeforeConnect; procedure DoConnect; class procedure Free; public constructor Create; overload; class function GetConnection: TUniConnection; end; implementation { TFCTConnection } constructor TFCTConnection.Create; begin inherited; FoSetting := TFCTSetting.Create; end; procedure TFCTConnection.DoBeforeConnect; begin FoConnection.Server := FoSetting.GetPostgreServer; FoConnection.Port := FoSetting.GetPostgrePort; FoConnection.Username := FoSetting.GetPostgreUser; FoConnection.Password := FoSetting.GetPostgrePass;{oSeguranca.Decriptografar(oConfiguracao.GetSenhaPostgreSQL)}; FoConnection.ProviderName := FoSetting.GetPostgreProvider; FoConnection.LoginPrompt := False; end; procedure TFCTConnection.DoConnect; begin try FoConnection.Open; except on E: Exception do begin raise Exception.Create('Error Message'); //TfrmMensagem.Erro(Format(sMSG_ERRO_CONECTAR_POSTGRE, [FoPostgreDB.Server, E.Message])); end; end; end; class procedure TFCTConnection.Free; begin if not Assigned(FoFCTConnection) then Exit; if Assigned(FoFCTConnection.FoSetting) then FreeAndNil(FoFCTConnection.FoSetting); FoFCTConnection.FoConnection.Close; FreeAndNil(FoFCTConnection.FoConnection); FreeAndNil(FoFCTConnection); end; class function TFCTConnection.GetConnection: TUniConnection; begin if not Assigned(FoFCTConnection) then begin FoFCTConnection := TFCTConnection.Create; FoFCTConnection.FoConnection := TUniConnection.Create(nil); FoFCTConnection.DoBeforeConnect; FoFCTConnection.DoConnect; end; Result := FoFCTConnection.FoConnection; end; initialization finalization TFCTConnection.Free; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, StdCtrls, ComCtrls, ExtCtrls, frViewer, Generics.Collections; type TForm1 = class(TForm) ActionList1: TActionList; actStart: TAction; actStop: TAction; actLoad: TAction; actLoadViewer: TAction; actAddViewer: TAction; actCloseViewer: TAction; GroupBox1: TGroupBox; btnLoad: TButton; btnStart: TButton; btnStop: TButton; GroupBox2: TGroupBox; btnClient: TButton; Button1: TButton; Button2: TButton; FlowPanel1: TFlowPanel; procedure actStartExecute(Sender: TObject); procedure actStopExecute(Sender: TObject); procedure actLoadExecute(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure actLoadViewerExecute(Sender: TObject); procedure actAddViewerExecute(Sender: TObject); procedure actCloseViewerExecute(Sender: TObject); private FViewers: TObjectList<TframViewer>; public procedure AfterConstruction;override; destructor Destroy; override; end; var Form1: TForm1; implementation uses VncServerAsDll, VncViewerAsDll; {$R *.dfm} procedure TForm1.actAddViewerExecute(Sender: TObject); var options: TVNCOptionsStruct; fr: TframViewer; viewer: THandle; begin FillChar(options, SizeOf(options), 0); TVncViewerAsDll.VncViewerDll_GetOptions(@options); options.m_ViewOnly := True; options.m_NoStatus := True; options.m_ShowToolbar := False; options.m_nServerScale := 2; options.m_clearPassword := 'test'; TVncViewerAsDll.VncViewerDll_SetOptions(@options); // ts := TTabSheet.Create(PageControl1); // ts.PageControl := PageControl1; // ts.Caption := 'localhost'; fr := TframViewer.Create(FlowPanel1); fr.Name := 'viewer' + FormatDateTime('hhnnsszzz', now) + IntToStr(FViewers.Count); fr.Width := 400; fr.Height := 400; fr.Parent := FlowPanel1; FViewers.Add(fr); //make new VNC client connection viewer := TVncViewerAsDll.VncViewerDll_NewConnection('localhost', 5900); fr.EmbedViewer(viewer); end; procedure TForm1.actCloseViewerExecute(Sender: TObject); begin //TVncViewerAsDll.VncViewerDll_CloseConnection(FLastViewer); FViewers.Remove(FViewers.Last); end; procedure TForm1.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin actLoad.Enabled := not TVncServerAsDll.IsLoaded; actStart.Enabled := TVncServerAsDll.IsLoaded and not TVncServerAsDll.Started; actStop.Enabled := TVncServerAsDll.IsLoaded and TVncServerAsDll.Started; actLoadViewer.Enabled := not TVncViewerAsDll.IsLoaded; actAddViewer.Enabled := TVncViewerAsDll.IsLoaded; actCloseViewer.Enabled := TVncViewerAsDll.IsLoaded and (FViewers.Count > 0); end; procedure TForm1.actLoadExecute(Sender: TObject); begin TVncServerAsDll.Load; TVncServerAsDll.WinVNCDll_Init(HInstance); end; procedure ClientResized(aConnectionWindow: THandle);stdcall; var r: TRect; fr: TframViewer; style, exStyle: Cardinal; begin Windows.GetClientRect(aConnectionWindow, r); for fr in Form1.FViewers do begin if fr.EmbeddedViewer = aConnectionWindow then begin //update new screen size fr.Width := r.Right + 5; fr.Height := r.Bottom + 5; Windows.SetWindowPos(aConnectionWindow, 0, 0, 0, fr.Width, fr.Height, SWP_ASYNCWINDOWPOS); //remove borders, captionbar, etc style := GetWindowLong(aConnectionWindow, GWL_STYLE); exStyle := GetWindowLong(aConnectionWindow, GWL_EXSTYLE); style := style and not (WS_POPUP or WS_CAPTION or WS_BORDER or WS_THICKFRAME or WS_DLGFRAME or DS_MODALFRAME or WS_VSCROLL or WS_HSCROLL); exStyle := exStyle and not (WS_EX_DLGMODALFRAME or WS_EX_WINDOWEDGE or WS_EX_CLIENTEDGE or WS_EX_TOOLWINDOW or WS_EX_LEFTSCROLLBAR or WS_EX_RIGHTSCROLLBAR); SetWindowLong(aConnectionWindow, GWL_STYLE, style); SetWindowLong(aConnectionWindow, GWL_EXSTYLE, exStyle); //remove scrollbar Windows.ShowScrollBar(aConnectionWindow, SB_BOTH, False); end; end; end; procedure TForm1.actLoadViewerExecute(Sender: TObject); begin TVncViewerAsDll.Load; TVncViewerAsDll.VncViewerDll_Init(HInstance); TVncViewerAsDll.VncViewerDll_SetWindowSizedCallback(ClientResized); end; procedure TForm1.actStartExecute(Sender: TObject); var props: TvncPropertiesStruct; begin //create TVncServerAsDll.WinVNCDll_CreateServer; //setup FillChar(props, SizeOf(props), 0); TVncServerAsDll.WinVNCDll_GetProperties(@props); //note: properties are default or loaded from "ultravnc.ini" //we set some minimal values to allow local testing (in case of default values) props.AllowLoopback := 1; props.PortNumber := 5900; props.password := 'test'; props.password_view := 'guest'; TVncServerAsDll.WinVNCDll_SetProperties(@props); //run! TVncServerAsDll.WinVNCDll_RunServer; end; procedure TForm1.actStopExecute(Sender: TObject); begin TVncServerAsDll.WinVNCDll_DestroyServer; end; procedure TForm1.AfterConstruction; begin inherited; FViewers := TObjectList<TframViewer>.Create(True); end; destructor TForm1.Destroy; begin FViewers.Free; inherited; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.Colors.Presets; interface {$SCOPEDENUMS ON} uses System.Classes; const { At one time many computer displays were only capable of displaying 256 colors. These may be dictated by the hardware or changeable by a "color table". When a color is found (e.g., in an image) that is not one available, a different one has to be used. This can be done by either using the closest color, which greatly speeds up the load time, or by using dithering, which results in more accurate results, but takes longer to load due to the complex calculations. See Details: http://en.wikipedia.org/wiki/Web_colors } COLORS_PRESET_WEB_SAFE: array [1..216] of TIdentMapEntry = ((Value: Integer($FFFFFFCC); Name: 'Unknow'), (Value: Integer($FFFFFF99); Name: 'Unknow'), (Value: Integer($FFFFFF66); Name: 'Unknow'), (Value: Integer($FFFFFF33); Name: 'Unknow'), (Value: Integer($FFFFFF00); Name: 'Unknow'), (Value: Integer($FFCCCC00); Name: 'Unknow'), (Value: Integer($FFFFCC66); Name: 'Unknow'), (Value: Integer($FFFFCC00); Name: 'Unknow'), (Value: Integer($FFFFCC33); Name: 'Unknow'), (Value: Integer($FFCC9900); Name: 'Unknow'), (Value: Integer($FFCC9933); Name: 'Unknow'), (Value: Integer($FF996600); Name: 'Unknow'), (Value: Integer($FFFF9900); Name: 'Unknow'), (Value: Integer($FFFF9933); Name: 'Unknow'), (Value: Integer($FFCC9966); Name: 'Unknow'), (Value: Integer($FFCC6600); Name: 'Unknow'), (Value: Integer($FF996633); Name: 'Unknow'), (Value: Integer($FF663300); Name: 'Unknow'), (Value: Integer($FFFFCC99); Name: 'Unknow'), (Value: Integer($FFFF9966); Name: 'Unknow'), (Value: Integer($FFFF6600); Name: 'Unknow'), (Value: Integer($FFCC6633); Name: 'Unknow'), (Value: Integer($FF993300); Name: 'Unknow'), (Value: Integer($FF660000); Name: 'Unknow'), (Value: Integer($FFFF6633); Name: 'Unknow'), (Value: Integer($FFCC3300); Name: 'Unknow'), (Value: Integer($FFFF3300); Name: 'Unknow'), (Value: Integer($FFFF0000); Name: 'Unknow'), (Value: Integer($FFCC0000); Name: 'Unknow'), (Value: Integer($FF990000); Name: 'Unknow'), (Value: Integer($FFFFCCCC); Name: 'Unknow'), (Value: Integer($FFFF9999); Name: 'Unknow'), (Value: Integer($FFFF6666); Name: 'Unknow'), (Value: Integer($FFFF3333); Name: 'Unknow'), (Value: Integer($FFFF0033); Name: 'Unknow'), (Value: Integer($FFCC0033); Name: 'Unknow'), (Value: Integer($FFCC9999); Name: 'Unknow'), (Value: Integer($FFCC6666); Name: 'Unknow'), (Value: Integer($FFCC3333); Name: 'Unknow'), (Value: Integer($FF993333); Name: 'Unknow'), (Value: Integer($FF990033); Name: 'Unknow'), (Value: Integer($FF330000); Name: 'Unknow'), (Value: Integer($FFFF6699); Name: 'Unknow'), (Value: Integer($FFFF3366); Name: 'Unknow'), (Value: Integer($FFFF0066); Name: 'Unknow'), (Value: Integer($FFCC3366); Name: 'Unknow'), (Value: Integer($FF996666); Name: 'Unknow'), (Value: Integer($FF663333); Name: 'Unknow'), (Value: Integer($FFFF99CC); Name: 'Unknow'), (Value: Integer($FFFF3399); Name: 'Unknow'), (Value: Integer($FFFF0099); Name: 'Unknow'), (Value: Integer($FFCC0066); Name: 'Unknow'), (Value: Integer($FF993366); Name: 'Unknow'), (Value: Integer($FF660033); Name: 'Unknow'), (Value: Integer($FFFF66CC); Name: 'Unknow'), (Value: Integer($FFFF00CC); Name: 'Unknow'), (Value: Integer($FFFF33CC); Name: 'Unknow'), (Value: Integer($FFCC6699); Name: 'Unknow'), (Value: Integer($FFCC0099); Name: 'Unknow'), (Value: Integer($FF990066); Name: 'Unknow'), (Value: Integer($FFFFCCFF); Name: 'Unknow'), (Value: Integer($FFFF99FF); Name: 'Unknow'), (Value: Integer($FFFF66FF); Name: 'Unknow'), (Value: Integer($FFFF33FF); Name: 'Unknow'), (Value: Integer($FFFF00FF); Name: 'Unknow'), (Value: Integer($FFCC3399); Name: 'Unknow'), (Value: Integer($FFCC99CC); Name: 'Unknow'), (Value: Integer($FFCC66CC); Name: 'Unknow'), (Value: Integer($FFCC00CC); Name: 'Unknow'), (Value: Integer($FFCC33CC); Name: 'Unknow'), (Value: Integer($FF990099); Name: 'Unknow'), (Value: Integer($FF993399); Name: 'Unknow'), (Value: Integer($FFCC66FF); Name: 'Unknow'), (Value: Integer($FFCC33FF); Name: 'Unknow'), (Value: Integer($FFCC00FF); Name: 'Unknow'), (Value: Integer($FF9900CC); Name: 'Unknow'), (Value: Integer($FF996699); Name: 'Unknow'), (Value: Integer($FF660066); Name: 'Unknow'), (Value: Integer($FFCC99FF); Name: 'Unknow'), (Value: Integer($FF9933CC); Name: 'Unknow'), (Value: Integer($FF9933FF); Name: 'Unknow'), (Value: Integer($FF9900FF); Name: 'Unknow'), (Value: Integer($FF660099); Name: 'Unknow'), (Value: Integer($FF663366); Name: 'Unknow'), (Value: Integer($FF9966CC); Name: 'Unknow'), (Value: Integer($FF9966FF); Name: 'Unknow'), (Value: Integer($FF6600CC); Name: 'Unknow'), (Value: Integer($FF6633CC); Name: 'Unknow'), (Value: Integer($FF663399); Name: 'Unknow'), (Value: Integer($FF330033); Name: 'Unknow'), (Value: Integer($FFCCCCFF); Name: 'Unknow'), (Value: Integer($FF9999FF); Name: 'Unknow'), (Value: Integer($FF6633FF); Name: 'Unknow'), (Value: Integer($FF6600FF); Name: 'Unknow'), (Value: Integer($FF330099); Name: 'Unknow'), (Value: Integer($FF330066); Name: 'Unknow'), (Value: Integer($FF9999CC); Name: 'Unknow'), (Value: Integer($FF6666FF); Name: 'Unknow'), (Value: Integer($FF6666CC); Name: 'Unknow'), (Value: Integer($FF666699); Name: 'Unknow'), (Value: Integer($FF333399); Name: 'Unknow'), (Value: Integer($FF333366); Name: 'Unknow'), (Value: Integer($FF3333FF); Name: 'Unknow'), (Value: Integer($FF3300FF); Name: 'Unknow'), (Value: Integer($FF3300CC); Name: 'Unknow'), (Value: Integer($FF3333CC); Name: 'Unknow'), (Value: Integer($FF000099); Name: 'Unknow'), (Value: Integer($FF000066); Name: 'Unknow'), (Value: Integer($FF6699FF); Name: 'Unknow'), (Value: Integer($FF3366FF); Name: 'Unknow'), (Value: Integer($FF0000FF); Name: 'Unknow'), (Value: Integer($FF0000CC); Name: 'Unknow'), (Value: Integer($FF0033CC); Name: 'Unknow'), (Value: Integer($FF000033); Name: 'Unknow'), (Value: Integer($FF0066FF); Name: 'Unknow'), (Value: Integer($FF0066CC); Name: 'Unknow'), (Value: Integer($FF3366CC); Name: 'Unknow'), (Value: Integer($FF0033FF); Name: 'Unknow'), (Value: Integer($FF003399); Name: 'Unknow'), (Value: Integer($FF003366); Name: 'Unknow'), (Value: Integer($FF99CCFF); Name: 'Unknow'), (Value: Integer($FF3399FF); Name: 'Unknow'), (Value: Integer($FF0099FF); Name: 'Unknow'), (Value: Integer($FF6699CC); Name: 'Unknow'), (Value: Integer($FF336699); Name: 'Unknow'), (Value: Integer($FF006699); Name: 'Unknow'), (Value: Integer($FF66CCFF); Name: 'Unknow'), (Value: Integer($FF33CCFF); Name: 'Unknow'), (Value: Integer($FF00CCFF); Name: 'Unknow'), (Value: Integer($FF3399CC); Name: 'Unknow'), (Value: Integer($FF0099CC); Name: 'Unknow'), (Value: Integer($FF003333); Name: 'Unknow'), (Value: Integer($FF99CCCC); Name: 'Unknow'), (Value: Integer($FF66CCCC); Name: 'Unknow'), (Value: Integer($FF339999); Name: 'Unknow'), (Value: Integer($FF669999); Name: 'Unknow'), (Value: Integer($FF006666); Name: 'Unknow'), (Value: Integer($FF336666); Name: 'Unknow'), (Value: Integer($FFCCFFFF); Name: 'Unknow'), (Value: Integer($FF99FFFF); Name: 'Unknow'), (Value: Integer($FF66FFFF); Name: 'Unknow'), (Value: Integer($FF33FFFF); Name: 'Unknow'), (Value: Integer($FF00FFFF); Name: 'Unknow'), (Value: Integer($FF00CCCC); Name: 'Unknow'), (Value: Integer($FF99FFCC); Name: 'Unknow'), (Value: Integer($FF66FFCC); Name: 'Unknow'), (Value: Integer($FF33FFCC); Name: 'Unknow'), (Value: Integer($FF00FFCC); Name: 'Unknow'), (Value: Integer($FF33CCCC); Name: 'Unknow'), (Value: Integer($FF009999); Name: 'Unknow'), (Value: Integer($FF66CC99); Name: 'Unknow'), (Value: Integer($FF33CC99); Name: 'Unknow'), (Value: Integer($FF00CC99); Name: 'Unknow'), (Value: Integer($FF339966); Name: 'Unknow'), (Value: Integer($FF009966); Name: 'Unknow'), (Value: Integer($FF006633); Name: 'Unknow'), (Value: Integer($FF66FF99); Name: 'Unknow'), (Value: Integer($FF33FF99); Name: 'Unknow'), (Value: Integer($FF00FF99); Name: 'Unknow'), (Value: Integer($FF33CC66); Name: 'Unknow'), (Value: Integer($FF00CC66); Name: 'Unknow'), (Value: Integer($FF009933); Name: 'Unknow'), (Value: Integer($FF99FF99); Name: 'Unknow'), (Value: Integer($FF66FF66); Name: 'Unknow'), (Value: Integer($FF33FF66); Name: 'Unknow'), (Value: Integer($FF00FF66); Name: 'Unknow'), (Value: Integer($FF339933); Name: 'Unknow'), (Value: Integer($FF006600); Name: 'Unknow'), (Value: Integer($FFCCFFCC); Name: 'Unknow'), (Value: Integer($FF99CC99); Name: 'Unknow'), (Value: Integer($FF66CC66); Name: 'Unknow'), (Value: Integer($FF669966); Name: 'Unknow'), (Value: Integer($FF336633); Name: 'Unknow'), (Value: Integer($FF003300); Name: 'Unknow'), (Value: Integer($FF33FF33); Name: 'Unknow'), (Value: Integer($FF00FF33); Name: 'Unknow'), (Value: Integer($FF00FF00); Name: 'Unknow'), (Value: Integer($FF00CC00); Name: 'Unknow'), (Value: Integer($FF33CC33); Name: 'Unknow'), (Value: Integer($FF00CC33); Name: 'Unknow'), (Value: Integer($FF66FF00); Name: 'Unknow'), (Value: Integer($FF66FF33); Name: 'Unknow'), (Value: Integer($FF33FF00); Name: 'Unknow'), (Value: Integer($FF33CC00); Name: 'Unknow'), (Value: Integer($FF339900); Name: 'Unknow'), (Value: Integer($FF009900); Name: 'Unknow'), (Value: Integer($FFCCFF99); Name: 'Unknow'), (Value: Integer($FF99FF66); Name: 'Unknow'), (Value: Integer($FF66CC00); Name: 'Unknow'), (Value: Integer($FF66CC33); Name: 'Unknow'), (Value: Integer($FF669933); Name: 'Unknow'), (Value: Integer($FF336600); Name: 'Unknow'), (Value: Integer($FF99FF00); Name: 'Unknow'), (Value: Integer($FF99FF33); Name: 'Unknow'), (Value: Integer($FF99CC66); Name: 'Unknow'), (Value: Integer($FF99CC00); Name: 'Unknow'), (Value: Integer($FF99CC33); Name: 'Unknow'), (Value: Integer($FF669900); Name: 'Unknow'), (Value: Integer($FFCCFF66); Name: 'Unknow'), (Value: Integer($FFCCFF00); Name: 'Unknow'), (Value: Integer($FFCCFF33); Name: 'Unknow'), (Value: Integer($FFCCCC99); Name: 'Unknow'), (Value: Integer($FF666633); Name: 'Unknow'), (Value: Integer($FF333300); Name: 'Unknow'), (Value: Integer($FFCCCC66); Name: 'Unknow'), (Value: Integer($FFCCCC33); Name: 'Unknow'), (Value: Integer($FF999966); Name: 'Unknow'), (Value: Integer($FF999933); Name: 'Unknow'), (Value: Integer($FF999900); Name: 'Unknow'), (Value: Integer($FF666600); Name: 'Unknow'), (Value: Integer($FFFFFFFF); Name: 'Unknow'), (Value: Integer($FFCCCCCC); Name: 'Unknow'), (Value: Integer($FF999999); Name: 'Unknow'), (Value: Integer($FF666666); Name: 'Unknow'), (Value: Integer($FF333333); Name: 'Unknow'), (Value: Integer($FF000000); Name: 'Unknow')); { The list of colors actually shipped with the X11 product varies between implementations, and clashes with certain of the HTML names such as green. Furthermore, X11 colors are defined as simple RGB (hence, no particular color space), rather than sRGB. This means that the list of colors found in X11 (e.g. in /usr/lib/X11/rgb.txt) should not directly be used to choose colors for the web.[8] See Details: http://en.wikipedia.org/wiki/Web_colors File with all RGB colors: http://cvsweb.xfree86.org/cvsweb/xc/programs/rgb/rgb.txt Standart X11: http://www.w3.org/TR/SVG/types.html#ColorKeywords } COLORS_PRESET_X11: array [1..657] of TIdentMapEntry = ((Value: Integer($FFFFFAFA); Name: 'Snow'), (Value: Integer($FFF8F8FF); Name: 'GhostWhite'), (Value: Integer($FFF5F5F5); Name: 'WhiteSmoke'), (Value: Integer($FFDCDCDC); Name: 'Gainsboro'), (Value: Integer($FFFFFAF0); Name: 'FloralWhite'), (Value: Integer($FFFDF5E6); Name: 'OldLace'), (Value: Integer($FFFAF0E6); Name: 'Linen'), (Value: Integer($FFFAEBD7); Name: 'AntiqueWhite'), (Value: Integer($FFFFEFD5); Name: 'PapayaWhip'), (Value: Integer($FFFFEBCD); Name: 'BlanchedAlmond'), (Value: Integer($FFFFE4C4); Name: 'Bisque'), (Value: Integer($FFFFDAB9); Name: 'PeachPuff'), (Value: Integer($FFFFDEAD); Name: 'NavajoWhite'), (Value: Integer($FFFFE4B5); Name: 'Moccasin'), (Value: Integer($FFFFF8DC); Name: 'Cornsilk'), (Value: Integer($FFFFFFF0); Name: 'Ivory'), (Value: Integer($FFFFFACD); Name: 'LemonChiffon'), (Value: Integer($FFFFF5EE); Name: 'Seashell'), (Value: Integer($FFF0FFF0); Name: 'Honeydew'), (Value: Integer($FFF5FFFA); Name: 'MintCream'), (Value: Integer($FFF0FFFF); Name: 'Azure'), (Value: Integer($FFF0F8FF); Name: 'AliceBlue'), (Value: Integer($FFE6E6FA); Name: 'Lavender'), (Value: Integer($FFFFF0F5); Name: 'LavenderBlush'), (Value: Integer($FFFFE4E1); Name: 'MistyRose'), (Value: Integer($FFFFFFFF); Name: 'White'), (Value: Integer($FF000000); Name: 'Black'), (Value: Integer($FF2F4F4F); Name: 'DarkSlateGray'), (Value: Integer($FF2F4F4F); Name: 'DarkSlateGrey'), (Value: Integer($FF696969); Name: 'DimGray'), (Value: Integer($FF696969); Name: 'DimGrey'), (Value: Integer($FF708090); Name: 'SlateGray'), (Value: Integer($FF708090); Name: 'SlateGrey'), (Value: Integer($FF778899); Name: 'LightSlateGray'), (Value: Integer($FF778899); Name: 'LightSlateGrey'), (Value: Integer($FFBEBEBE); Name: 'Gray'), (Value: Integer($FFBEBEBE); Name: 'Grey'), (Value: Integer($FFD3D3D3); Name: 'LightGrey'), (Value: Integer($FFD3D3D3); Name: 'LightGray'), (Value: Integer($FF191970); Name: 'MidnightBlue'), (Value: Integer($FF000080); Name: 'Navy'), (Value: Integer($FF000080); Name: 'NavyBlue'), (Value: Integer($FF6495ED); Name: 'CornflowerBlue'), (Value: Integer($FF483D8B); Name: 'DarkSlateBlue'), (Value: Integer($FF6A5ACD); Name: 'SlateBlue'), (Value: Integer($FF7B68EE); Name: 'MediumSlateBlue'), (Value: Integer($FF8470FF); Name: 'LightSlateBlue'), (Value: Integer($FF0000CD); Name: 'MediumBlue'), (Value: Integer($FF4169E1); Name: 'RoyalBlue'), (Value: Integer($FF0000FF); Name: 'Blue'), (Value: Integer($FF1E90FF); Name: 'DodgerBlue'), (Value: Integer($FF00BFFF); Name: 'DeepSkyBlue'), (Value: Integer($FF87CEEB); Name: 'SkyBlue'), (Value: Integer($FF87CEFA); Name: 'LightSkyBlue'), (Value: Integer($FF4682B4); Name: 'SteelBlue'), (Value: Integer($FFB0C4DE); Name: 'LightSteelBlue'), (Value: Integer($FFADD8E6); Name: 'LightBlue'), (Value: Integer($FFB0E0E6); Name: 'PowderBlue'), (Value: Integer($FFAFEEEE); Name: 'PaleTurquoise'), (Value: Integer($FF00CED1); Name: 'DarkTurquoise'), (Value: Integer($FF48D1CC); Name: 'MediumTurquoise'), (Value: Integer($FF40E0D0); Name: 'Turquoise'), (Value: Integer($FF00FFFF); Name: 'Cyan'), (Value: Integer($FFE0FFFF); Name: 'LightCyan'), (Value: Integer($FF5F9EA0); Name: 'CadetBlue'), (Value: Integer($FF66CDAA); Name: 'MediumAquamarine'), (Value: Integer($FF7FFFD4); Name: 'Aquamarine'), (Value: Integer($FF006400); Name: 'DarkGreen'), (Value: Integer($FF556B2F); Name: 'DarkOliveGreen'), (Value: Integer($FF8FBC8F); Name: 'DarkSeaGreen'), (Value: Integer($FF2E8B57); Name: 'SeaGreen'), (Value: Integer($FF3CB371); Name: 'MediumSeaGreen'), (Value: Integer($FF20B2AA); Name: 'LightSeaGreen'), (Value: Integer($FF98FB98); Name: 'PaleGreen'), (Value: Integer($FF00FF7F); Name: 'SpringGreen'), (Value: Integer($FF7CFC00); Name: 'LawnGreen'), (Value: Integer($FF00FF00); Name: 'Green'), (Value: Integer($FF7FFF00); Name: 'Chartreuse'), (Value: Integer($FF00FA9A); Name: 'MediumSpringGreen'), (Value: Integer($FFADFF2F); Name: 'GreenYellow'), (Value: Integer($FF32CD32); Name: 'LimeGreen'), (Value: Integer($FF9ACD32); Name: 'YellowGreen'), (Value: Integer($FF228B22); Name: 'ForestGreen'), (Value: Integer($FF6B8E23); Name: 'OliveDrab'), (Value: Integer($FFBDB76B); Name: 'DarkKhaki'), (Value: Integer($FFF0E68C); Name: 'Khaki'), (Value: Integer($FFEEE8AA); Name: 'PaleGoldenrod'), (Value: Integer($FFFAFAD2); Name: 'LightGoldenrodYellow'), (Value: Integer($FFFFFFE0); Name: 'LightYellow'), (Value: Integer($FFFFFF00); Name: 'Yellow'), (Value: Integer($FFFFD700); Name: 'Gold'), (Value: Integer($FFEEDD82); Name: 'LightGoldenrod'), (Value: Integer($FFDAA520); Name: 'Goldenrod'), (Value: Integer($FFB8860B); Name: 'DarkGoldenrod'), (Value: Integer($FFBC8F8F); Name: 'RosyBrown'), (Value: Integer($FFCD5C5C); Name: 'IndianRed'), (Value: Integer($FF8B4513); Name: 'SaddleBrown'), (Value: Integer($FFA0522D); Name: 'Sienna'), (Value: Integer($FFCD853F); Name: 'Peru'), (Value: Integer($FFDEB887); Name: 'Burlywood'), (Value: Integer($FFF5F5DC); Name: 'Beige'), (Value: Integer($FFF5DEB3); Name: 'Wheat'), (Value: Integer($FFF4A460); Name: 'SandyBrown'), (Value: Integer($FFD2B48C); Name: 'Tan'), (Value: Integer($FFD2691E); Name: 'Chocolate'), (Value: Integer($FFB22222); Name: 'Firebrick'), (Value: Integer($FFA52A2A); Name: 'Brown'), (Value: Integer($FFE9967A); Name: 'DarkSalmon'), (Value: Integer($FFFA8072); Name: 'Salmon'), (Value: Integer($FFFFA07A); Name: 'LightSalmon'), (Value: Integer($FFFFA500); Name: 'Orange'), (Value: Integer($FFFF8C00); Name: 'DarkOrange'), (Value: Integer($FFFF7F50); Name: 'Coral'), (Value: Integer($FFF08080); Name: 'LightCoral'), (Value: Integer($FFFF6347); Name: 'Tomato'), (Value: Integer($FFFF4500); Name: 'OrangeRed'), (Value: Integer($FFFF0000); Name: 'Red'), (Value: Integer($FFFF69B4); Name: 'HotPink'), (Value: Integer($FFFF1493); Name: 'DeepPink'), (Value: Integer($FFFFC0CB); Name: 'Pink'), (Value: Integer($FFFFB6C1); Name: 'LightPink'), (Value: Integer($FFDB7093); Name: 'PaleVioletRed'), (Value: Integer($FFB03060); Name: 'Maroon'), (Value: Integer($FFC71585); Name: 'MediumVioletRed'), (Value: Integer($FFD02090); Name: 'VioletRed'), (Value: Integer($FFFF00FF); Name: 'Magenta'), (Value: Integer($FFEE82EE); Name: 'Violet'), (Value: Integer($FFDDA0DD); Name: 'Plum'), (Value: Integer($FFDA70D6); Name: 'Orchid'), (Value: Integer($FFBA55D3); Name: 'MediumOrchid'), (Value: Integer($FF9932CC); Name: 'DarkOrchid'), (Value: Integer($FF9400D3); Name: 'DarkViolet'), (Value: Integer($FF8A2BE2); Name: 'BlueViolet'), (Value: Integer($FFA020F0); Name: 'Purple'), (Value: Integer($FF9370DB); Name: 'MediumPurple'), (Value: Integer($FFD8BFD8); Name: 'Thistle'), (Value: Integer($FFFFFAFA); Name: 'Snow1'), (Value: Integer($FFEEE9E9); Name: 'Snow2'), (Value: Integer($FFCDC9C9); Name: 'Snow3'), (Value: Integer($FF8B8989); Name: 'Snow4'), (Value: Integer($FFFFF5EE); Name: 'Seashell1'), (Value: Integer($FFEEE5DE); Name: 'Seashell2'), (Value: Integer($FFCDC5BF); Name: 'Seashell3'), (Value: Integer($FF8B8682); Name: 'Seashell4'), (Value: Integer($FFFFEFDB); Name: 'AntiqueWhite1'), (Value: Integer($FFEEDFCC); Name: 'AntiqueWhite2'), (Value: Integer($FFCDC0B0); Name: 'AntiqueWhite3'), (Value: Integer($FF8B8378); Name: 'AntiqueWhite4'), (Value: Integer($FFFFE4C4); Name: 'Bisque1'), (Value: Integer($FFEED5B7); Name: 'Bisque2'), (Value: Integer($FFCDB79E); Name: 'Bisque3'), (Value: Integer($FF8B7D6B); Name: 'Bisque4'), (Value: Integer($FFFFDAB9); Name: 'PeachPuff1'), (Value: Integer($FFEECBAD); Name: 'PeachPuff2'), (Value: Integer($FFCDAF95); Name: 'PeachPuff3'), (Value: Integer($FF8B7765); Name: 'PeachPuff4'), (Value: Integer($FFFFDEAD); Name: 'NavajoWhite1'), (Value: Integer($FFEECFA1); Name: 'NavajoWhite2'), (Value: Integer($FFCDB38B); Name: 'NavajoWhite3'), (Value: Integer($FF8B795E); Name: 'NavajoWhite4'), (Value: Integer($FFFFFACD); Name: 'LemonChiffon1'), (Value: Integer($FFEEE9BF); Name: 'LemonChiffon2'), (Value: Integer($FFCDC9A5); Name: 'LemonChiffon3'), (Value: Integer($FF8B8970); Name: 'LemonChiffon4'), (Value: Integer($FFFFF8DC); Name: 'Cornsilk1'), (Value: Integer($FFEEE8CD); Name: 'Cornsilk2'), (Value: Integer($FFCDC8B1); Name: 'Cornsilk3'), (Value: Integer($FF8B8878); Name: 'Cornsilk4'), (Value: Integer($FFFFFFF0); Name: 'Ivory1'), (Value: Integer($FFEEEEE0); Name: 'Ivory2'), (Value: Integer($FFCDCDC1); Name: 'Ivory3'), (Value: Integer($FF8B8B83); Name: 'Ivory4'), (Value: Integer($FFF0FFF0); Name: 'Honeydew1'), (Value: Integer($FFE0EEE0); Name: 'Honeydew2'), (Value: Integer($FFC1CDC1); Name: 'Honeydew3'), (Value: Integer($FF838B83); Name: 'Honeydew4'), (Value: Integer($FFFFF0F5); Name: 'LavenderBlush1'), (Value: Integer($FFEEE0E5); Name: 'LavenderBlush2'), (Value: Integer($FFCDC1C5); Name: 'LavenderBlush3'), (Value: Integer($FF8B8386); Name: 'LavenderBlush4'), (Value: Integer($FFFFE4E1); Name: 'MistyRose1'), (Value: Integer($FFEED5D2); Name: 'MistyRose2'), (Value: Integer($FFCDB7B5); Name: 'MistyRose3'), (Value: Integer($FF8B7D7B); Name: 'MistyRose4'), (Value: Integer($FFF0FFFF); Name: 'Azure1'), (Value: Integer($FFE0EEEE); Name: 'Azure2'), (Value: Integer($FFC1CDCD); Name: 'Azure3'), (Value: Integer($FF838B8B); Name: 'Azure4'), (Value: Integer($FF836FFF); Name: 'SlateBlue1'), (Value: Integer($FF7A67EE); Name: 'SlateBlue2'), (Value: Integer($FF6959CD); Name: 'SlateBlue3'), (Value: Integer($FF473C8B); Name: 'SlateBlue4'), (Value: Integer($FF4876FF); Name: 'RoyalBlue1'), (Value: Integer($FF436EEE); Name: 'RoyalBlue2'), (Value: Integer($FF3A5FCD); Name: 'RoyalBlue3'), (Value: Integer($FF27408B); Name: 'RoyalBlue4'), (Value: Integer($FF0000FF); Name: 'Blue1'), (Value: Integer($FF0000EE); Name: 'Blue2'), (Value: Integer($FF0000CD); Name: 'Blue3'), (Value: Integer($FF00008B); Name: 'Blue4'), (Value: Integer($FF1E90FF); Name: 'DodgerBlue1'), (Value: Integer($FF1C86EE); Name: 'DodgerBlue2'), (Value: Integer($FF1874CD); Name: 'DodgerBlue3'), (Value: Integer($FF104E8B); Name: 'DodgerBlue4'), (Value: Integer($FF63B8FF); Name: 'SteelBlue1'), (Value: Integer($FF5CACEE); Name: 'SteelBlue2'), (Value: Integer($FF4F94CD); Name: 'SteelBlue3'), (Value: Integer($FF36648B); Name: 'SteelBlue4'), (Value: Integer($FF00BFFF); Name: 'DeepSkyBlue1'), (Value: Integer($FF00B2EE); Name: 'DeepSkyBlue2'), (Value: Integer($FF009ACD); Name: 'DeepSkyBlue3'), (Value: Integer($FF00688B); Name: 'DeepSkyBlue4'), (Value: Integer($FF87CEFF); Name: 'SkyBlue1'), (Value: Integer($FF7EC0EE); Name: 'SkyBlue2'), (Value: Integer($FF6CA6CD); Name: 'SkyBlue3'), (Value: Integer($FF4A708B); Name: 'SkyBlue4'), (Value: Integer($FFB0E2FF); Name: 'LightSkyBlue1'), (Value: Integer($FFA4D3EE); Name: 'LightSkyBlue2'), (Value: Integer($FF8DB6CD); Name: 'LightSkyBlue3'), (Value: Integer($FF607B8B); Name: 'LightSkyBlue4'), (Value: Integer($FFC6E2FF); Name: 'SlateGray1'), (Value: Integer($FFB9D3EE); Name: 'SlateGray2'), (Value: Integer($FF9FB6CD); Name: 'SlateGray3'), (Value: Integer($FF6C7B8B); Name: 'SlateGray4'), (Value: Integer($FFCAE1FF); Name: 'LightSteelBlue1'), (Value: Integer($FFBCD2EE); Name: 'LightSteelBlue2'), (Value: Integer($FFA2B5CD); Name: 'LightSteelBlue3'), (Value: Integer($FF6E7B8B); Name: 'LightSteelBlue4'), (Value: Integer($FFBFEFFF); Name: 'LightBlue1'), (Value: Integer($FFB2DFEE); Name: 'LightBlue2'), (Value: Integer($FF9AC0CD); Name: 'LightBlue3'), (Value: Integer($FF68838B); Name: 'LightBlue4'), (Value: Integer($FFE0FFFF); Name: 'LightCyan1'), (Value: Integer($FFD1EEEE); Name: 'LightCyan2'), (Value: Integer($FFB4CDCD); Name: 'LightCyan3'), (Value: Integer($FF7A8B8B); Name: 'LightCyan4'), (Value: Integer($FFBBFFFF); Name: 'PaleTurquoise1'), (Value: Integer($FFAEEEEE); Name: 'PaleTurquoise2'), (Value: Integer($FF96CDCD); Name: 'PaleTurquoise3'), (Value: Integer($FF668B8B); Name: 'PaleTurquoise4'), (Value: Integer($FF98F5FF); Name: 'CadetBlue1'), (Value: Integer($FF8EE5EE); Name: 'CadetBlue2'), (Value: Integer($FF7AC5CD); Name: 'CadetBlue3'), (Value: Integer($FF53868B); Name: 'CadetBlue4'), (Value: Integer($FF00F5FF); Name: 'Turquoise1'), (Value: Integer($FF00E5EE); Name: 'Turquoise2'), (Value: Integer($FF00C5CD); Name: 'Turquoise3'), (Value: Integer($FF00868B); Name: 'Turquoise4'), (Value: Integer($FF00FFFF); Name: 'Cyan1'), (Value: Integer($FF00EEEE); Name: 'Cyan2'), (Value: Integer($FF00CDCD); Name: 'Cyan3'), (Value: Integer($FF008B8B); Name: 'Cyan4'), (Value: Integer($FF97FFFF); Name: 'DarkSlateGray1'), (Value: Integer($FF8DEEEE); Name: 'DarkSlateGray2'), (Value: Integer($FF79CDCD); Name: 'DarkSlateGray3'), (Value: Integer($FF528B8B); Name: 'DarkSlateGray4'), (Value: Integer($FF7FFFD4); Name: 'Aquamarine1'), (Value: Integer($FF76EEC6); Name: 'Aquamarine2'), (Value: Integer($FF66CDAA); Name: 'Aquamarine3'), (Value: Integer($FF458B74); Name: 'Aquamarine4'), (Value: Integer($FFC1FFC1); Name: 'DarkSeaGreen1'), (Value: Integer($FFB4EEB4); Name: 'DarkSeaGreen2'), (Value: Integer($FF9BCD9B); Name: 'DarkSeaGreen3'), (Value: Integer($FF698B69); Name: 'DarkSeaGreen4'), (Value: Integer($FF54FF9F); Name: 'SeaGreen1'), (Value: Integer($FF4EEE94); Name: 'SeaGreen2'), (Value: Integer($FF43CD80); Name: 'SeaGreen3'), (Value: Integer($FF2E8B57); Name: 'SeaGreen4'), (Value: Integer($FF9AFF9A); Name: 'PaleGreen1'), (Value: Integer($FF90EE90); Name: 'PaleGreen2'), (Value: Integer($FF7CCD7C); Name: 'PaleGreen3'), (Value: Integer($FF548B54); Name: 'PaleGreen4'), (Value: Integer($FF00FF7F); Name: 'SpringGreen1'), (Value: Integer($FF00EE76); Name: 'SpringGreen2'), (Value: Integer($FF00CD66); Name: 'SpringGreen3'), (Value: Integer($FF008B45); Name: 'SpringGreen4'), (Value: Integer($FF00FF00); Name: 'Green1'), (Value: Integer($FF00EE00); Name: 'Green2'), (Value: Integer($FF00CD00); Name: 'Green3'), (Value: Integer($FF008B00); Name: 'Green4'), (Value: Integer($FF7FFF00); Name: 'Chartreuse1'), (Value: Integer($FF76EE00); Name: 'Chartreuse2'), (Value: Integer($FF66CD00); Name: 'Chartreuse3'), (Value: Integer($FF458B00); Name: 'Chartreuse4'), (Value: Integer($FFC0FF3E); Name: 'OliveDrab1'), (Value: Integer($FFB3EE3A); Name: 'OliveDrab2'), (Value: Integer($FF9ACD32); Name: 'OliveDrab3'), (Value: Integer($FF698B22); Name: 'OliveDrab4'), (Value: Integer($FFCAFF70); Name: 'DarkOliveGreen1'), (Value: Integer($FFBCEE68); Name: 'DarkOliveGreen2'), (Value: Integer($FFA2CD5A); Name: 'DarkOliveGreen3'), (Value: Integer($FF6E8B3D); Name: 'DarkOliveGreen4'), (Value: Integer($FFFFF68F); Name: 'Khaki1'), (Value: Integer($FFEEE685); Name: 'Khaki2'), (Value: Integer($FFCDC673); Name: 'Khaki3'), (Value: Integer($FF8B864E); Name: 'Khaki4'), (Value: Integer($FFFFEC8B); Name: 'LightGoldenrod1'), (Value: Integer($FFEEDC82); Name: 'LightGoldenrod2'), (Value: Integer($FFCDBE70); Name: 'LightGoldenrod3'), (Value: Integer($FF8B814C); Name: 'LightGoldenrod4'), (Value: Integer($FFFFFFE0); Name: 'LightYellow1'), (Value: Integer($FFEEEED1); Name: 'LightYellow2'), (Value: Integer($FFCDCDB4); Name: 'LightYellow3'), (Value: Integer($FF8B8B7A); Name: 'LightYellow4'), (Value: Integer($FFFFFF00); Name: 'Yellow1'), (Value: Integer($FFEEEE00); Name: 'Yellow2'), (Value: Integer($FFCDCD00); Name: 'Yellow3'), (Value: Integer($FF8B8B00); Name: 'Yellow4'), (Value: Integer($FFFFD700); Name: 'Gold1'), (Value: Integer($FFEEC900); Name: 'Gold2'), (Value: Integer($FFCDAD00); Name: 'Gold3'), (Value: Integer($FF8B7500); Name: 'Gold4'), (Value: Integer($FFFFC125); Name: 'Goldenrod1'), (Value: Integer($FFEEB422); Name: 'Goldenrod2'), (Value: Integer($FFCD9B1D); Name: 'Goldenrod3'), (Value: Integer($FF8B6914); Name: 'Goldenrod4'), (Value: Integer($FFFFB90F); Name: 'DarkGoldenrod1'), (Value: Integer($FFEEAD0E); Name: 'DarkGoldenrod2'), (Value: Integer($FFCD950C); Name: 'DarkGoldenrod3'), (Value: Integer($FF8B6508); Name: 'DarkGoldenrod4'), (Value: Integer($FFFFC1C1); Name: 'RosyBrown1'), (Value: Integer($FFEEB4B4); Name: 'RosyBrown2'), (Value: Integer($FFCD9B9B); Name: 'RosyBrown3'), (Value: Integer($FF8B6969); Name: 'RosyBrown4'), (Value: Integer($FFFF6A6A); Name: 'IndianRed1'), (Value: Integer($FFEE6363); Name: 'IndianRed2'), (Value: Integer($FFCD5555); Name: 'IndianRed3'), (Value: Integer($FF8B3A3A); Name: 'IndianRed4'), (Value: Integer($FFFF8247); Name: 'Sienna1'), (Value: Integer($FFEE7942); Name: 'Sienna2'), (Value: Integer($FFCD6839); Name: 'Sienna3'), (Value: Integer($FF8B4726); Name: 'Sienna4'), (Value: Integer($FFFFD39B); Name: 'Burlywood1'), (Value: Integer($FFEEC591); Name: 'Burlywood2'), (Value: Integer($FFCDAA7D); Name: 'Burlywood3'), (Value: Integer($FF8B7355); Name: 'Burlywood4'), (Value: Integer($FFFFE7BA); Name: 'Wheat1'), (Value: Integer($FFEED8AE); Name: 'Wheat2'), (Value: Integer($FFCDBA96); Name: 'Wheat3'), (Value: Integer($FF8B7E66); Name: 'Wheat4'), (Value: Integer($FFFFA54F); Name: 'Tan1'), (Value: Integer($FFEE9A49); Name: 'Tan2'), (Value: Integer($FFCD853F); Name: 'Tan3'), (Value: Integer($FF8B5A2B); Name: 'Tan4'), (Value: Integer($FFFF7F24); Name: 'Chocolate1'), (Value: Integer($FFEE7621); Name: 'Chocolate2'), (Value: Integer($FFCD661D); Name: 'Chocolate3'), (Value: Integer($FF8B4513); Name: 'Chocolate4'), (Value: Integer($FFFF3030); Name: 'Firebrick1'), (Value: Integer($FFEE2C2C); Name: 'Firebrick2'), (Value: Integer($FFCD2626); Name: 'Firebrick3'), (Value: Integer($FF8B1A1A); Name: 'Firebrick4'), (Value: Integer($FFFF4040); Name: 'Brown1'), (Value: Integer($FFEE3B3B); Name: 'Brown2'), (Value: Integer($FFCD3333); Name: 'Brown3'), (Value: Integer($FF8B2323); Name: 'Brown4'), (Value: Integer($FFFF8C69); Name: 'Salmon1'), (Value: Integer($FFEE8262); Name: 'Salmon2'), (Value: Integer($FFCD7054); Name: 'Salmon3'), (Value: Integer($FF8B4C39); Name: 'Salmon4'), (Value: Integer($FFFFA07A); Name: 'LightSalmon1'), (Value: Integer($FFEE9572); Name: 'LightSalmon2'), (Value: Integer($FFCD8162); Name: 'LightSalmon3'), (Value: Integer($FF8B5742); Name: 'LightSalmon4'), (Value: Integer($FFFFA500); Name: 'Orange1'), (Value: Integer($FFEE9A00); Name: 'Orange2'), (Value: Integer($FFCD8500); Name: 'Orange3'), (Value: Integer($FF8B5A00); Name: 'Orange4'), (Value: Integer($FFFF7F00); Name: 'DarkOrange1'), (Value: Integer($FFEE7600); Name: 'DarkOrange2'), (Value: Integer($FFCD6600); Name: 'DarkOrange3'), (Value: Integer($FF8B4500); Name: 'DarkOrange4'), (Value: Integer($FFFF7256); Name: 'Coral1'), (Value: Integer($FFEE6A50); Name: 'Coral2'), (Value: Integer($FFCD5B45); Name: 'Coral3'), (Value: Integer($FF8B3E2F); Name: 'Coral4'), (Value: Integer($FFFF6347); Name: 'Tomato1'), (Value: Integer($FFEE5C42); Name: 'Tomato2'), (Value: Integer($FFCD4F39); Name: 'Tomato3'), (Value: Integer($FF8B3626); Name: 'Tomato4'), (Value: Integer($FFFF4500); Name: 'OrangeRed1'), (Value: Integer($FFEE4000); Name: 'OrangeRed2'), (Value: Integer($FFCD3700); Name: 'OrangeRed3'), (Value: Integer($FF8B2500); Name: 'OrangeRed4'), (Value: Integer($FFFF0000); Name: 'Red1'), (Value: Integer($FFEE0000); Name: 'Red2'), (Value: Integer($FFCD0000); Name: 'Red3'), (Value: Integer($FF8B0000); Name: 'Red4'), (Value: Integer($FFFF1493); Name: 'DeepPink1'), (Value: Integer($FFEE1289); Name: 'DeepPink2'), (Value: Integer($FFCD1076); Name: 'DeepPink3'), (Value: Integer($FF8B0A50); Name: 'DeepPink4'), (Value: Integer($FFFF6EB4); Name: 'HotPink1'), (Value: Integer($FFEE6AA7); Name: 'HotPink2'), (Value: Integer($FFCD6090); Name: 'HotPink3'), (Value: Integer($FF8B3A62); Name: 'HotPink4'), (Value: Integer($FFFFB5C5); Name: 'Pink1'), (Value: Integer($FFEEA9B8); Name: 'Pink2'), (Value: Integer($FFCD919E); Name: 'Pink3'), (Value: Integer($FF8B636C); Name: 'Pink4'), (Value: Integer($FFFFAEB9); Name: 'LightPink1'), (Value: Integer($FFEEA2AD); Name: 'LightPink2'), (Value: Integer($FFCD8C95); Name: 'LightPink3'), (Value: Integer($FF8B5F65); Name: 'LightPink4'), (Value: Integer($FFFF82AB); Name: 'PaleVioletRed1'), (Value: Integer($FFEE799F); Name: 'PaleVioletRed2'), (Value: Integer($FFCD6889); Name: 'PaleVioletRed3'), (Value: Integer($FF8B475D); Name: 'PaleVioletRed4'), (Value: Integer($FFFF34B3); Name: 'Maroon1'), (Value: Integer($FFEE30A7); Name: 'Maroon2'), (Value: Integer($FFCD2990); Name: 'Maroon3'), (Value: Integer($FF8B1C62); Name: 'Maroon4'), (Value: Integer($FFFF3E96); Name: 'VioletRed1'), (Value: Integer($FFEE3A8C); Name: 'VioletRed2'), (Value: Integer($FFCD3278); Name: 'VioletRed3'), (Value: Integer($FF8B2252); Name: 'VioletRed4'), (Value: Integer($FFFF00FF); Name: 'Magenta1'), (Value: Integer($FFEE00EE); Name: 'Magenta2'), (Value: Integer($FFCD00CD); Name: 'Magenta3'), (Value: Integer($FF8B008B); Name: 'Magenta4'), (Value: Integer($FFFF83FA); Name: 'Orchid1'), (Value: Integer($FFEE7AE9); Name: 'Orchid2'), (Value: Integer($FFCD69C9); Name: 'Orchid3'), (Value: Integer($FF8B4789); Name: 'Orchid4'), (Value: Integer($FFFFBBFF); Name: 'Plum1'), (Value: Integer($FFEEAEEE); Name: 'Plum2'), (Value: Integer($FFCD96CD); Name: 'Plum3'), (Value: Integer($FF8B668B); Name: 'Plum4'), (Value: Integer($FFE066FF); Name: 'MediumOrchid1'), (Value: Integer($FFD15FEE); Name: 'MediumOrchid2'), (Value: Integer($FFB452CD); Name: 'MediumOrchid3'), (Value: Integer($FF7A378B); Name: 'MediumOrchid4'), (Value: Integer($FFBF3EFF); Name: 'DarkOrchid1'), (Value: Integer($FFB23AEE); Name: 'DarkOrchid2'), (Value: Integer($FF9A32CD); Name: 'DarkOrchid3'), (Value: Integer($FF68228B); Name: 'DarkOrchid4'), (Value: Integer($FF9B30FF); Name: 'Purple1'), (Value: Integer($FF912CEE); Name: 'Purple2'), (Value: Integer($FF7D26CD); Name: 'Purple3'), (Value: Integer($FF551A8B); Name: 'Purple4'), (Value: Integer($FFAB82FF); Name: 'MediumPurple1'), (Value: Integer($FF9F79EE); Name: 'MediumPurple2'), (Value: Integer($FF8968CD); Name: 'MediumPurple3'), (Value: Integer($FF5D478B); Name: 'MediumPurple4'), (Value: Integer($FFFFE1FF); Name: 'Thistle1'), (Value: Integer($FFEED2EE); Name: 'Thistle2'), (Value: Integer($FFCDB5CD); Name: 'Thistle3'), (Value: Integer($FF8B7B8B); Name: 'Thistle4'), (Value: Integer($FF000000); Name: 'Gray0'), (Value: Integer($FF000000); Name: 'Grey0'), (Value: Integer($FF030303); Name: 'Gray1'), (Value: Integer($FF030303); Name: 'Grey1'), (Value: Integer($FF050505); Name: 'Gray2'), (Value: Integer($FF050505); Name: 'Grey2'), (Value: Integer($FF080808); Name: 'Gray3'), (Value: Integer($FF080808); Name: 'Grey3'), (Value: Integer($FF0A0A0A); Name: 'Gray4'), (Value: Integer($FF0A0A0A); Name: 'Grey4'), (Value: Integer($FF0D0D0D); Name: 'Gray5'), (Value: Integer($FF0D0D0D); Name: 'Grey5'), (Value: Integer($FF0F0F0F); Name: 'Gray6'), (Value: Integer($FF0F0F0F); Name: 'Grey6'), (Value: Integer($FF121212); Name: 'Gray7'), (Value: Integer($FF121212); Name: 'Grey7'), (Value: Integer($FF141414); Name: 'Gray8'), (Value: Integer($FF141414); Name: 'Grey8'), (Value: Integer($FF171717); Name: 'Gray9'), (Value: Integer($FF171717); Name: 'Grey9'), (Value: Integer($FF1A1A1A); Name: 'Gray10'), (Value: Integer($FF1A1A1A); Name: 'Grey10'), (Value: Integer($FF1C1C1C); Name: 'Gray11'), (Value: Integer($FF1C1C1C); Name: 'Grey11'), (Value: Integer($FF1F1F1F); Name: 'Gray12'), (Value: Integer($FF1F1F1F); Name: 'Grey12'), (Value: Integer($FF212121); Name: 'Gray13'), (Value: Integer($FF212121); Name: 'Grey13'), (Value: Integer($FF242424); Name: 'Gray14'), (Value: Integer($FF242424); Name: 'Grey14'), (Value: Integer($FF262626); Name: 'Gray15'), (Value: Integer($FF262626); Name: 'Grey15'), (Value: Integer($FF292929); Name: 'Gray16'), (Value: Integer($FF292929); Name: 'Grey16'), (Value: Integer($FF2B2B2B); Name: 'Gray17'), (Value: Integer($FF2B2B2B); Name: 'Grey17'), (Value: Integer($FF2E2E2E); Name: 'Gray18'), (Value: Integer($FF2E2E2E); Name: 'Grey18'), (Value: Integer($FF303030); Name: 'Gray19'), (Value: Integer($FF303030); Name: 'Grey19'), (Value: Integer($FF333333); Name: 'Gray20'), (Value: Integer($FF333333); Name: 'Grey20'), (Value: Integer($FF363636); Name: 'Gray21'), (Value: Integer($FF363636); Name: 'Grey21'), (Value: Integer($FF383838); Name: 'Gray22'), (Value: Integer($FF383838); Name: 'Grey22'), (Value: Integer($FF3B3B3B); Name: 'Gray23'), (Value: Integer($FF3B3B3B); Name: 'Grey23'), (Value: Integer($FF3D3D3D); Name: 'Gray24'), (Value: Integer($FF3D3D3D); Name: 'Grey24'), (Value: Integer($FF404040); Name: 'Gray25'), (Value: Integer($FF404040); Name: 'Grey25'), (Value: Integer($FF424242); Name: 'Gray26'), (Value: Integer($FF424242); Name: 'Grey26'), (Value: Integer($FF454545); Name: 'Gray27'), (Value: Integer($FF454545); Name: 'Grey27'), (Value: Integer($FF474747); Name: 'Gray28'), (Value: Integer($FF474747); Name: 'Grey28'), (Value: Integer($FF4A4A4A); Name: 'Gray29'), (Value: Integer($FF4A4A4A); Name: 'Grey29'), (Value: Integer($FF4D4D4D); Name: 'Gray30'), (Value: Integer($FF4D4D4D); Name: 'Grey30'), (Value: Integer($FF4F4F4F); Name: 'Gray31'), (Value: Integer($FF4F4F4F); Name: 'Grey31'), (Value: Integer($FF525252); Name: 'Gray32'), (Value: Integer($FF525252); Name: 'Grey32'), (Value: Integer($FF545454); Name: 'Gray33'), (Value: Integer($FF545454); Name: 'Grey33'), (Value: Integer($FF575757); Name: 'Gray34'), (Value: Integer($FF575757); Name: 'Grey34'), (Value: Integer($FF595959); Name: 'Gray35'), (Value: Integer($FF595959); Name: 'Grey35'), (Value: Integer($FF5C5C5C); Name: 'Gray36'), (Value: Integer($FF5C5C5C); Name: 'Grey36'), (Value: Integer($FF5E5E5E); Name: 'Gray37'), (Value: Integer($FF5E5E5E); Name: 'Grey37'), (Value: Integer($FF616161); Name: 'Gray38'), (Value: Integer($FF616161); Name: 'Grey38'), (Value: Integer($FF636363); Name: 'Gray39'), (Value: Integer($FF636363); Name: 'Grey39'), (Value: Integer($FF666666); Name: 'Gray40'), (Value: Integer($FF666666); Name: 'Grey40'), (Value: Integer($FF696969); Name: 'Gray41'), (Value: Integer($FF696969); Name: 'Grey41'), (Value: Integer($FF6B6B6B); Name: 'Gray42'), (Value: Integer($FF6B6B6B); Name: 'Grey42'), (Value: Integer($FF6E6E6E); Name: 'Gray43'), (Value: Integer($FF6E6E6E); Name: 'Grey43'), (Value: Integer($FF707070); Name: 'Gray44'), (Value: Integer($FF707070); Name: 'Grey44'), (Value: Integer($FF737373); Name: 'Gray45'), (Value: Integer($FF737373); Name: 'Grey45'), (Value: Integer($FF757575); Name: 'Gray46'), (Value: Integer($FF757575); Name: 'Grey46'), (Value: Integer($FF787878); Name: 'Gray47'), (Value: Integer($FF787878); Name: 'Grey47'), (Value: Integer($FF7A7A7A); Name: 'Gray48'), (Value: Integer($FF7A7A7A); Name: 'Grey48'), (Value: Integer($FF7D7D7D); Name: 'Gray49'), (Value: Integer($FF7D7D7D); Name: 'Grey49'), (Value: Integer($FF7F7F7F); Name: 'Gray50'), (Value: Integer($FF7F7F7F); Name: 'Grey50'), (Value: Integer($FF828282); Name: 'Gray51'), (Value: Integer($FF828282); Name: 'Grey51'), (Value: Integer($FF858585); Name: 'Gray52'), (Value: Integer($FF858585); Name: 'Grey52'), (Value: Integer($FF878787); Name: 'Gray53'), (Value: Integer($FF878787); Name: 'Grey53'), (Value: Integer($FF8A8A8A); Name: 'Gray54'), (Value: Integer($FF8A8A8A); Name: 'Grey54'), (Value: Integer($FF8C8C8C); Name: 'Gray55'), (Value: Integer($FF8C8C8C); Name: 'Grey55'), (Value: Integer($FF8F8F8F); Name: 'Gray56'), (Value: Integer($FF8F8F8F); Name: 'Grey56'), (Value: Integer($FF919191); Name: 'Gray57'), (Value: Integer($FF919191); Name: 'Grey57'), (Value: Integer($FF949494); Name: 'Gray58'), (Value: Integer($FF949494); Name: 'Grey58'), (Value: Integer($FF969696); Name: 'Gray59'), (Value: Integer($FF969696); Name: 'Grey59'), (Value: Integer($FF999999); Name: 'Gray60'), (Value: Integer($FF999999); Name: 'Grey60'), (Value: Integer($FF9C9C9C); Name: 'Gray61'), (Value: Integer($FF9C9C9C); Name: 'Grey61'), (Value: Integer($FF9E9E9E); Name: 'Gray62'), (Value: Integer($FF9E9E9E); Name: 'Grey62'), (Value: Integer($FFA1A1A1); Name: 'Gray63'), (Value: Integer($FFA1A1A1); Name: 'Grey63'), (Value: Integer($FFA3A3A3); Name: 'Gray64'), (Value: Integer($FFA3A3A3); Name: 'Grey64'), (Value: Integer($FFA6A6A6); Name: 'Gray65'), (Value: Integer($FFA6A6A6); Name: 'Grey65'), (Value: Integer($FFA8A8A8); Name: 'Gray66'), (Value: Integer($FFA8A8A8); Name: 'Grey66'), (Value: Integer($FFABABAB); Name: 'Gray67'), (Value: Integer($FFABABAB); Name: 'Grey67'), (Value: Integer($FFADADAD); Name: 'Gray68'), (Value: Integer($FFADADAD); Name: 'Grey68'), (Value: Integer($FFB0B0B0); Name: 'Gray69'), (Value: Integer($FFB0B0B0); Name: 'Grey69'), (Value: Integer($FFB3B3B3); Name: 'Gray70'), (Value: Integer($FFB3B3B3); Name: 'Grey70'), (Value: Integer($FFB5B5B5); Name: 'Gray71'), (Value: Integer($FFB5B5B5); Name: 'Grey71'), (Value: Integer($FFB8B8B8); Name: 'Gray72'), (Value: Integer($FFB8B8B8); Name: 'Grey72'), (Value: Integer($FFBABABA); Name: 'Gray73'), (Value: Integer($FFBABABA); Name: 'Grey73'), (Value: Integer($FFBDBDBD); Name: 'Gray74'), (Value: Integer($FFBDBDBD); Name: 'Grey74'), (Value: Integer($FFBFBFBF); Name: 'Gray75'), (Value: Integer($FFBFBFBF); Name: 'Grey75'), (Value: Integer($FFC2C2C2); Name: 'Gray76'), (Value: Integer($FFC2C2C2); Name: 'Grey76'), (Value: Integer($FFC4C4C4); Name: 'Gray77'), (Value: Integer($FFC4C4C4); Name: 'Grey77'), (Value: Integer($FFC7C7C7); Name: 'Gray78'), (Value: Integer($FFC7C7C7); Name: 'Grey78'), (Value: Integer($FFC9C9C9); Name: 'Gray79'), (Value: Integer($FFC9C9C9); Name: 'Grey79'), (Value: Integer($FFCCCCCC); Name: 'Gray80'), (Value: Integer($FFCCCCCC); Name: 'Grey80'), (Value: Integer($FFCFCFCF); Name: 'Gray81'), (Value: Integer($FFCFCFCF); Name: 'Grey81'), (Value: Integer($FFD1D1D1); Name: 'Gray82'), (Value: Integer($FFD1D1D1); Name: 'Grey82'), (Value: Integer($FFD4D4D4); Name: 'Gray83'), (Value: Integer($FFD4D4D4); Name: 'Grey83'), (Value: Integer($FFD6D6D6); Name: 'Gray84'), (Value: Integer($FFD6D6D6); Name: 'Grey84'), (Value: Integer($FFD9D9D9); Name: 'Gray85'), (Value: Integer($FFD9D9D9); Name: 'Grey85'), (Value: Integer($FFDBDBDB); Name: 'Gray86'), (Value: Integer($FFDBDBDB); Name: 'Grey86'), (Value: Integer($FFDEDEDE); Name: 'Gray87'), (Value: Integer($FFDEDEDE); Name: 'Grey87'), (Value: Integer($FFE0E0E0); Name: 'Gray88'), (Value: Integer($FFE0E0E0); Name: 'Grey88'), (Value: Integer($FFE3E3E3); Name: 'Gray89'), (Value: Integer($FFE3E3E3); Name: 'Grey89'), (Value: Integer($FFE5E5E5); Name: 'Gray90'), (Value: Integer($FFE5E5E5); Name: 'Grey90'), (Value: Integer($FFE8E8E8); Name: 'Gray91'), (Value: Integer($FFE8E8E8); Name: 'Grey91'), (Value: Integer($FFEBEBEB); Name: 'Gray92'), (Value: Integer($FFEBEBEB); Name: 'Grey92'), (Value: Integer($FFEDEDED); Name: 'Gray93'), (Value: Integer($FFEDEDED); Name: 'Grey93'), (Value: Integer($FFF0F0F0); Name: 'Gray94'), (Value: Integer($FFF0F0F0); Name: 'Grey94'), (Value: Integer($FFF2F2F2); Name: 'Gray95'), (Value: Integer($FFF2F2F2); Name: 'Grey95'), (Value: Integer($FFF5F5F5); Name: 'Gray96'), (Value: Integer($FFF5F5F5); Name: 'Grey96'), (Value: Integer($FFF7F7F7); Name: 'Gray97'), (Value: Integer($FFF7F7F7); Name: 'Grey97'), (Value: Integer($FFFAFAFA); Name: 'Gray98'), (Value: Integer($FFFAFAFA); Name: 'Grey98'), (Value: Integer($FFFCFCFC); Name: 'Gray99'), (Value: Integer($FFFCFCFC); Name: 'Grey99'), (Value: Integer($FFFFFFFF); Name: 'Gray100'), (Value: Integer($FFFFFFFF); Name: 'Grey100'), (Value: Integer($FFA9A9A9); Name: 'DarkGrey'), (Value: Integer($FFA9A9A9); Name: 'DarkGray'), (Value: Integer($FF00008B); Name: 'DarkBlue'), (Value: Integer($FF008B8B); Name: 'DarkCyan'), (Value: Integer($FF8B008B); Name: 'DarkMagenta'), (Value: Integer($FF8B0000); Name: 'DarkRed'), (Value: Integer($FF90EE90); Name: 'LightGreen')); type TfgColorsPreset = array of TIdentMapEntry; implementation end.
unit udmTabsPromocionais; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS, uMatVars; type TdmTabsPromocionais = class(TdmPadrao) qryManutencaoFILIAL: TStringField; qryManutencaoTARIFA: TStringField; qryManutencaoVLR_NOTA_MIN: TFloatField; qryManutencaoVLR_NOTA_MAX: TFloatField; qryManutencaoFINAL_1: TFloatField; qryManutencaoFRT_FIN_1: TFloatField; qryManutencaoAD_FIN_1: TFloatField; qryManutencaoFINAL_2: TFloatField; qryManutencaoFRT_FIN_2: TFloatField; qryManutencaoAD_FIN_2: TFloatField; qryManutencaoFINAL_3: TFloatField; qryManutencaoFRT_FIN_3: TFloatField; qryManutencaoAD_FIN_3: TFloatField; qryManutencaoFINAL_4: TFloatField; qryManutencaoFRT_FIN_4: TFloatField; qryManutencaoAD_FIN_4: TFloatField; qryManutencaoFINAL_5: TFloatField; qryManutencaoFRT_FIN_5: TFloatField; qryManutencaoAD_FIN_5: TFloatField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoNM_FILIAL: TStringField; qryLocalizacaoFILIAL: TStringField; qryLocalizacaoTARIFA: TStringField; qryLocalizacaoVLR_NOTA_MIN: TFloatField; qryLocalizacaoVLR_NOTA_MAX: TFloatField; qryLocalizacaoFINAL_1: TFloatField; qryLocalizacaoFRT_FIN_1: TFloatField; qryLocalizacaoAD_FIN_1: TFloatField; qryLocalizacaoFINAL_2: TFloatField; qryLocalizacaoFRT_FIN_2: TFloatField; qryLocalizacaoAD_FIN_2: TFloatField; qryLocalizacaoFINAL_3: TFloatField; qryLocalizacaoFRT_FIN_3: TFloatField; qryLocalizacaoAD_FIN_3: TFloatField; qryLocalizacaoFINAL_4: TFloatField; qryLocalizacaoFRT_FIN_4: TFloatField; qryLocalizacaoAD_FIN_4: TFloatField; qryLocalizacaoFINAL_5: TFloatField; qryLocalizacaoFRT_FIN_5: TFloatField; qryLocalizacaoAD_FIN_5: TFloatField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoNM_FILIAL: TStringField; private FCod_Filial : String; FCod_Tarifa : String; public procedure MontaSQLBusca(DataSet :TDataSet = Nil); override; procedure MontaSQLRefresh; override; property Filial :String read FCod_Filial write FCod_Filial; property Tarifa :String read FCod_Tarifa write FCod_Tarifa; end; const C_SQL_DEFAUT = 'SELECT ' + ' PROM.FILIAL, ' + ' PROM.TARIFA, ' + ' PROM.VLR_NOTA_MIN, ' + ' PROM.VLR_NOTA_MAX, ' + ' PROM.FINAL_1, ' + ' PROM.FRT_FIN_1, ' + ' PROM.AD_FIN_1, ' + ' PROM.FINAL_2, ' + ' PROM.FRT_FIN_2, ' + ' PROM.AD_FIN_2, ' + ' PROM.FINAL_3, ' + ' PROM.FRT_FIN_3, ' + ' PROM.AD_FIN_3, ' + ' PROM.FINAL_4, ' + ' PROM.FRT_FIN_4, ' + ' PROM.AD_FIN_4, ' + ' PROM.FINAL_5, ' + ' PROM.FRT_FIN_5, ' + ' PROM.AD_FIN_5, ' + ' PROM.DT_ALTERACAO, ' + ' PROM.OPERADOR, ' + ' FIL.NOME NM_FILIAL ' + 'FROM STWOPETPROM PROM ' + 'LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = PROM.FILIAL '; var dmTabsPromocionais: TdmTabsPromocionais; implementation uses udmPrincipal; {$R *.dfm} { TdmTabsPromocionais } { TdmTabsPromocionais } procedure TdmTabsPromocionais.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(C_SQL_DEFAUT); SQL.Add('WHERE ( FILIAL = :FILIAL ) AND ( TARIFA = :TARIFA )'); SQL.Add('ORDER BY FILIAL, TARIFA'); Params[ 0].AsString := FCod_Filial; Params[ 1].AsString := FCod_Tarifa; end; end; procedure TdmTabsPromocionais.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(C_SQL_DEFAUT); SQL.Add('ORDER BY FILIAL, TARIFA'); end; end; end.
unit ArduinoNewProjectWizard_intf; {$MODE DELPHI} interface uses uArduinoFormWorkspace, FileUtil, LazFileUtils, StrUtils, Classes, SysUtils, Controls, Forms, Dialogs, LazIDEIntf, ProjectIntf; type { TArduinoApplicationDescriptor } TArduinoApplicationDescriptor = class(TProjectDescriptor) private FProjectName: string; FProjectPath : string; FTargetSpecific: string; //-Wp FDeleteGeneratedAssembler: boolean; //-a FInstructionSet: string; //-Cp FCodeTemplate: TCodeTemplate; FPathToArduinoIDE: string; FPathToCodeTemplates: string; function SettingsFilename: string; function GetWorkSpaceFromForm: boolean; public constructor Create; override; function GetLocalizedName: string; override; function GetLocalizedDescription: string; override; function DoInitDescriptor: TModalResult; override; function InitProject(AProject: TLazProject): TModalResult; override; function CreateStartFiles(AProject: TLazProject): TModalResult; override; end; var ProjectDescriptorArduinoApplication: TArduinoApplicationDescriptor; procedure Register; implementation procedure Register; begin ProjectDescriptorArduinoApplication := TArduinoApplicationDescriptor.Create; RegisterProjectDescriptor(ProjectDescriptorArduinoApplication); end; {TArduinoApplicationDescriptor} function TArduinoApplicationDescriptor.SettingsFilename: string; begin Result := AppendPathDelim(LazarusIDE.GetPrimaryConfigPath) + 'AVRArduinoProject.ini' end; function TArduinoApplicationDescriptor.GetWorkSpaceFromForm: boolean; var frm: TArduinoFormWorkspace; installList: TStringList; begin Result := False; frm := TArduinoFormWorkspace.Create(nil); frm.LoadSettings(SettingsFilename); if frm.ShowModal = mrOK then begin frm.SaveSettings(SettingsFilename); FTargetSpecific:= frm.TargetSpecific; //-Wp FDeleteGeneratedAssembler:= frm.DeleteGeneratedAssembler; //-a FInstructionSet:= frm.InstructionSet; //-Cp FProjectName := trim(frm.ProjectName); FProjectPath := Trim(frm.WorkspacePath) + DirectorySeparator + FProjectName; FCodeTemplate:= frm.CodeTemplate; FPathToArduinoIDE:= frm.PathToArduinoIDE; FPathToCodeTemplates:= frm.PathToCodeTemplates; ForceDirectory(FProjectPath); //chdir(FProjectPath); - fix error [not found fpc.exe] installList:= TStringList.Create; //thanks to @HatForGat! installList.Add(FPathToArduinoIDE+DirectorySeparator+ 'hardware'+DirectorySeparator+ 'tools'+DirectorySeparator+ 'avr'+DirectorySeparator+ 'bin'+DirectorySeparator+ 'avrdude -C'+FPathToArduinoIDE+ 'hardware'+DirectorySeparator+ 'tools'+DirectorySeparator+ 'avr'+DirectorySeparator+ 'etc'+DirectorySeparator+ 'avrdude.conf -v -patmega328p -carduino -P\\.\%1 -b115200 -D -Uflash:w:'+FProjectName+'.hex:i'); installList.SaveToFile(FProjectPath+DirectorySeparator+'install.bat'); Result := True; end; frm.Free; end; constructor TArduinoApplicationDescriptor.Create; begin inherited Create; Name := 'Create New Arduino AVR Module [Lamwino]'; end; function TArduinoApplicationDescriptor.GetLocalizedName: string; begin Result:= 'Arduino AVR Module [Lamwino]'; end; function TArduinoApplicationDescriptor.GetLocalizedDescription: string; begin Result:= 'Arduino [AVR] Module'+ LineEnding + '[Native "*.hex" Executable]'+ LineEnding + 'The project is maintained by Lazarus [Lamwino].' end; function TArduinoApplicationDescriptor.DoInitDescriptor: TModalResult; begin if GetWorkSpaceFromForm then Result := mrOK else Result := mrAbort; end; function TArduinoApplicationDescriptor.InitProject(AProject: TLazProject): TModalResult; var NewSource: TStringList; MainFile: TLazProjectFile; begin inherited InitProject(AProject); Aproject.Title := FProjectName; NewSource:= TStringList.Create; if FCodeTemplate = ctBlinking then begin NewSource.Add('program ' + FProjectName +'; //Lamwino: Lazarus Arduino Module Wizard :: '+DateTimeToStr(Now)); NewSource.Add('//thanks to @ykot! ref. http://forum.lazarus.freepascal.org/index.php/topic,30960.0.html'); NewSource.Add('{$mode delphi}'); NewSource.Add(' '); NewSource.Add('//uses'); NewSource.Add(' '); NewSource.Add('const'); NewSource.Add(' PB5 = 1 shl 5; //Bit 5 in "PortB" control UNO Pin13 [internal LED]'); NewSource.Add(' '); NewSource.Add('var'); NewSource.Add(' DelayVar: Integer = 0;'); NewSource.Add(' '); NewSource.Add('procedure SomeDelay;'); NewSource.Add('var'); NewSource.Add(' I: LongInt;'); NewSource.Add('begin'); NewSource.Add(' for I := 0 to 400000 do'); NewSource.Add(' Dec(DelayVar);'); NewSource.Add('end;'); NewSource.Add(' '); NewSource.Add('begin'); NewSource.Add(' '); NewSource.Add(' DDRB := DDRB or PB5; //force DDRB bit 5 to 1 !! [i.e, signalize PORTB bit 5 [Pin13] as output]'); NewSource.Add(' '); NewSource.Add(' while True do'); NewSource.Add(' begin'); NewSource.Add(' '); NewSource.Add(' PORTB := PORTB and (not PB5); //force PORTB bit 5 [Pin13] to 0!'); NewSource.Add(' SomeDelay;'); NewSource.Add(' '); NewSource.Add(' PORTB := PORTB or PB5; //force PORTB bit 5 [Pin13] to 1!'); NewSource.Add(' SomeDelay;'); NewSource.Add(' '); NewSource.Add(' end;'); NewSource.Add(' '); NewSource.Add('end.'); end; if FCodeTemplate = ctMinimal then begin NewSource.Add('program ' + FProjectName+'; //Lamwino: Lazarus Arduino Module Wizard :: '+DateTimeToStr(Now)); NewSource.Add(' '); NewSource.Add('{$mode delphi}'); NewSource.Add(' '); NewSource.Add('//uses'); NewSource.Add(' '); NewSource.Add('//const'); NewSource.Add(' '); NewSource.Add('var'); NewSource.Add(' DelayVar: Integer = 0;'); NewSource.Add(' '); NewSource.Add('procedure SomeDelay; //by @ykot'); NewSource.Add('var'); NewSource.Add(' I: LongInt;'); NewSource.Add('begin'); NewSource.Add(' for I := 0 to 400000 do'); NewSource.Add(' Dec(DelayVar);'); NewSource.Add('end;'); NewSource.Add(' '); NewSource.Add('begin'); NewSource.Add(' '); NewSource.Add(' while True do'); NewSource.Add(' begin'); NewSource.Add(' '); NewSource.Add(' SomeDelay;'); NewSource.Add(' '); NewSource.Add(' end;'); NewSource.Add(' '); NewSource.Add('end.'); end; if FCodeTemplate = ctSerial then begin NewSource.Add('program ' + FProjectName+'; //Lamwino: Lazarus Arduino Module Wizard :: '+DateTimeToStr(Now)); NewSource.Add(' '); NewSource.Add('{$mode delphi}'); NewSource.Add(' '); NewSource.Add('uses'); NewSource.Add(' LamwinoAvrSerial;'); NewSource.Add(' '); NewSource.Add('//const'); NewSource.Add(' '); NewSource.Add('var'); NewSource.Add(' DelayVar: Integer = 0;'); NewSource.Add(' prompt: PChar;'); NewSource.Add(' ch: char;'); NewSource.Add(' '); NewSource.Add('procedure SomeDelay; //by @ykot'); NewSource.Add('var'); NewSource.Add(' I: LongInt;'); NewSource.Add('begin'); NewSource.Add(' for I := 0 to 400000 do'); NewSource.Add(' Dec(DelayVar);'); NewSource.Add('end;'); NewSource.Add(' '); NewSource.Add('begin'); NewSource.Add(' '); NewSource.Add(' prompt:= ''Please, enter a char [or digit]: '';'); NewSource.Add(' '); NewSource.Add(' Serial.Init(9600);'); NewSource.Add(' '); NewSource.Add(' Serial.WriteString(''Hello World!'');'); NewSource.Add(' '); NewSource.Add(' Serial.WriteLineBreak;'); NewSource.Add(' '); NewSource.Add(' while True do'); NewSource.Add(' begin'); NewSource.Add(' '); NewSource.Add(' Serial.WriteLineBreak;'); NewSource.Add(' '); NewSource.Add(' Serial.WriteString(prompt);'); NewSource.Add(' '); NewSource.Add(' Serial.WriteLineBreak;'); NewSource.Add(' '); NewSource.Add(' ch:= Serial.ReadChar();'); NewSource.Add(' Serial.WriteChar(ch);'); NewSource.Add(' '); NewSource.Add(' Serial.WriteLineBreak;'); NewSource.Add(' '); NewSource.Add(' SomeDelay;'); NewSource.Add(' '); NewSource.Add(' end;'); NewSource.Add(' '); NewSource.Add('end.'); end; MainFile := AProject.CreateProjectFile( FProjectPath + DirectorySeparator+ Lowercase(FProjectName) + '.lpr'); MainFile.SetSourceText(NewSource.Text); MainFile.IsPartOfProject := True; AProject.AddFile(MainFile, False {NOT Added To Project Uses Clause}); AProject.MainFileID := 0; AProject.Flags := AProject.Flags - [pfMainUnitHasCreateFormStatements, pfMainUnitHasTitleStatement]; AProject.UseManifest:= False; AProject.UseAppBundle:= False; {Parsing} AProject.LazCompilerOptions.SyntaxMode:= 'Delphi'; {CodeGeneration} AProject.LazCompilerOptions.SmartLinkUnit:= True; AProject.LazCompilerOptions.TargetCPU:= 'avr'; {-P} AProject.LazCompilerOptions.TargetOS:= 'embedded'; AProject.LazCompilerOptions.OptimizationLevel:= 3; AProject.LazCompilerOptions.Win32GraphicApp:= False; {Linking} AProject.LazCompilerOptions.StripSymbols:= True; {-Xs} AProject.LazCompilerOptions.LinkSmart:= True {-XX}; AProject.LazCompilerOptions.GenerateDebugInfo:= False; //AProject.LazCompilerOptions.SmallerCode:= True; AProject.LazCompilerOptions.SmartLinkUnit:= True; AProject.LazCompilerOptions.IncludePath:='$(ProjOutDir)'; //-Fi AProject.LazCompilerOptions.UnitOutputDirectory := '\lib\$(TargetCPU)-$(TargetOS)'; //-FU AProject.LazCompilerOptions.TargetFilename:= FProjectName; //-o //http://www.freepascal.org/docs-html/user/userap1.html // -W<x> Target-specific options (targets); // -a The compiler does not delete the generated assembler file; // -Cp<x> Select instruction set; //FTargetSpecific:= 'atmega328p'; //-Wp //FDeleteGeneratedAssembler:= frm.DeleteGeneratedAssembler; //-a //FInstructionSet:= 'avr5'; //-Cp if not FDeleteGeneratedAssembler then AProject.LazCompilerOptions.CustomOptions:= '-Cp'+FInstructionSet+ ' -Wp'+FTargetSpecific +' -a' else AProject.LazCompilerOptions.CustomOptions:= '-Cp'+FInstructionSet+ ' -Wp'+FTargetSpecific; AProject.CustomData.Values['LAMWINO'] := 'AVR'; AProject.CustomData.Values['AVRCHIP'] := FTargetSpecific; AProject.ProjectInfoFile := FProjectPath + DirectorySeparator + ChangeFileExt( FProjectName, '.lpi'); NewSource.Free; Result := mrOK; end; function TArduinoApplicationDescriptor.CreateStartFiles(AProject: TLazProject): TModalResult; var templateList: TStringList; pathToProjectInfo: TStringList; auxPathToProject: string; i: integer; userString: string; begin if AProject=nil then Exit; pathToProjectInfo:= TStringList.Create; pathToProjectInfo.Delimiter:= DirectorySeparator; pathToProjectInfo.StrictDelimiter:= True; pathToProjectInfo.DelimitedText:=LazarusIDE.ActiveProject.ProjectInfoFile; auxPathToProject:= pathToProjectInfo.Strings[0] + DirectorySeparator; for i:=1 to pathToProjectInfo.Count-2 do begin auxPathToProject:= auxPathToProject + pathToProjectInfo.Strings[i] + DirectorySeparator; end; pathToProjectInfo.Free; templateList:= TStringList.Create; if FCodeTemplate = ctSerial then begin if FPathToCodeTemplates = '' then begin userString:= 'C:\lazarus\components\arduinomodulewizard\templates'; if InputQuery('Configure Path', 'Path to code templates', userString) then begin FPathToCodeTemplates:= userString; end; end; if FPathToCodeTemplates <> '' then begin templateList.LoadFromFile(FPathToCodeTemplates+DirectorySeparator+'lamwinoavrserial.pas'); templateList.SaveToFile(auxPathToProject+'lamwinoavrserial.pas'); end; end; templateList.Free; LazarusIDE.DoSaveProject([sfSaveAs]); Result := mrOK; end; end.
unit BusReg; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls; type TBusRegDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; lbCampo: TStaticText; Label2: TLabel; Buscar: TEdit; private FCampo: string; procedure SetCampo(const Value: string); { Private declarations } public { Public declarations } property Campo: string read FCampo write SetCampo; end; function BuscarValor( FCampo, FNombre: string ): string; var BusRegDlg: TBusRegDlg; implementation {$R *.DFM} function BuscarValor( FCampo, FNombre: string ): string; begin with TBusRegDlg.create( application ) do try Campo := Campo; lbCampo.Caption := FNombre; ShowModal; if ModalResult = mrOK then Result := Buscar.Text else Result := ''; finally free; end; end; { TBusRegDlg } procedure TBusRegDlg.SetCampo(const Value: string); begin FCampo := Value; end; end.
// ------------------------------------------------------------------------------ // 1. In iTunes connect ensure that you have a unique App ID // 2. Create a new application and update application information. You can know more about this in apple add new apps documentation. // 3. Setup a leader board in Manage Game Center of your application's page where add a single leaderboard and give leaderboard ID and score Type. Here we give leader board ID as DPFLeaderboard. // 4. Setup a Achievement in Manage Game Center of your application's page where add a single Achievement and give leaderboard ID and score Type. Here we give Achievement ID as DPFAchievementID. // 5. Enter the bundle identifier is the identifier specified in iTunes connect. (very important) // ------------------------------------------------------------------------------ unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, DPF.iOS.BaseControl, DPF.iOS.UIView, DPF.iOS.GameKit, DPF.iOS.UIButton, DPF.iOS.UIViewController, DPF.iOS.UILabel, DPF.iOS.UITextField, DPF.iOS.GameCenterManager, DPF.iOS.Keyboard; type TFGameCenter = class( TForm ) DPFUIView1: TDPFUIViewController; DPFButtonShowGameCenter: TDPFButton; DPFTextField1: TDPFTextField; DPFLabel1: TDPFLabel; DPFGameCenterManager1: TDPFGameCenterManager; DPFButtonIncreaseScore: TDPFButton; DPFButtonSubmitScore: TDPFButton; DPFButtonSubmitAchievement: TDPFButton; DPFKeyboard1: TDPFKeyboard; DPFButtonConnect: TDPFButton; DPFLabelSubmitScore: TDPFLabel; DPFLabelSubmitAchievement: TDPFLabel; DPFLabelConnect: TDPFLabel; DPFButtonGetScore: TDPFButton; DPFLabelGetScore: TDPFLabel; DPFButtonAchievement: TDPFButton; DPFLabelAchievement: TDPFLabel; DPFButtonMatchmaker: TDPFButton; DPFButtonFriendRequest: TDPFButton; procedure DPFButtonShowGameCenterClick( Sender: TObject ); procedure DPFButtonIncreaseScoreClick( Sender: TObject ); procedure DPFButtonSubmitScoreClick( Sender: TObject ); procedure DPFButtonSubmitAchievementClick( Sender: TObject ); procedure DPFButtonConnectClick( Sender: TObject ); procedure DPFGameCenterManager1Authenticate( Sender: TObject; const isAuthenticated: Boolean; error: string; const ErrorCode: NativeUInt ); procedure DPFGameCenterManager1ReportAchievement( Sender: TObject; const Submitted: Boolean; error: string; const ErrorCode: NativeUInt ); procedure DPFGameCenterManager1ReportScrore( Sender: TObject; const Submitted: Boolean; error: string; const ErrorCode: NativeUInt ); procedure DPFButtonGetScoreClick( Sender: TObject ); procedure DPFGameCenterManager1GetScores( Sender: TObject; const Scores: TScores; const error: string; const ErrorCode: NativeUInt ); procedure DPFButtonAchievementClick( Sender: TObject ); procedure DPFGameCenterManager1GetAchievements( Sender: TObject; const Achievements: TAchievements; const error: string; const ErrorCode: NativeUInt ); procedure DPFButtonMatchmakerClick( Sender: TObject ); procedure DPFButtonFriendRequestClick( Sender: TObject ); private { Private declarations } protected procedure PaintRects( const UpdateRects: array of TRectF ); override; public { Public declarations } end; var FGameCenter: TFGameCenter; implementation {$R *.fmx} procedure TFGameCenter.DPFButtonShowGameCenterClick( Sender: TObject ); begin DPFGameCenterManager1.ShowGameCenter( 'DPFLeaderboard' ); end; procedure TFGameCenter.DPFButtonAchievementClick( Sender: TObject ); begin DPFLabelAchievement.Text := 'Wait...'; DPFGameCenterManager1.RequestAchievements; end; procedure TFGameCenter.DPFButtonConnectClick( Sender: TObject ); begin if not DPFGameCenterManager1.InitPlayer then begin DPFLabelConnect.TextColor := TAlphaColors.Black; DPFLabelConnect.Text := 'Wait...' end; end; procedure TFGameCenter.DPFButtonFriendRequestClick( Sender: TObject ); begin DPFGameCenterManager1.ShowFriendRequest; end; procedure TFGameCenter.DPFButtonGetScoreClick( Sender: TObject ); begin DPFLabelGetScore.Text := 'Wait...'; DPFGameCenterManager1.RequestScores( 'DPFLeaderboard' ); end; procedure TFGameCenter.DPFButtonIncreaseScoreClick( Sender: TObject ); begin DPFTextField1.Text := IntToStr( StrToInt64Def( DPFTextField1.Text, 0 ) + 1 ); end; procedure TFGameCenter.DPFButtonMatchmakerClick( Sender: TObject ); begin DPFGameCenterManager1.ShowMatchmaker; end; procedure TFGameCenter.DPFButtonSubmitAchievementClick( Sender: TObject ); begin DPFLabelSubmitAchievement.TextColor := TAlphaColors.Black; DPFLabelSubmitAchievement.Text := 'Wait...'; DPFGameCenterManager1.ReportAchievement( 'DPFAchievementID', StrToFloat( DPFTextField1.Text ), true ); end; procedure TFGameCenter.DPFButtonSubmitScoreClick( Sender: TObject ); begin DPFLabelSubmitScore.TextColor := TAlphaColors.Black; DPFLabelSubmitScore.Text := 'Wait...'; DPFGameCenterManager1.ReportScore( 'DPFLeaderboard', StrToInt64( DPFTextField1.Text ) ); end; procedure TFGameCenter.DPFGameCenterManager1Authenticate( Sender: TObject; const isAuthenticated: Boolean; error: string; const ErrorCode: NativeUInt ); begin DPFButtonSubmitScore.Enabled := isAuthenticated; DPFButtonSubmitAchievement.Enabled := isAuthenticated; DPFButtonShowGameCenter.Enabled := isAuthenticated; DPFButtonGetScore.Enabled := isAuthenticated; DPFButtonAchievement.Enabled := isAuthenticated; DPFButtonMatchmaker.Enabled := isAuthenticated; DPFButtonFriendRequest.Enabled := isAuthenticated; if isAuthenticated then begin DPFLabelConnect.TextColor := TAlphaColors.Green; DPFLabelConnect.Text := 'Connected.' end else begin DPFLabelConnect.TextColor := TAlphaColors.Red; DPFLabelConnect.Text := Error; end; end; procedure TFGameCenter.DPFGameCenterManager1GetAchievements( Sender: TObject; const Achievements: TAchievements; const error: string; const ErrorCode: NativeUInt ); begin if Length( Achievements ) > 0 then begin DPFLabelAchievement.Text := 'V: ' + Achievements[0].percentComplete.ToString( ); end else DPFLabelAchievement.Text := 'No Achievement'; end; procedure TFGameCenter.DPFGameCenterManager1GetScores( Sender: TObject; const Scores: TScores; const error: string; const ErrorCode: NativeUInt ); begin if Length( Scores ) > 0 then begin DPFLabelGetScore.Text := 'V: ' + Scores[0].Value.ToString( ) + ' - R: ' + Scores[0].Rank.ToString; end else DPFLabelGetScore.Text := 'No Score'; end; procedure TFGameCenter.DPFGameCenterManager1ReportAchievement( Sender: TObject; const Submitted: Boolean; error: string; const ErrorCode: NativeUInt ); begin if Submitted then begin DPFLabelSubmitAchievement.TextColor := TAlphaColors.Green; DPFLabelSubmitAchievement.Text := 'Submitted' end else begin DPFLabelSubmitAchievement.TextColor := TAlphaColors.Red; DPFLabelSubmitAchievement.Text := Error; end; end; procedure TFGameCenter.DPFGameCenterManager1ReportScrore( Sender: TObject; const Submitted: Boolean; error: string; const ErrorCode: NativeUInt ); begin if Submitted then begin DPFLabelSubmitScore.TextColor := TAlphaColors.Green; DPFLabelSubmitScore.Text := 'Submitted' end else begin DPFLabelSubmitScore.TextColor := TAlphaColors.Red; DPFLabelSubmitScore.Text := Error; end; end; procedure TFGameCenter.PaintRects( const UpdateRects: array of TRectF ); begin { } end; end.
unit UTLBClasses; interface uses System.Classes, System.Generics.Collections; type TCustomOut = class strict private const CEmptyStr = ''; CIdent = ' '; strict private FIdentStr: string; FLevels: TStrings; strict private function GetIdent: Integer; procedure SetIdent(AVal: Integer); function GetLevel(AIdx: Integer): string; strict protected procedure WriteStr(const AStr: string); virtual; abstract; public constructor Create; destructor Destroy; override; procedure Write(const AStr: string); procedure WriteFmt(const AFmt: string; const AArgs: array of const); procedure WriteIdent(const AStr: string); procedure WriteIdentFmt(const AFmt: string; const AArgs: array of const); procedure EmptyLine; procedure IncIdent; procedure DecIdent; public property Ident: Integer read GetIdent write SetIdent; property Level[AIdx: Integer]: string read GetLevel; end; TOutFile = class(TCustomOut) strict private FFile: TextFile; strict protected procedure WriteStr(const AStr: string); override; public constructor Create(const AFileName: string); destructor Destroy; override; end; TOutBuffer = class(TCustomOut) strict private FBuffer: TStrings; strict private function GetCount: Integer; function GetBuffer(AIdx: Integer): string; strict protected procedure WriteStr(const AStr: string); override; public constructor Create; destructor Destroy; override; procedure Clear; procedure Flush(AOut: TCustomOut); public property Count: Integer read GetCount; property Buffer[AIdx: Integer]: string read GetBuffer; end; TStdUnits = (suSystem, suCustom, suActiveX, suWindows, suComObj, suOleServer, suClasses); TPasTypeInfo = record Name: string; Ref: Integer; RefBase: Integer; VarType: TVarType; StdUnit: TStdUnits; CustomUnit: string; function IsEqual(const AInfo: TPasTypeInfo): Boolean; end; TUnitManager = class strict private type TUnitName = record Name: string; NS: string; end; const CStdUnits: array[TStdUnits] of TUnitName = ( (Name: 'System'; NS: ''), (Name: ''; NS: ''), (Name: 'ActiveX'; NS: 'Winapi'), (Name: 'Windows'; NS: 'Winapi'), (Name: 'ComObj'; NS: 'System.Win'), (Name: 'OleServer'; NS: 'Vcl'), (Name: 'Classes'; NS: 'System') ); strict private FUnits: TDictionary<string, Integer>; FUseNS: Boolean; public constructor Create(AUseNS: Boolean); destructor Destroy; override; procedure AddStdUnit(AUnit: TStdUnits); procedure AddCustomUnit(const AUnit: string); procedure AddPasType(const AType: TPasTypeInfo); procedure Print(AOut: TCustomOut); procedure Clear; end; TReservedWords = class strict private class var FWords: TDictionary<string, Byte>; strict private class constructor Create; class destructor Destroy; public class function IsReserved(const AStr: string): Boolean; class function Escape(const AStr: string): string; end; function CompareInt(const ALeft, ARight: Integer): Integer; implementation uses System.SysUtils, System.Generics.Defaults; function CompareInt(const ALeft, ARight: Integer): Integer; begin if ALeft < ARight then Result := -1 else if ALeft = ARight then Result := 0 else Result := 1; end; { TCustomOut } constructor TCustomOut.Create; begin inherited Create; FLevels := TStringList.Create; FLevels.Add(CEmptyStr); end; destructor TCustomOut.Destroy; begin FLevels.Free; inherited Destroy; end; function TCustomOut.GetIdent: Integer; begin Result := FLevels.Count - 1; end; procedure TCustomOut.SetIdent(AVal: Integer); begin if AVal < 0 then raise Exception.CreateFmt('Invalid ident %d', [AVal]); while AVal > Ident do IncIdent; while AVal < Ident do DecIdent; end; function TCustomOut.GetLevel(AIdx: Integer): string; begin Result := FLevels[Ident + AIdx]; end; procedure TCustomOut.Write(const AStr: string); begin WriteStr(FIdentStr + AStr); FLevels[Ident] := AStr; end; procedure TCustomOut.WriteFmt(const AFmt: string; const AArgs: array of const); begin Write(Format(AFmt, AArgs)); end; procedure TCustomOut.WriteIdent(const AStr: string); begin IncIdent; try Write(AStr); finally DecIdent; end; end; procedure TCustomOut.WriteIdentFmt(const AFmt: string; const AArgs: array of const); begin IncIdent; try WriteFmt(AFmt, AArgs); finally DecIdent; end; end; procedure TCustomOut.EmptyLine; begin WriteStr(CEmptyStr); end; procedure TCustomOut.IncIdent; begin FIdentStr := FIdentStr + CIdent; FLevels.Add(CEmptyStr); end; procedure TCustomOut.DecIdent; begin SetLength(FIdentStr, Length(FIdentStr) - Length(CIdent)); FLevels.Delete(Ident); end; { TOutFile } constructor TOutFile.Create(const AFileName: string); begin inherited Create; AssignFile(FFile, AFileName); Rewrite(FFile); end; destructor TOutFile.Destroy; begin CloseFile(FFile); inherited Destroy; end; procedure TOutFile.WriteStr(const AStr: string); begin System.Writeln(FFile, AStr); end; { TOutBuffer } constructor TOutBuffer.Create; begin inherited Create; FBuffer := TStringList.Create; end; destructor TOutBuffer.Destroy; begin FBuffer.Free; inherited Destroy; end; function TOutBuffer.GetCount: Integer; begin Result := FBuffer.Count; end; function TOutBuffer.GetBuffer(AIdx: Integer): string; begin Result := FBuffer[AIdx]; end; procedure TOutBuffer.WriteStr(const AStr: string); begin FBuffer.Add(AStr); end; procedure TOutBuffer.Clear; begin FBuffer.Clear; end; procedure TOutBuffer.Flush(AOut: TCustomOut); var Li: Integer; begin AOut.Ident := 0; for Li := 0 to FBuffer.Count - 1 do AOut.Write(FBuffer[Li]); Clear; AOut.Ident := Ident; end; { TPasTypeInfo } function TPasTypeInfo.IsEqual(const AInfo: TPasTypeInfo): Boolean; begin Result := (Name = AInfo.Name) and (Ref = AInfo.Ref); end; { TUnitManager } constructor TUnitManager.Create(AUseNS: Boolean); begin inherited Create; FUnits := TDictionary<string, Integer>.Create(Length(CStdUnits)); FUseNS := AUseNS; end; destructor TUnitManager.Destroy; begin FUnits.Free; inherited Destroy; end; procedure TUnitManager.AddStdUnit(AUnit: TStdUnits); var LStr: string; LUnit: TUnitName; begin if AUnit > suCustom then begin LUnit := CStdUnits[AUnit]; if FUseNS and (LUnit.NS <> '') then LStr := Format('%s.%s', [LUnit.NS, LUnit.Name]) else LStr := LUnit.Name; AddCustomUnit(LStr); end; end; procedure TUnitManager.AddCustomUnit(const AUnit: string); begin if (AUnit <> '') and not FUnits.ContainsKey(AUnit) then FUnits.Add(AUnit, FUnits.Count); end; procedure TUnitManager.AddPasType(const AType: TPasTypeInfo); begin if AType.StdUnit <> suCustom then AddStdUnit(AType.StdUnit) else AddCustomUnit(AType.CustomUnit); end; procedure TUnitManager.Print(AOut: TCustomOut); const CDelim = ', '; type TUnitPair = TPair<string, Integer>; var LData: TArray<TUnitPair>; Li: Integer; LStr: string; LUnitLen: Integer; begin if FUnits.Count = 0 then Exit; LData := FUnits.ToArray; TArray.Sort<TUnitPair>(LData, TComparer<TUnitPair>.Construct( function(const ALeft, ARight: TUnitPair): Integer begin Result := CompareInt(ALeft.Value, ARight.Value); end )); AOut.Write('uses'); AOut.IncIdent; try LStr := ''; for Li := 0 to Length(LData) - 1 do begin LUnitLen := Length(LData[Li].Key) + Length(CDelim); if (Length(LStr) + LUnitLen >= 78) and (LStr <> '') then begin AOut.Write(TrimRight(LStr)); LStr := ''; end; LStr := LStr + LData[Li].Key + CDelim; end; SetLength(LStr, Length(LStr) - Length(CDelim)); LStr := LStr + ';'; AOut.Write(LStr); finally AOut.DecIdent; end; AOut.EmptyLine; end; procedure TUnitManager.Clear; begin FUnits.Clear; end; { TReservedWords } class constructor TReservedWords.Create; const CWords: array[0..63] of string = ( 'and', 'array', 'as', 'asm', 'begin', 'case', 'class', 'const', 'constructor', 'destructor', 'dispinterface', 'div', 'do', 'downto', 'else', 'end', 'except', 'exports', 'file', 'finalization', 'finally', 'for', 'function', 'goto', 'if', 'implementation', 'in', 'inherited', 'initialization', 'inline', 'interface', 'is', 'label', 'library', 'mod', 'nil', 'not', 'object', 'of', 'or', 'packed', 'procedure', 'program', 'property', 'raise', 'record', 'repeat', 'resourcestring', 'set', 'shl', 'shr', 'string', 'then', 'threadvar', 'to', 'try', 'type', 'unit', 'until', 'uses', 'var', 'while', 'with', 'xor' ); var Li: Integer; begin FWords := TDictionary<string, Byte>.Create(Length(CWords)); for Li := 0 to Length(CWords) - 1 do FWords.Add(CWords[Li], 0); end; class destructor TReservedWords.Destroy; begin FWords.Free; end; class function TReservedWords.IsReserved(const AStr: string): Boolean; begin Result := FWords.ContainsKey(AnsiLowerCase(AStr)); end; class function TReservedWords.Escape(const AStr: string): string; begin Result := AStr; if IsReserved(AStr) then Result := Result + '_'; end; end.
// // purpose: Packet sniffer demo for use with the open source WinPcap driver // author: Authorized KOL version, © 2005, Thaddy de Koning // Original version © Umar Sear // Remarks: The WinPCap driver is free ware and available from // http://winpcap.polito.it/ under a BSD style license // // This KOL demo and the KOL headerfile translations are not freeware // They are subject to the same license as Umar states in his header // comments {******************************************************************************** -------------------------------------------------------------------------------- TSniffer component for Delphi uses winpcap Packet Capture Driver by Politecnico di Torino Written by Umar Sear -------------------------------------------------------------------------------- TERMS AND CONDITIONS OF USE. Code in this unit is Copyright(C) 2003 Umar Sear The author of this software assumes no liability for damages caused under any circumstances whatsoever, and is under no obligation. Use of the software indicates acceptance of all conditions contained in this document. If you do not agree to these terms, you must delete this software immediately. You may distribute the archive in which this software is distributed, but under no circumstances must this archive be changed. Distributing a modified archive is a violation of the software license. If you do redistribute this software, please let me know at the email address given below. This software is not freeware, if you wish to use it other than for trial purposes, please contact me for a full licence. If you have any questions, requests, bug reports, etc., please contact me at the address given below. Umar Sear Email : usear@yahoo.com Winpcap author: webpsite: http://netgroup-serv.polito.it ********************************************************************************} unit KolSniffer; interface uses kolwinpcap,kolwinpcaptypes,winsock,kol; Type PInterface=^TInterFace; TInterface=Packed record iName, iDesc : String; Addr, Mask, Bcast : LongWord; End; // Capture event callback definations TOnCapture = Procedure (const Header:PTpcap_pkthdr; const Data:Pointer) of object; TOnCaptureIP = Procedure (const Header:PTpcap_pkthdr; const Data:PIPPckt) of object; TOnCaptureTcp = Procedure (const Header:PTpcap_pkthdr; const Data:PTCPPckt) of object; TOnCaptureUdp = Procedure (const Header:PTpcap_pkthdr; const Data:PUDPPckt) of object; TProto = (pIP, pTCP, pUDP, pICMP, pAny, pArp); TCapMode = (capPromiscuous, capNonPromiscuous); PSniffer = ^TSniffer; PSnifferthreaddata =^TSnifferthreadData; TSnifferThreadData = object(TObj) private sniffer : PSniffer; public ReadTimes : integer; Destructor destroy;virtual; function DoExecute(sender:PThread):integer; end; Tsniffer = object(Tobj) Protected FOnCapture : TOnCapture; FOnCaptureIP : TOnCaptureIP; FOnCaptureTCP : TOnCaptureTCP; FOnCaptureUDP : TOnCaptureUDP; FPCAP : PPCAP; // Handle to the pcapdriver FBpfProgram : Pbpf_program; FProto : TProto; FIList : PList; FDevNames : PStrList; FDevDesc : PStrList; FIIndex : Integer; // current adapter FIName, // Interface name FFilter, FIDesc : String; // Interface description FIMask, FIIp : LongWord; FThread : PThread; // The listening thread FCapMode : TCapMode; FSniffing : Boolean; // Flag indicating snooping activity FSnapLen : Integer; // Snapshot length FFiltered : Boolean; // Filtered flag FInterface : PInterface; Function GetInterfaces (Var ErrStr:string) : boolean; procedure ThreadTerminate; procedure SetInterfaceIndex (const Value: integer); Procedure SetSnapLen (Const Value: Integer); Procedure SetProtocol (Const Value : TProto); Procedure SetFDesc (Const Value : String); Procedure SetFiltered (Const value : Boolean); Procedure SetFilterStr (Const Value : String); Procedure AddInterface (dev : Ppcap_if); Function GetFMask : String; Function GetIP : String; Procedure SetFMask (Const Value : String); Procedure SetIP (Const Value : String); public Destructor Destroy;virtual; Function Activate : Integer; Function Deactivate : Integer; property DeviceNames : PStrList read FDevNames; property DeviceDescriptions : PStrList read FDevDesc; property DeviceIndex : Integer read FIIndex write SetInterfaceIndex; Property CaptureProtocol : TProto read FProto Write SetProtocol; property Filtered : Boolean read FFiltered Write SetFiltered; property DeviceName : String read FIName Write SetFDesc; property DeviceDescription : String read FIDesc Write SetFDesc; property CaptureLength : Integer read FSnapLen Write SetSnapLen; property FilterString : String read FFilter Write SetFilterStr; property OnCapture : TOnCapture read FOnCapture write FOnCapture; property OnCaptureIP : TOnCaptureIP read FOnCaptureIP write FOnCaptureIP; property OnCaptureTCP : TOnCaptureTCP read FOnCaptureTCP write FOnCaptureTCP; property OnCaptureUDP : TOnCaptureUDP read FOnCaptureUDP write FOnCaptureUDP; Property CaptureMode : TCapMode read FCapMode Write FCapMode; property DeviceMask : String read GetFMask Write SetFMask; property DeviceAddress : String read GetIP Write SetIP; end; function NewSnifferThread(Sniff:PSniffer):PThread; function NewSniffer(AOwner: Pcontrol):PSniffer; implementation //Capture Call Back procedure CaptureCB(User:pointer;const Header:PTpcap_pkthdr;const Data:Pointer); cdecl; begin // Trigger OnCapture event If Assigned(PSniffer(User).OnCapture) Then PSniffer(user).OnCapture(Header,Data); // Trigger OnCaptureIP event If (Assigned(PSniffer(User).OnCaptureIP)) and (Ntohs(PEthernetHdr(Data).Protocol)=Proto_IP) Then PSniffer(user).OnCaptureIP(Header,PIPPckt(Data)); // Trigger OnCaptureTCP event If Assigned(PSniffer(User).OnCaptureTCP) and (PIPHdr(Data).Protocol=Proto_TCP) Then PSniffer(user).OnCaptureTCP(Header,PTCPPckt(Data)); // Trigger OnCaptureUDP event If Assigned(PSniffer(User).OnCaptureUDP) and (PIPHdr(Data).Protocol=Proto_UDP) Then PSniffer(user).OnCaptureUDP(Header,PUDPPckt(Data)); end; function NewSniffer(AOwner: Pcontrol):PSniffer; Var ErrStr : String; begin New(Result,Create); AOwner.Add2autofree(Result); with Result^ do begin FDevNames:=NewStrList; FDevDesc :=NewStrList; FSnapLen:=DEFAULT_SNAPLEN; FIList:=Newlist; If GetInterfaces(ErrStr) Then SetInterfaceIndex(0) Else SetInterfaceIndex(-1); Fproto:=pAny; FPCAP := Nil; Fsniffing:=false; end; end; Destructor TSniffer.Destroy; begin DeActivate; FIList.Free; Inherited Destroy; end; function TSniffer.Activate: Integer; Var ErrStr : String; i : Integer; begin // Result:=0; If (FSniffing) or (fpcap<>nil) then Begin Result:=1; //Already sniffing Exit; End; If (Not Assigned(OnCapture)) and (Not Assigned(OnCaptureIP)) and (Not Assigned(OnCaptureTCP)) and (Not Assigned(OnCaptureUDP)) Then begin // ErrStr:='No callback specified'; Result:=2; exit; end; If FCapMode=capPromiscuous then Fpcap:=pcap_open_live(pchar(FIName),FSnapLen,1, 20, pchar(ErrStr)) Else Fpcap:=pcap_open_live(pchar(FIName),FSnapLen,0, 20, pchar(ErrStr)); Fsnaplen:=pcap_snapshot(Fpcap); If Fpcap=nil then Begin // ErrStr:='Packet capture failed'; Result:=3; Exit; End; If FFiltered Then pcap_setfilter(Fpcap,FBpfProgram); FThread := NewSnifferThread(@Self); //! Fthread.OnSuspend:= ThreadTerminate; Fthread.AutoFree := false; Fthread.resume; FSniffing := True; result:=0; end; Function TSniffer.Deactivate: Integer; begin // result := false; if (not Fsniffing) then begin // errstr:='not active'; Result:=1; exit; end; if FThread=nil then begin //errstr:='Thread not active'; Result:=2; exit; end; Pcap_Close(FPCAP); FThread.Terminate; FThread.WaitFor; FThread.Free; Fthread := nil; Fpcap:=Nil; FSniffing:=False; result :=0; end; Procedure TSniffer.AddInterface(dev : Ppcap_if); Var anInterface : PInterFace; Begin FDevNames.Add(Dev.name); FDevDesc.Add(Dev.description); New(AnInterFace); AnInterFace.iName:=Dev.name; AnInterFace.iDesc:=Dev.description; If Dev.addresses<>nil then Begin AnInterFace.Addr:=StrToIP(Dev.addresses.addr); AnInterFace.Mask:=StrToIP(Dev.addresses.netmask); AnInterFace.Bcast:=StrToIP(Dev.addresses.broadaddr); End; FIList.Add(AnInterFace); End; function TSniffer.GetInterfaces(var ErrStr:string): boolean; Var alldevs : PPPcap_if; dev : ppcap_if; begin Result:=False; New(alldevs); If Initializewpcap then Begin If pcap_findalldevs(alldevs,Pchar(errStr))=-1 then Exit; Try dev:=Alldevs^; AddInterface(dev); While dev.next <>nil do Begin dev:=dev.next; AddInterFace(dev); end; pcap_freealldevs(Alldevs^); Result:=True; Except ErrStr:='Error whilst retrieving interface names'; End; End; Dispose(allDevs); end; function NewSnifferThread(Sniff:PSniffer):PThread; var Data:PSnifferthreadData; begin New(Data,Create); Data.ReadTimes:=0; Data.Sniffer:=Sniff; Result:=NewThread; Result.Data:=Data; Result.OnExecute:=Data.DoExecute; end; destructor TSnifferThreadData.destroy; begin Sniffer.FSniffing:=false; end; function TSnifferThreadData.DoExecute(sender:PThread):integer; begin Result:=0; if Sniffer=nil then exit; pcap_loop(Sniffer.FPCAP,0,@CaptureCB,Pointer(Sniffer)); Sniffer.FSniffing:=True; end; procedure TSniffer.ThreadTerminate; begin FSniffing:=false; end; procedure TSniffer.SetInterfaceIndex(const Value: integer); begin If FIIndex=Value then exit; SetFiltered(False); if (value>-1) and (value<FIList.count) then Begin FInterFace:=FIList.Items[Value]; FIIndex := Value; FIName :=FInterFace.iName; // Interfaces.Names[Value]; FIDesc :=FInterFace.iDesc; // InterFaces.ValueFromIndex[Value]; FIMask :=FInterFace.Mask; // Mask FIip :=FInterFace.Addr; // IP address End else Begin FIIndex := -1; FIName := 'Invalid interface'; FIDesc := 'Invalid interface'; FIMask := 0; FIip := 0; End; end; procedure TSniffer.SetSnapLen(const Value: integer); Begin FSnapLen:=Value; End; Procedure TSniffer.SetProtocol(Const Value : TProto); Begin If Value=Fproto then exit; FProto:=Value; Case Fproto of pIP : FFilter:='ip'; pTCP : FFilter:='tcp'; pUDP : FFilter:='udp'; pICMP : FFilter:='icmp'; PArp : FFilter:='arp'; pAny : FFilter:=''; End; {Case} SetFiltered(false); End; Procedure TSniffer.SetFDesc (Const Value : String); Begin End; Procedure TSniffer.SetFMask (Const Value : String); Begin End; Procedure TSniffer.SetIp (Const Value : String); Begin End; Function TSniffer.GetFMask: String; Begin Result:=IPToStr(FIMask); End; Function TSniffer.GetIp: String; Begin Result:=IPToStr(FIIp); End; Procedure TSniffer.SetFiltered (Const value : Boolean); Var MyPcap : PPcap; ErrStr : String; Begin if value=FFiltered then exit; If (Value) and (FIIndex>-1) then Begin Mypcap:=pcap_open_live(pchar(FIName),FSnapLen,1, 20, pchar(ErrStr)); // Mypcap:=pcap_open_live(pchar(FIName),150,1, 20, pchar(ErrStr)); If MyPcap=nil then Begin FFiltered:=False; Exit; End; New(FBpfProgram); // If pcap_compile(Mypcap,FBpfProgram,Pchar(FFilter),1,$ffff0000)=-1 then If pcap_compile(Mypcap,FBpfProgram,Pchar(FFilter),1,FIMask)=-1 then Begin Filtered:=False; // ErrStr:=pcap_geterr(MyPcap); Exit; End; Pcap_Close(MyPcap); End; If not (Value) and (FBpfProgram<>nil) then Dispose(FBpfProgram); FFiltered:=Value; End; Procedure TSniffer.SetFilterStr (Const value : String); Begin if value=FFilter then exit; FFilter:=LowerCase(Value); SetFiltered(false); Fproto:=pAny; End; end.
{ redis for delphi } unit uRedisHandle; interface uses Classes, IdTCPClient, SysUtils, StrUtils, IdException, uRedisCommand, uRedisCommon; type //redis handle exception ERedisException = class(Exception); //redis应答错误信息 ERedisErrorReply = class(Exception); //当redis应答错误时,回调此函数,如isHandled返回true,则提示成功,否则弹异常 TOnGetRedisError = procedure(aRedisCommand: TRedisCommand; var aResponseList: TStringList; aErr: string; var isHandled: Boolean) of object; // TRedisHandle = class private FPassword: string; FDb: Integer; FPort: Integer; FIp: string; FReadTimeout: Integer; FOnGetRedisError: TOnGetRedisError; procedure SetPassword(const Value: string); procedure SetDb(const Value: Integer); procedure SetIp(const Value: string); procedure SetPort(const Value: Integer); procedure SetReadTimeout(const Value: Integer); procedure SetOnGetRedisError(const Value: TOnGetRedisError); protected //命令行 FRedisCommand: TRedisCommand; FResponseList: TStringList; //tcp FTcpClient: TIdTCPClient; function GetConnection: Boolean; procedure SetConnection(const Value: Boolean); //tcp procedure NewTcpClient; //异常 procedure RaiseErr(aErr: string); //组装并发送命令 无数据返回 procedure SendCommandWithNoResponse(aRedisCommand: TRedisCommand); //获取String应答,无返回空 function SendCommandWithStrResponse(aRedisCommand: TRedisCommand): string; //获取Integer应答,无返回0 function SendCommandWithIntResponse(aRedisCommand: TRedisCommand): Integer; //组装并发送命令 procedure SendCommand(aRedisCommand: TRedisCommand); //读取应答并解析 procedure ReadAndParseResponse(var aResponseList: TStringList); public constructor Create(); virtual; destructor Destroy; override; //连接 property Connection: Boolean read GetConnection write SetConnection; //应答 property ResponseList: TStringList read FResponseList; //发送命令解析应答 procedure SendCommandAndGetResponse(aRedisCommand: TRedisCommand; var aResponseList: TStringList); //////////////////////////////////////////////////////////////////////////// /// 命令 //使用Password认证 procedure RedisAuth(); //选择Db数据库,默认使用0号数据库 procedure RedisSelect(); //////////////////////////////////////////////////////////////////////////// /// Key //Redis DEL 命令用于删除已存在的键。不存在的 key 会被忽略。 procedure KeyDelete(aKey: String); //Redis EXISTS 命令用于检查给定 key 是否存在。 function KeyExist(aKey: String): Boolean; //Redis Expire 命令用于设置 key 的过期时间,key 过期后将不再可用。单位以秒计。 procedure KeySetExpire(aKey: String; aExpireSec: Integer); //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /// String //Redis Get 命令用于获取指定 key 的值。如果 key 不存在,返回 nil 。如果key 储存的值不是字符串类型,返回一个错误。 function StringGet(aKey: string): string; //Redis SET 命令用于设置给定 key 的值。如果 key 已经存储其他值, SET 就覆写旧值,且无视类型。 procedure StringSet(aKey, aValue: String); overload; //Redis Getset 命令用于设置指定 key 的值,并返回 key 的旧值。 function StringGetSet(aKey, aValue: String): String; //set 带超时(秒) procedure StringSet(aKey, aValue: String; aExpireSec: Int64); overload; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// /// List //list队尾插入值,返回新的list长度 //Redis Rpush 命令用于将一个或多个值插入到列表的尾部(最右边)。 //如果列表不存在,一个空列表会被创建并执行RPUSH 操作。当列表存在但不是列表类型时返回一个错误 //Insert all the specified values at the tail of the list stored at key. //If key does not exist, it is created as empty list before performing the push operation. //When key holds a value that is not a list, an error is returned. function ListRPush(aKey, aValue: string): Integer; overload; function ListRPush(aKey: string; aValues: array of string): Integer; overload; //Redis Lpush 命令将一个或多个值插入到列表头部。 如果 key 不存在, //一个空列表会被创建并执行 LPUSH 操作。 当 key 存在但不是列表类型时,返回一个错误。 function ListLPush(aKey, aValue: string): Integer; overload; function ListLPush(aKey: string; aValues: array of string): Integer; overload; //Redis Rpop 命令用于移除列表的最后一个元素,返回值为移除的元素,无数据返回空。 function ListRPop(aKey: string): string; //Redis Lpop 命令用于移除并返回列表的第一个元素,无数据返回空。 function ListLPop(aKey: string): string; //获取list大小 function ListLen(aKey: string): Integer; //获取list范围数据,获取后数据并不会被删除 function ListRange(aKey: string; aBegin, aEnd: Integer; var aRetValues: TStringList): Integer; //Redis Lrem 根据参数 COUNT 的值,移除列表中与参数 VALUE 相等的元素,返回移除数据个数 //COUNT 的值可以是以下几种: //count > 0 : 从表头开始向表尾搜索,移除与 VALUE 相等的元素,数量为 COUNT 。 //count < 0 : 从表尾开始向表头搜索,移除与 VALUE 相等的元素,数量为 COUNT 的绝对值。 //count = 0 : 移除表中所有与 VALUE 相等的值。 //Removes the first count occurrences of elements equal to element from the list stored at key //The count argument influences the operation in the following ways: //count > 0: Remove elements equal to element moving from head to tail. //count < 0: Remove elements equal to element moving from tail to head. //count = 0: Remove all elements equal to element. function ListRemove(aKey, aValue: string; aCount: Integer): Integer; //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //redis ip property Ip: string read FIp write SetIp; //redis port property Port: Integer read FPort write SetPort; //redis 读超时 property ReadTimeout: Integer read FReadTimeout write SetReadTimeout; //redis 密码 property Password: string read FPassword write SetPassword; //redis 数据库 property Db: Integer read FDb write SetDb; //当redis应答错误时,回调此函数,如isHandled返回true,则提示成功,否则弹异常 property OnGetRedisError: TOnGetRedisError read FOnGetRedisError write SetOnGetRedisError; end; implementation { TRedisHandle } constructor TRedisHandle.Create(); begin FIp := Redis_Default_Ip; FPort := Redis_Default_Port; FPassword := ''; FDb := 0; FRedisCommand := TRedisCommand.Create; FResponseList := TStringList.Create; NewTcpClient; end; destructor TRedisHandle.Destroy; begin FTcpClient.Free; FRedisCommand.Free; FResponseList.Free; inherited; end; procedure TRedisHandle.RaiseErr(aErr: string); begin raise ERedisException.Create(aErr); end; procedure TRedisHandle.ReadAndParseResponse(var aResponseList: TStringList); var aRetType: string; aLen: Integer; aBuff: TBytes; i, aBegin: Integer; begin // aRetType := FTcpClient.IOHandler.ReadByte; // // if aRetType = $2B then // begin // //状态回复(status reply)的第一个字节是 "+" // end // else if aRetType = $3A then // begin // //整数回复(integer reply)的第一个字节是 ":" // end // else if aRetType = $24 then // begin // //批量回复(bulk reply)的第一个字节是 "$" // end // else if aRetType = $2A then // begin // //多条批量回复(multi bulk reply)的第一个字节是 "*" // end; FTcpClient.IOHandler.ReadBytes(aBuff, -1, False); aLen := Length(aBuff); if aLen = 0 then RaiseErr('无应答'); if aLen <= 2 then begin Sleep(100); FTcpClient.IOHandler.ReadBytes(aBuff, -1, True); aLen := Length(aBuff); end; if aLen <= 2 then RaiseErr('未知应答:' + TEncoding.UTF8.GetString(aBuff)); //数据类型 aRetType := TEncoding.UTF8.GetString(aBuff, 0, 1); if aRetType = '-' then begin //错误回复(error reply)的第一个字节是 "-" raise ERedisErrorReply.Create(TEncoding.UTF8.GetString(aBuff, 1, aLen - 2)); end; aResponseList.Clear; aResponseList.Add(aRetType); //应答数据 aBegin := 1; for i := 2 to aLen - 2 do begin if (aBuff[i] = $0D) and (aBuff[i + 1] = $0A) then begin aResponseList.Add(TEncoding.UTF8.GetString(aBuff, aBegin, i - aBegin)); aBegin := i + 2; end; end; if aResponseList.Count < 2 then RaiseErr('应答数据缺失'); end; procedure TRedisHandle.RedisAuth; var aCommand: TRedisCommand; begin aCommand := TRedisCommand.Create; try //AUTH <password> aCommand.Clear.Add('AUTH').Add(FPassword); //发送,读取应答并解析 SendCommandWithNoResponse(aCommand); finally aCommand.Free; end; end; function TRedisHandle.StringGet(aKey: string): string; begin FRedisCommand.Clear.Add('GET').Add(aKey); //发送,读取应答并解析 Result := SendCommandWithStrResponse(FRedisCommand); end; function TRedisHandle.StringGetSet(aKey, aValue: String): String; begin FRedisCommand.Clear.Add('GETSET').Add(aKey).Add(aValue); //发送,读取应答并解析 Result := SendCommandWithStrResponse(FRedisCommand); end; procedure TRedisHandle.StringSet(aKey, aValue: String); begin StringSet(aKey, aValue, -1); end; procedure TRedisHandle.StringSet(aKey, aValue: String; aExpireSec: Int64); begin FRedisCommand.Clear.Add('SET').Add(aKey).Add(aValue); if aExpireSec > 0 then begin FRedisCommand.Add('EX').Add(IntToStr(aExpireSec)); end; //发送,读取应答并解析 SendCommandWithNoResponse(FRedisCommand); end; procedure TRedisHandle.RedisSelect(); var aCommand: TRedisCommand; begin aCommand := TRedisCommand.Create; try //SELECT index aCommand.Clear.Add('SELECT').Add(IntToStr(FDb)); //发送,读取应答并解析 SendCommandWithNoResponse(aCommand); finally aCommand.Free; end; end; function TRedisHandle.GetConnection: Boolean; begin Result := Assigned(FTcpClient) and FTcpClient.Connected; end; procedure TRedisHandle.KeyDelete(aKey: String); begin FRedisCommand.Clear.Add('DEL').Add(aKey); //发送,读取应答并解析 SendCommandWithNoResponse(FRedisCommand); end; function TRedisHandle.KeyExist(aKey: String): Boolean; begin FRedisCommand.Clear.Add('EXISTS').Add(aKey); //发送,读取应答并解析 Result := SendCommandWithIntResponse(FRedisCommand) <> 0; end; procedure TRedisHandle.KeySetExpire(aKey: String; aExpireSec: Integer); begin FRedisCommand.Clear.Add('EXPIRE').Add(aKey).Add(IntToStr(aExpireSec)); //发送,读取应答并解析 SendCommandWithNoResponse(FRedisCommand); end; function TRedisHandle.ListRange(aKey: string; aBegin, aEnd: Integer; var aRetValues: TStringList): Integer; var i: Integer; begin FRedisCommand.Clear.Add('LRANGE').Add(aKey) .Add(IntToStr(aBegin)).Add(IntToStr(aEnd)); //发送 SendCommandAndGetResponse(FRedisCommand, FResponseList); Result := StrToInt(FResponseList.Strings[1]); aRetValues.Clear; if Result <= 0 then Exit; for i := 0 to Result - 1 do begin aRetValues.Add(FResponseList.Strings[3 + i * 2]); end; end; function TRedisHandle.ListRemove(aKey, aValue: string; aCount: Integer): Integer; begin FRedisCommand.Clear.Add('LREM').Add(aKey).Add(IntToStr(aCount)).Add(aValue); //发送 Result := SendCommandWithIntResponse(FRedisCommand); end; function TRedisHandle.ListLen(aKey: string): Integer; begin FRedisCommand.Clear.Add('LLEN').Add(aKey); //发送 Result := SendCommandWithIntResponse(FRedisCommand); end; function TRedisHandle.ListLPop(aKey: string): string; begin FRedisCommand.Clear.Add('LPOP').Add(aKey); //发送 Result := SendCommandWithStrResponse(FRedisCommand); end; function TRedisHandle.ListLPush(aKey, aValue: string): Integer; begin Result := ListLPush(aKey, [aValue]); end; function TRedisHandle.ListLPush(aKey: string; aValues: array of string): Integer; var i: Integer; begin if Length(aValues) <= 0 then RaiseErr('无数据'); FRedisCommand.Clear.Add('LPUSH').Add(aKey); for i := 0 to Length(aValues) - 1 do FRedisCommand.Add(aValues[i]); //发送 Result := SendCommandWithIntResponse(FRedisCommand); end; function TRedisHandle.ListRPop(aKey: string): string; begin FRedisCommand.Clear.Add('RPOP').Add(aKey); //发送 Result := SendCommandWithStrResponse(FRedisCommand); end; function TRedisHandle.ListRPush(aKey, aValue: string): Integer; begin Result := ListRPush(aKey, [aValue]); end; function TRedisHandle.ListRPush(aKey: string; aValues: array of string): Integer; var i: Integer; begin if Length(aValues) <= 0 then RaiseErr('无数据'); FRedisCommand.Clear.Add('RPUSH').Add(aKey); for i := 0 to Length(aValues) - 1 do FRedisCommand.Add(aValues[i]); //发送 Result := SendCommandWithIntResponse(FRedisCommand); end; procedure TRedisHandle.NewTcpClient; begin if Assigned(FTcpClient) then begin try FreeAndNil(FTcpClient); except on E: Exception do begin end; end; end; FTcpClient := TIdTCPClient.Create(nil); end; function TRedisHandle.SendCommandWithIntResponse( aRedisCommand: TRedisCommand): Integer; begin SendCommandAndGetResponse(aRedisCommand, FResponseList); Result := StrToInt(FResponseList.Strings[1]); end; procedure TRedisHandle.SendCommandWithNoResponse(aRedisCommand: TRedisCommand); begin SendCommandAndGetResponse(aRedisCommand, FResponseList); end; function TRedisHandle.SendCommandWithStrResponse( aRedisCommand: TRedisCommand): string; begin SendCommandAndGetResponse(aRedisCommand, FResponseList); if StrToInt(FResponseList.Strings[1]) <= 0 then Exit(''); Result := FResponseList.Strings[2]; end; procedure TRedisHandle.SendCommand(aRedisCommand: TRedisCommand); var aBuff: TBytes; begin aBuff := aRedisCommand.ToRedisCommand; try FTcpClient.IOHandler.Write(aBuff); except on E: EIdException do begin NewTcpClient; raise e; end; end; end; procedure TRedisHandle.SendCommandAndGetResponse(aRedisCommand: TRedisCommand; var aResponseList: TStringList); var isHandled: Boolean; begin Connection := True; SendCommand(aRedisCommand); try ReadAndParseResponse(aResponseList); except on E: ERedisErrorReply do begin if Assigned(FOnGetRedisError) then begin FOnGetRedisError(aRedisCommand, aResponseList, e.Message, isHandled); if isHandled then Exit; end; raise e; end; end; end; procedure TRedisHandle.SetConnection(const Value: Boolean); begin if Value = GetConnection then Exit; try if Value then begin if FIp = '' then FIp := Redis_Default_Ip; if FPort <= 0 then FPort := Redis_Default_Port; if FReadTimeout <= 0 then FReadTimeout := Redis_default_ReadTimeout; FTcpClient.Host := FIp; FTcpClient.Port := FPort; FTcpClient.ReadTimeout := FReadTimeout; FTcpClient.Connect; if Password <> '' then RedisAuth; if Db <> 0 then RedisSelect; end else begin FTcpClient.Disconnect; end; except on E: EIdException do begin NewTcpClient; raise e; end; end; end; procedure TRedisHandle.SetDb(const Value: Integer); begin FDb := Value; end; procedure TRedisHandle.SetIp(const Value: string); begin FIp := Value; end; procedure TRedisHandle.SetOnGetRedisError(const Value: TOnGetRedisError); begin FOnGetRedisError := Value; end; procedure TRedisHandle.SetPassword(const Value: string); begin FPassword := Value; end; procedure TRedisHandle.SetPort(const Value: Integer); begin FPort := Value; end; procedure TRedisHandle.SetReadTimeout(const Value: Integer); begin FReadTimeout := Value; end; end.
unit Unit2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm2 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation uses DSharp.Core.Fibers, AsyncCalls; {$R *.dfm} type TAsyncCallAnonymFunc = class(TAsyncCall) private FFiber: TFiber; FProc: TProc; protected function ExecuteAsyncCall: Integer; override; public constructor Create(AProc: TProc); procedure ExecuteAsyncAndYield; end; procedure Await(aAnonymousProc: TProc); var async: IAsyncCall; begin async := TAsyncCallAnonymFunc.Create(aAnonymousProc); TAsyncCallAnonymFunc(async).ExecuteAsyncAndYield; async.Sync; //will re-raise internal exception if present end; procedure Awaitable(aAnonymousProc: TProc); begin TActionFiber.Create(aAnonymousProc, False{no threads but only mainthread?}) .Resume; end; procedure TForm2.Button1Click(Sender: TObject); begin Awaitable( //run in anonymous procedure in a fiber procedure begin Button1.Caption := 'busy'; Button1.Enabled := False; Self.Caption := 'GUI is fully resposive!'; try //await: it will pause current fiber till "sleep" is finished //note: GUI will be responsive in the mean time! Await( procedure begin Sleep(5 * 1000); end); finally Button1.Enabled := True; Button1.Caption := 'done'; end; //exception handling works too try Await( procedure begin Sleep(2 * 1000); raise Exception.Create('Error!'); end); except on E:Exception do Button1.Caption := e.Message; end; end); end; { TAsyncCallAnonymFunc } constructor TAsyncCallAnonymFunc.Create(AProc: TProc); begin inherited Create; FProc := AProc; FFiber := TFiber.CurrentFiber; end; procedure TAsyncCallAnonymFunc.ExecuteAsyncAndYield; begin ExecuteAsync; FFiber.Yield; //pause current fiber end; function TAsyncCallAnonymFunc.ExecuteAsyncCall: Integer; begin Result := 0; try FProc(); finally TThread.Queue(nil, procedure begin FFiber.Resume; //resume fiber again end); end; end; end.
unit Cloud.Console; interface uses System.SysUtils, Cloud.Consts, Cloud.Types, Cloud.Utils, Cloud.Client; type TCloudConsole = class(TCloudDelegate) private CloudClient: TCloudClient; procedure DoPrintHelp(const Title: string); procedure OnEvent(Event: TCloudEvent; const Text: string); override; procedure OnInit(const Init: TCloudResponseInit); override; procedure OnError(const Error: TCloudResponseError); override; procedure OnRegistration(const Registration: TCloudResponseRegistration); override; procedure OnLogin(const Login: TCloudResponseLogin); override; procedure OnAddresses(const Addresses: TCloudResponseGetAddresses); override; procedure OnCreateAddress(const Address: TCloudResponseCreateAddress); override; procedure OnTransactions(const Transactions: TCloudResponseTransactions); override; procedure OnAddress(const Address: TCloudResponseCurrentAddresses); override; procedure OnInfo(const Info: TCloudResponseInfo); override; procedure OnSendTo(const SendTo: TCloudResponseSendTo); override; procedure OnRatio(const Ratio: TCloudResponseRatio); override; procedure OnRequestForging(const Forging: TCloudRequestForging); override; procedure OnForging(const Forging: TCloudResponseForging); override; procedure OnRequestAccountBalance(const AccountBalance: TCloudRequestAccountBalance); override; procedure OnCreateOffer(const Offer: TCloudResponseCreateOffer); override; procedure OnOffers(const Offers: TCloudResponseOffers); override; procedure OnOfferAccount(const Account: TCloudResponseOfferAccount); override; procedure OnKillOffers(const Offers: TCloudResponseKillOffers); override; procedure OnActiveOffers(const Offers: TCloudResponseOffers); override; procedure OnClosedOffers(const Offers: TCloudResponseOffers); override; procedure OnHistoryOffers(const Offers: TCloudResponseOffers); override; procedure OnPairsSummary(const Pairs: TCloudResponsePairs); override; public constructor Create(CloudClient: TCloudClient); function DoConsoleCommand(const Command: string): Boolean; end; implementation constructor TCloudConsole.Create(CloudClient: TCloudClient); begin Self.CloudClient:=CloudClient; CloudClient.SetDelegate(Self); end; procedure TCloudConsole.OnEvent(Event: TCloudEvent; const Text: string); begin case Event of EVENT_REQUEST: Writeln('>'+Text); EVENT_RESPONSE: Writeln('<'+Text); else Writeln(Text); end; end; procedure TCloudConsole.OnInit(const Init: TCloudResponseInit); begin end; procedure TCloudConsole.OnError(const Error: TCloudResponseError); begin Writeln(string(Error)); end; procedure TCloudConsole.OnRegistration(const Registration: TCloudResponseRegistration); begin Writeln('registered'); end; procedure TCloudConsole.OnLogin(const Login: TCloudResponseLogin); begin Writeln('login successful'); end; procedure TCloudConsole.OnAddresses(const Addresses: TCloudResponseGetAddresses); begin if not Addresses.Error then begin Writeln('----Addresses----'); for var S in Addresses.Addresses do Writeln(S); end else Writeln(Addresses.ErrorText); end; procedure TCloudConsole.OnCreateAddress(const Address: TCloudResponseCreateAddress); begin if not Address.Error then Writeln('Address: '+Address.Address) else Writeln(Address.ErrorText); end; procedure TCloudConsole.OnTransactions(const Transactions: TCloudResponseTransactions); begin Writeln('----Transactions----'); for var Transaction in Transactions.Transactions do Writeln(string(Transaction)); end; procedure TCloudConsole.OnAddress(const Address: TCloudResponseCurrentAddresses); begin Writeln(string(Address)); end; procedure TCloudConsole.OnInfo(const Info: TCloudResponseInfo); begin Writeln(string(Info)); end; procedure TCloudConsole.OnSendTo(const SendTo: TCloudResponseSendTo); begin Writeln(string(SendTo)); end; procedure TCloudConsole.OnRatio(const Ratio: TCloudResponseRatio); begin Writeln(string(Ratio)); end; procedure TCloudConsole.OnRequestForging(const Forging: TCloudRequestForging); begin Writeln(string(Forging)); end; procedure TCloudConsole.OnForging(const Forging: TCloudResponseForging); begin Writeln('tx:'+Forging.Tx); end; procedure TCloudConsole.OnRequestAccountBalance(const AccountBalance: TCloudRequestAccountBalance); begin Writeln('request account balance: args='+AccountBalance.Args); CloudClient.SendResponseAccountBalance(340.2,10.705); end; procedure TCloudConsole.OnCreateOffer(const Offer: TCloudResponseCreateOffer); begin Writeln(string(Offer)); end; procedure TCloudConsole.OnOffers(const Offers: TCloudResponseOffers); begin for var O in Offers.Offers do Writeln(string(O)); end; procedure TCloudConsole.OnOfferAccount(const Account: TCloudResponseOfferAccount); begin Writeln('offer account='+Account.AccountID.ToString); end; procedure TCloudConsole.OnKillOffers(const Offers: TCloudResponseKillOffers); begin Writeln(string(Offers)); end; procedure TCloudConsole.OnActiveOffers(const Offers: TCloudResponseOffers); begin for var O in Offers.Offers do Writeln(string(O)); end; procedure TCloudConsole.OnClosedOffers(const Offers: TCloudResponseOffers); begin for var O in Offers.Offers do Writeln(string(O)); end; procedure TCloudConsole.OnHistoryOffers(const Offers: TCloudResponseOffers); begin for var O in Offers.Offers do Writeln(string(O)); end; procedure TCloudConsole.OnPairsSummary(const Pairs: TCloudResponsePairs); begin for var P in Pairs.Pairs do Writeln(string(P)); end; procedure TCloudConsole.DoPrintHelp(const Title: string); begin Writeln(Title); Writeln('reg <email> <password> <ref>'#9#9'- registration account'); Writeln('login <email> <password> '#9#9'- login account'); Writeln('add <btc|ltc|eth> '#9#9#9'- add new address'); Writeln('list <btc|ltc|eth> '#9#9#9'- get addresses list'); Writeln('tx <btc|ltc|eth> '#9#9#9'- get transactions list'); Writeln('get'#9#9#9#9#9'- get current addresses list'); Writeln('info <btc|ltc|eth> '#9#9#9'- get current wallet info'); Writeln('send <btc|ltc|eth> <address> <amount> '#9'- send coins to address'); Writeln('ratio'#9#9#9#9#9'- get USD ratio coins'); Writeln('forg <rlc|gtn> <btc|ltc|eth>'#9#9'- forging'); Writeln('cof <b|s> <btc|ltc|eth|rlc|gtn> <btc|ltc|eth|rlc|gtn> <amount> <ratio>'#9#9'- create offer'); Writeln('of <btc|ltc|eth|rlc|gtn> <btc|ltc|eth|rlc|gtn>'#9#9#9#9#9'- list offers'); Writeln('ca'#9#9#9#9#9'- get offer account'); Writeln('aaof'#9#9#9#9#9'- get active account offers'); Writeln('acof <begin date> <end date>'#9#9'- get closed account offers'); Writeln('ahof <begin date> <end date>'#9#9'- get history account offers'); Writeln('cp'#9#9#9#9#9'- show pairs summary'); Writeln('raw <Command>'#9#9#9#9'- execute any command'); Writeln('exit'#9#9#9#9#9'- terminated'); end; function GetPort(const Symbol: string): string; begin Result:=SymbolToPort(Symbol,PORT_BITCOIN); end; function GetDate(const S: string; Default: TDateTime): TDateTime; begin Result:=StrToDateTimeDef(S,Default); end; function TCloudConsole.DoConsoleCommand(const Command: string): Boolean; var Args: TArray<string>; begin Result:=True; Args:=Command.Split([' '])+['','','']; if Args[0]='' then else if Command='exit' then Exit(False) else if Args[0]='raw' then CloudClient.SendRequestRaw(Skip(Command,[' '],1)) else if Args[0]='reg' then CloudClient.SendRequestRegistration(Args[1],Args[2],StrToIntDef(Args[3],0)) else if Args[0]='login' then CloudClient.SendRequestLogin(Args[1],Args[2]) else if Args[0]='add' then CloudClient.SendRequestCreateAddress(GetPort(Args[1])) else if Args[0]='list' then CloudClient.SendRequestAddresses(GetPort(Args[1])) else if Args[0]='tx' then CloudClient.SendRequestTransactions(GetPort(Args[1])) else if Args[0]='get' then CloudClient.SendRequestAddress() else if Args[0]='info' then CloudClient.SendRequestInfo(GetPort(Args[1])) else if Args[0]='send' then CloudClient.SendRequestSendTo(Args[2],StrToAmount(Args[3]),6,GetPort(Args[1])) else if Args[0]='ratio' then CloudClient.SendRequestRatio() else if Args[0]='forg' then CloudClient.SendRequestForging(1,SymbolID(Args[1],1),GetPort(Args[2]),25,0.0001,6456.543,1.00000,1.00000) else if Args[0]='cof' then CloudClient.SendRequestCreateOffer(Map(Args[1],['b','s'],['1','2'],'1').ToInteger,SymbolID(Args[2]),SymbolID(Args[3]),StrToAmount(Args[4]),StrToAmount(Args[5]),Now+20) else if Args[0]='ca' then CloudClient.SendRequestOfferAccount else if Args[0]='of' then CloudClient.SendRequestOffers(SymbolID(Args[1]),SymbolID(Args[2])) else if Args[0]='aaof' then CloudClient.SendRequestActiveOffers else if Args[0]='acof' then CloudClient.SendRequestClosedOffers(GetDate(Args[1],Date-10),GetDate(Args[2],Date)) else if Args[0]='ahof' then CloudClient.SendRequestHistoryOffers(GetDate(Args[1],Date-10),GetDate(Args[2],Date)) else if Args[0]='cp' then CloudClient.SendRequestPairsSummary else DoPrintHelp('unknown command, use:'); end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.FMXUI.Wait, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, FireDAC.Comp.UI, Data.Bind.Components, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.Bind.DBScope, FMX.ListView; type TFormMain = class(TForm) FDConnection1: TFDConnection; ListView1: TListView; BindSourceDB1: TBindSourceDB; FDQuery1: TFDQuery; BindingsList1: TBindingsList; LinkFillControlToField1: TLinkFillControlToField; FDGUIxWaitCursor1: TFDGUIxWaitCursor; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; procedure FDConnection1BeforeConnect(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} uses System.IOUtils; procedure TFormMain.FDConnection1BeforeConnect(Sender: TObject); begin FDConnection1.Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, 'employees.sdb'); end; end.
{ The unit is part of Lazarus Chelper package Copyright (C) 2010 Dmitry Boyarintsev skalogryz dot lists at gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit converteridesettings; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ctopasconvert, IniFiles; var ConvSettings : TConvertSettings=nil; ExtTool : AnsiString=''; UseExtTool : Boolean=False; ExtTimeOut : LongWord = 5000; ConvFile : AnsiString=''; DefineFile : AnsiString=''; procedure StringToFile(const Str, DstFileName: AnsiString); function StringFromFile(const SrcFileName: AnsiString): AnsiString; procedure WriteIDESettings(const FileName: AnsiString); procedure ReadIDESettings(const FileName: AnsiString); implementation procedure StringToFile(const Str, DstFileName: AnsiString); var fs: TFileStream; begin fs:=TFileStream.Create(DstFileName, fmCreate); if Str<>'' then fs.Write(Str[1], length(Str)); fs.Free; end; function StringFromFile(const SrcFileName: AnsiString): AnsiString; var fs : TFileStream; begin Result:=''; try if not FileExists(SrcFileName) then Exit; fs:=TFileStream.Create(SrcFileName, fmOpenRead or fmShareDenyNone); try SetLength(Result, fs.Size); if fs.Size>0 then fs.Read(Result[1], fs.Size); finally fs.Free; end; except end; end; procedure WriteIDESettings(const FileName:AnsiString); var ini : TIniFile; begin try ini:=TIniFile.Create(FileName); try ini.WriteBool('Tool', 'UseExt', UseExtTool); ini.WriteString('Tool', 'Exe', ExtTool); ini.WriteString('Tool', 'DefineFile', DefineFile); finally ini.Free; end; except end; end; procedure ReadIDESettings(const FileName:AnsiString); var ini : TIniFile; begin try ini:=TIniFile.Create(FileName); try UseExtTool:=ini.ReadBool('Tool', 'UseExt', UseExtTool); ExtTool:=ini.ReadString('Tool', 'Exe', ExtTool); DefineFile:=ini.ReadString('Tool', 'DefineFile',DefineFile); finally ini.Free; end; except end; end; initialization ConvSettings := TConvertSettings.Create; finalization ConvSettings.Free; end.
unit BassPlayer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dynamic_BASS, StdCtrls, ComCtrls, ExtCtrls, Math; const WM_INFO_UPDATE = WM_USER + 101; { type WAVHDR = packed record riff: array[0..3] of Char; len: DWord; cWavFmt: array[0..7] of Char; dwHdrLen: DWord; wFormat: Word; wNumChannels: Word; dwSampleRate: DWord; dwBytesPerSec: DWord; wBlockAlign: Word; wBitsPerSample: Word; cData: array[0..3] of Char; dwDataLen: DWord; end; } type TfrmBassPlayer = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; lvPlugins: TListView; Memo1: TMemo; lblMeta: TLabel; tmrLoadNowPlaying: TTimer; procedure FormCreate(Sender: TObject); procedure tmrLoadNowPlayingTimer(Sender: TObject); private { Private declarations } public { Public declarations } Sliding: boolean; procedure BASSPlayer_Play(sFileName: String); procedure BASSPlayer_Stop; procedure BASSPlayer_Pause; procedure BASSPlayer_Volume(value: Integer); procedure BASSPlayer_SetEq(index: Integer; value: Integer); procedure BASSPlayer_GetEq(index: Integer; var value: Integer); procedure BASSPlayer_SetReverb(index: Integer; value: Integer); procedure BASSPlayer_GetReverb(index: Integer; var value: Integer); procedure BASSPlayer_FileStreamFree; procedure BASSPlayer_AllFree; procedure Error(const Text: string); function GetCTypeString(ctype: DWORD; plugin: HPLUGIN): string; procedure WndProc(var Msg: TMessage); override; //////////////////////////////////// procedure Player_Stop; procedure PlayStopRadio; procedure Player_ChangeVolume(value: Integer); protected procedure CreateParams (var Params: TCreateParams); override; end; var frmBassPlayer: TfrmBassPlayer; Chan: HStream; cthread: DWORD = 0; // chan: HSTREAM = 0; win: hwnd; { WaveHdr: WAVHDR; // WAV header rchan: HRECORD; // recording channel } Proxy: array [0..99] of char; //proxy server p: BASS_DX8_PARAMEQ; pR: BASS_DX8_REVERB; WaveStream: TMemoryStream; FileStream : TFileStream; implementation uses General, uLNG, Info, DownloadFile, u_qip_plugin, TextSearch, uStatistics, uEqualizer, uNowPlaying, uFileFolder; var fx: array[1..EQ_REVERB] of integer; {$R *.dfm} procedure TfrmBassPlayer.CreateParams (var Params: TCreateParams); begin inherited; with Params do begin ExStyle := (ExStyle or WS_EX_TOOLWINDOW or WS_EX_NOACTIVATE); end; end; procedure Error(es: string); begin Radio_Playing := False; MessageBox(win, PChar(es + #13#10 + '(error code: ' + IntToStr(BASS_ErrorGetCode) + ')'), nil, 0); end; procedure TfrmBassPlayer.Error(const Text: string); begin MessageBox(Handle, PChar(Text + ' Errorcode = ' + inttostr(Bass_ErrorGetCode)), PChar('Error'), 16); end; function ProgDir: string; begin result := ExtractFilePath({ParamStr(0)}PluginDllPath); end; function TfrmBassPlayer.GetCTypeString(ctype: DWORD; plugin: HPLUGIN): string; var pInfo: ^BASS_PLUGININFO; a: integer; begin if plugin <> 0 then begin //pInfo := BASS_PluginGetInfo(plugin); pInfo := pointer(BASS_PluginGetInfo(plugin)); for a := 0 to PInfo.formatc - 1 do if pInfo.Formats[a].ctype = cType then Result := pInfo.Formats[a].name; end; // check built-in stream formats... case cType of BASS_CTYPE_STREAM_MP1: Result := Result + '1'; // 'MPEG Layer-1' BASS_CTYPE_STREAM_MP2: Result := Result + '2'; // 'MPEG Layer-2' BASS_CTYPE_STREAM_MP3: Result := Result + '3'; // 'MPEG Layer-3' BASS_CTYPE_STREAM_OGG: Result := Result + '4'; // 'Ogg Vorbis' BASS_CTYPE_STREAM_WAV_PCM: Result := Result + '5'; // 'PCM WAV' BASS_CTYPE_STREAM_WAV_FLOAT: Result := Result + '6'; // 'Floating-point WAV' BASS_CTYPE_STREAM_WAV: Result := Result + '7'; // 'WAV' BASS_CTYPE_STREAM_AIFF: Result := Result + '8'; // 'Audio IFF' end; if Result = 'Advanced Audio Coding' then Result := '9'; end; procedure DoMeta(); var meta: PAnsiChar; p: Integer; begin meta := BASS_ChannelGetTags(chan, BASS_TAG_META); if (meta <> nil) then begin FBassPlayer.lblMeta.Caption := meta; p := Pos('StreamTitle=', meta); if (p = 0) then Exit; p := p + 13; SendMessage(win, WM_INFO_UPDATE, 7, DWORD(PAnsiChar(Copy(meta, p, Pos(';', meta) - p - 1)))); end; end; procedure MetaSync(handle: HSYNC; channel, data, user: DWORD); stdcall; begin DoMeta(); end; procedure StatusProc(buffer: Pointer; len, user: DWORD); stdcall; begin RecordingBufferSize := len; //Creates a sample stream from an MP3, MP2, MP1, OGG, WAV, AIFF or plugin supported file on the internet, optionally receiving the downloaded data in a callback function. try if StreamRecording = True then begin if (FileStream = nil) then begin //AddLog('Create FileStream'); FileStream := TFileStream.Create(GetRecordTempFile, fmCreate); // create the file //AddLog('Create FileStream Complete'); end; if (buffer = nil) then begin //AddLog('FileStream.Free'); FileStream.Free; // finished downloading //AddLog('FileStream.Free Complete'); end else begin //AddLog('FileStream.WriteBuffer'); FileStream.WriteBuffer(buffer^, len); //AddLog('FileStream.WriteBuffer Complete'); end; end; finally end; try if (buffer <> nil) and (len = 0) then SendMessage(win, WM_INFO_UPDATE, 8, DWORD(PAnsiChar(buffer))); finally end; end; procedure TfrmBassPlayer.WndProc(var Msg: TMessage); // to be threadsave we are passing all Canvas Stuff(e.g. Labels) to this messages begin inherited; try if Msg.Msg = WM_INFO_UPDATE then begin case msg.WParam of 0: begin ExtraText := ''; ExtraTextTime := 0; QIPPlugin.RedrawSpecContact(UniqContactId); if Radio_Playing then Label4.Caption := LNG('PLAYER', 'Connecting', 'Connecting...') else Label4.Caption := LNG('PLAYER', 'NoRadio', 'Nothing to play');; Label3.Caption := ''; Label5.Caption := ''; end; 1: begin ExtraText := LNG('PLAYER', 'NotPlaying', 'Not playing'); ExtraTextTime := 4; QIPPlugin.RedrawSpecContact(UniqContactId); Label4.Caption := LNG('PLAYER', 'NotPlaying', 'Not playing');//'1 ' + 'not playing'; // Error('Can''t play the stream'); end; 2: begin ExtraText := Format(LNG('PLAYER', 'Buffering', 'Buffering... %d%%'), [msg.LParam]); ExtraTextTime := 4; QIPPlugin.RedrawSpecContact(UniqContactId); Label4.Caption := Format(LNG('PLAYER', 'Buffering', 'Buffering... %d%%'), [msg.LParam]);//'2 ' + Format('buffering... %d%%', [msg.LParam]); end; 3: begin ExtraText := ''; ExtraTextTime := 0; QIPPlugin.RedrawSpecContact(UniqContactId); Label4.Caption := PAnsiChar(msg.LParam); end; 4,5,6: Label5.Caption := PAnsiChar(msg.LParam); 7: Label3.Caption := PAnsiChar(msg.LParam); 8: Label5.Caption := PAnsiChar(msg.LParam); //icy info end; ChangeXstatus := True; iSong := Label3.Caption; iRadio := Label4.Caption; iBitrate := Label5.Caption; iCover := ''; iBitrate := Trim(StringReplace(iBitrate, 'bitrate:', '', [])); iTime := 0; end; finally end; try if InfoIsShow=True then begin FInfo.lbleRadio.Text := iRadio; end; finally end; end; procedure TfrmBassPlayer.FormCreate(Sender: TObject); var fd: TWin32FindData; fh: THandle; plug: HPLUGIN; Info: ^Bass_PluginInfo; s: string; a: integer; ListItem: TListItem; i: Integer; MyString, fnn: AnsiString; begin if FileExists(PluginDllPath+'bass.dll')=True then MoveFileIfExists(PluginDllPath+'bass.dll', PluginDllPath+'Plugins\', True); //BassLoadLib( PluginDllPath ); Load_BASSDLL( PluginDllPath + 'Plugins\' + 'bass.dll' ); //Load_BASSDLL( PluginDllPath + 'bass.dll' ); bBassLoadLibLoaded := True; WaveStream := TMemoryStream.Create; // check the correct BASS was loaded win := handle; if (HIWORD(BASS_GetVersion) <> BASSVERSION) then begin MessageBox(0, 'An incorrect version of BASS.DLL was loaded', nil, MB_ICONERROR); Halt; end; if not Bass_Init(-1, 44100, 0, handle, nil) then begin Error('Can''t initialize device'); Application.Terminate; end; BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST, 1); // enable playlist processing BASS_SetConfig(BASS_CONFIG_NET_PREBUF, 0); // minimize automatic pre-buffering, so we can do it (and display it) instead if Proxy_Mode in [1, 2] then BASS_SetConfigPtr(BASS_CONFIG_NET_PROXY, @proxy[0]) // setup proxy server location else BASS_SetConfigPtr(BASS_CONFIG_NET_PROXY, nil); // no proxy! // Set The OpenDialog Filter to the Bass build In Formats { Open1.Filter := 'BASS built-in *.mp3;*.mp2;*.mp1;*.ogg;*.wav;*.aif)\0*.mp3;*.mp2;*.mp1;*.ogg;*.wav;*.aif' + '|' + '*.mp3;*.mp2;*.mp1;*.ogg;*.wav*;*.aif'; } // get the Modules from the currentDirectory // showmessage(ProgDir); // fh := FindFirstFile(PChar(ProgDir + 'bass*.dll'), fd); //label1.Caption := PluginDllPath + 'bass*.dll'; fh := FindFirstFile(PChar(PluginDllPath + 'Plugins\' + 'bass*.dll'), fd); if (fh <> INVALID_HANDLE_VALUE) then try repeat for i:=1 to 260 do MyString := MyString + ' '; for i:=0 to 259 do MyString[ i + 1]:= AnsiChar(fd.cFileName[ i]); // fnn := PChar(PluginDllPath )+ PChar(fd.cFileName); fnn := PluginDllPath + 'Plugins\' + Trim(MyString); memo1.Text := memo1.Text + #13#10 + fnn;//fd.cFileName; // fnn := fnn + plug := BASS_PluginLoad(PAnsiChar(fnn), 0); // plug := BASS_PluginLoad(fd.cFileName, 0); memo1.Text := memo1.Text +' ' + inttostr(plug); if Plug <> 0 then begin // Info := BASS_PluginGetInfo(Plug); // get plugin info to add to the file selector filter... Info := pointer(BASS_PluginGetInfo(Plug)); // get plugin info to add to the file selector filter... for a := 0 to Info.formatc - 1 do begin // Set The OpenDialog additional, to the supported PlugIn Formats { open1.Filter := Open1.Filter + '|' + Info.Formats[a].name + ' ' + '(' + Info.Formats[a].exts + ') , ' + fd.cFileName + '|' + Info.Formats[a].exts; } // Lets Show in the Listview the supported Formats if (Info.Formats[a].name <> nil) then if (a = 0) then s :=Info.Formats[a].name else s := s + ',' + Info.Formats[a].name; end; ListItem := LvPlugIns.Items.Add; ListItem.Caption := fd.cFileName; ListItem.SubItems.Add(s); end; until FindNextFile(fh, fd) = false; finally Windows.FindClose(fh); end; { if LvPlugIns.Items.Count = 0 then begin ListItem := LvPlugIns.Items.Add; ListItem.SubItems.Add('no plugins found - visit the BASS webpage to get some'); end; } end; function OpenURL(url: PAnsiChar): Integer; var Info: Bass_ChannelInfo; // url: Pansichar; icy: PAnsiChar; Len, Progress: DWORD; index, value, i: Integer; begin { if open1.Execute then begin } // Timer1.Enabled := false; // Bass_StreamFree(Chan); //icyx:/85.248.7.162:8000/48.aac Result := 0; BASS_StreamFree(chan); // close old stream progress := 0; SendMessage(win, WM_INFO_UPDATE, 0, 0); // reset the Labels and trying connecting // url := 'mms://netshow4.play.cz/cro1-128'; // url := 'icyx://85.248.7.162:8000/48.aac'; // url := 'http://85.248.7.162:8000/48.aac'; //url := 'http://www.play.cz/radio/frekvence1-128.asx'; //showmessage(url); url := PAnsiChar(PlayURL); //showmessage(url); ////////////// RECORD { with WaveHdr do begin riff := 'RIFF'; len := 36; cWavFmt := 'WAVEfmt '; dwHdrLen := 16; wFormat := 1; wNumChannels := 2; dwSampleRate := 44100; wBlockAlign := 4; dwBytesPerSec := 176400; wBitsPerSample := 16; cData := 'data'; dwDataLen := 0; end; WaveStream.Write(WaveHdr, SizeOf(WAVHDR)); } ///////////////END RECORD /// /// //iHandle = Bass_StreamCreateFile(sFileName, 00, 00, BASSStream.BASS_DEFAULT | BASSStream.BASS_SAMPLE_MONO | BASSStream.BASS_SPEAKER_CENTER | BASSStream.BASS_SPEAKER_LFE | BASSStream.BASS_SPEAKER_REAR2RIGHT | BASSStream.BASS_SPEAKER_REAR2LEFT ); chan := BASS_StreamCreateURL(url, 0, BASS_STREAM_STATUS{BASS_STREAM_RESTRATE} { + BASS_SPEAKER_CENTER + BASS_SPEAKER_LFE} {+ BASS_SPEAKER_REAR2RIGHT + BASS_SPEAKER_REAR2LEFT}, @StatusProc, 0); // chan := BASS_StreamCreateURL(url, 0, BASS_STREAM_STATUS{BASS_STREAM_RESTRATE}, @StatusProc, 0); // BASS_ChannelGetData( ////////////// RECORD (*//BASS_RecordInit(chan); // BASS_RecordSetDevice(chan); BASS_ChannelSetDevice(chan,400); BASS_RecordSetDevice(400); rchan := BASS_RecordStart(44100, 2, 0, @RecordingCallback, nil); if rchan = 0 then begin MessageDlg('Couldn''t start recording!', mtError, [mbOk], 0); WaveStream.Clear; end else begin { bRecord.Caption := 'Stop'; bPlay.Enabled := False; bSave.Enabled := False;} end; *) ///////////////END RECORD /// // BASS_ChannelSetDevice(() // BASS_RecordGetInputName() // Chan := Bass_StreamCreateFile(false, PChar(open1.FileName), 0, 0, BASS_SAMPLE_LOOP); if CHan <> 0 then begin // BASS_ChannelGetInfo(chan, info); // Button1.Caption := open1.FileName; (* lblInfo.Caption := 'channel type = ' + inttostr(info.ctype) + ' ' + getCTypeString(info.ctype, info.plugin);*) // Scrollbar1.Max := round(BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE))); // Bass_ChannelPlay(Chan, false); // Timer1.Enabled := true; // Progress repeat len := BASS_StreamGetFilePosition(chan, BASS_FILEPOS_END); if (len = DW_Error) then break; // something's gone wrong! (eg. BASS_Free called) progress := (BASS_StreamGetFilePosition(chan, BASS_FILEPOS_DOWNLOAD) - BASS_StreamGetFilePosition(chan, BASS_FILEPOS_CURRENT)) * 100 div len; // percentage of buffer filled SendMessage(win, WM_INFO_UPDATE, 2, progress); // show the Progess value in the label until progress > 75; // get the broadcast name and bitrate icy := BASS_ChannelGetTags(chan, BASS_TAG_ICY); if (icy = nil) then icy := BASS_ChannelGetTags(chan, BASS_TAG_HTTP); // no ICY tags, try HTTP if (icy <> nil) then while (icy^ <> #0) do begin if (Copy(icy, 1, 9) = 'icy-name:') then SendMessage(win, WM_INFO_UPDATE, 3, DWORD(PAnsiChar(Copy(icy, 10, MaxInt)))) else if (Copy(icy, 1, 7) = 'icy-br:') then SendMessage(win, WM_INFO_UPDATE, 4, DWORD(PAnsiChar('bitrate: ' + Copy(icy, 8, MaxInt)))); icy := icy + Length(icy) + 1; end; // get the stream title and set sync for subsequent titles DoMeta(); BASS_ChannelSetSync(chan, BASS_SYNC_META, 0, @MetaSync, 0); for i := 1 to FrequencyCount do begin fx[i] := BASS_ChannelSetFX(chan, BASS_FX_DX8_PARAMEQ, 1) end; //Reverb fx[EQ_REVERB] := BASS_ChannelSetFX(chan, BASS_FX_DX8_REVERB, 1); // Set equalizer to flat and reverb off to start p.fGain := 0; p.fBandwidth := 4; for i := 1 to FrequencyCount do begin p.fCenter := StrToInt(slFreqs.Strings[i-1]); BASS_FXSetParameters(fx[i], @p); end; BASS_FXGetParameters(fx[i+1], @pR); pR.fReverbMix := -96; pR.fReverbTime := 1200; pR.fHighFreqRTRatio := 0.1; BASS_FXSetParameters(fx[i+1], @pR); // equalizer enabled? if EqualizerEnabled then begin if EqualizerToRadioGenre then ActiveEqualizer(TStation(Stations.Objects[Radio_StationID]).Genre) else ActiveEqualizer(EqualizerOption); end else begin DeactiveEqualizer; end; // play it! BASS_ChannelPlay(chan, FALSE); end else begin SendMessage(win, WM_INFO_UPDATE, 1, 0); // Oops Error (* Button1.Caption := 'Click here to open a file';*) (* Error('Can''t play the file');*) end; { end; } cthread := 0; end; procedure TfrmBassPlayer.BASSPlayer_Play(sFileName: String); var x: Boolean; ThreadId: Cardinal; begin //showmessage(AnsiUpperCase(Copy(sFileName,7))); //icyx://85.248.7.162:8000/48.aac if AnsiUpperCase(Copy(sFileName,1,7))=AnsiUpperCase('icyx://') then PlayURL := 'http://' + Copy(sFileName,8) else if AnsiUpperCase(Copy(sFileName,1,6))=AnsiUpperCase('icyx:/') then PlayURL := 'http://' + Copy(sFileName,7) else PlayURL := sFileName; // showmessage(PlayURL); //showmessage(sFileName); StrPCopy(proxy,Proxy_Server); // copy the Servertext to the Proxy array if (cthread <> 0) then MessageBeep(0) else cthread := BeginThread(nil, 0, @OpenURL, PAnsiChar('not'), 0, ThreadId); end; procedure TfrmBassPlayer.BASSPlayer_Stop; var x: Boolean; begin { x := BASS_Stop; } try BASS_StreamFree(chan); // close old stream SendMessage(win, WM_INFO_UPDATE, 0, 0); finally end; {if savedialog.Execute then begin StartRecord.enabled := false; CopyFile(PAnsiChar(GetTempFile),PAnsiChar(savedialog1.FileName),false); StartRecord.enabled := true; end; } end; procedure TfrmBassPlayer.BASSPlayer_Pause; var x: Boolean; begin x := BASS_Pause; end; procedure TfrmBassPlayer.BASSPlayer_Volume(value: Integer); //var f: Float; var v: Cardinal; begin // BassPlayer1.Volume := value; // f := value / 100; v := round(value * (10000 / 100)) ; //BASS_SetVolume (f); // BASS_ChannelSetAttribute(chan, BASS_ATTRIB_MUSIC_VOL_GLOBAL, 0); // BASS_ChannelSetAttribute(chan, BASS_ATTRIB_MUSIC_VOL_CHAN, 0); // BASS_ChannelSetAttribute(chan, BASS_ATTRIB_PAN, 100); // BASS_ChannelSetAttribute(chan, BASS_ATTRIB_VOL, 100); //showmessage( floattostr( BASS_GetVolume) ); BASS_SetConfig(BASS_CONFIG_GVOL_MUSIC, v ); BASS_SetConfig(BASS_CONFIG_GVOL_STREAM, v ); end; procedure TfrmBassPlayer.BASSPlayer_SetEq(index: Integer; value: Integer); begin BASS_FXGetParameters(fx[index], @p); p.fGain := value; BASS_FXSetParameters(fx[index], @p); end; procedure TfrmBassPlayer.BASSPlayer_GetEq(index: Integer; var value: Integer); begin BASS_FXGetParameters(fx[index], @p); value := Round(p.fGain); end; procedure TfrmBassPlayer.BASSPlayer_SetReverb(index: Integer; value: Integer); begin BASS_FXGetParameters(fx[index], @pR); // give exponential quality to trackbar as Bass more sensitive near 0 pR.fReverbMix := -0.012*value*value*value; // gives -96 when bar at 20 BASS_FXSetParameters(fx[index], @pR); end; procedure TfrmBassPlayer.BASSPlayer_GetReverb(index: Integer; var value: Integer); begin BASS_FXGetParameters(fx[index], @pR); value := Round( Power( pR.fReverbMix / (-0.012), 1/3 ) ); end; procedure TfrmBassPlayer.BASSPlayer_FileStreamFree; begin try FileStream.Destroy; // finished downloading finally end; end; procedure TfrmBassPlayer.BASSPlayer_AllFree; begin try Bass_Free(); BASS_PluginFree(0); finally end; end; procedure TfrmBassPlayer.Player_Stop; begin FBassPlayer.BASSPlayer_Stop; end; procedure TfrmBassPlayer.PlayStopRadio; var HTMLData: TResultData; iFS, iFS1, iFS2: Integer; sPlayURL, sExt, sURL: WideString; // F: TextFile; // s : string; // i : integer; // sTempFileName: WideString; sToken, sStream, smyAdID : WideString; label 1,2,3,4,5,0; begin if Stations.Count = 0 then begin QIPPlugin.AddFadeMsg(1, PluginSkin.PluginIcon.Icon.Handle, PLUGIN_NAME, LNG('PLAYER', 'NoRadio', 'Nothing to play.'), True, False, 0, 0); Exit; end; if (Stations.Count - 1 < Radio_StationID) AND (Radio_StationID <> -1) then begin { if Radio_Playing = False then begin end else begin end; } end else if TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 < Radio_StreamID then begin // end; begin if TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL = '' then begin Radio_Playing := False; Radio_PlayingError := True; QIPPlugin.AddFadeMsg(1, PluginSkin.PluginIcon.Icon.Handle, PLUGIN_NAME, LNG('PLAYER', 'NoRadio', 'Nothing to play.'), True, False, 0, 0); Exit; end; end; if Radio_Playing = False then begin if Stations.Count - 1 < Radio_StationID then begin QIPPlugin.AddFadeMsg(1, PluginSkin.PluginIcon.Icon.Handle, PLUGIN_NAME, LNG('PLAYER', 'NoRadio', 'Nothing to play.'), True, False, 0, 0); end else begin Playlist.Clear; Statistics_PlayCount_Add( TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL ); sExt := AnsiUpperCase(ExtractFileExt(TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL)); sURL := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL; if (sExt='.ASX') and (Proxy_Mode = 0) then //result:='Windows Media ASX Playlist'; begin try HTMLData := GetHTML(TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL, '', '', 5000, NO_CACHE, DownloadingInfo); except end; if HTMLData.OK = True then begin sPlayURL := FoundStr(HTMLData.parString, '<entry>', '</entry>', 1, iFS, iFS1, iFS2); sPlayURL := FoundStr(sPlayURL, '<Ref', '>', 1, iFS, iFS1, iFS2); sPlayURL := FoundStr(sPlayURL, '"', '"', 1, iFS, iFS1, iFS2); //Playlist.Add(sPlayURL); end; end else if (AnsiUpperCase(Copy(sURL,1,Length('http://lsd.newmedia.tiscali-business.com') )) = AnsiUpperCase( 'http://lsd.newmedia.tiscali-business.com' )) or (AnsiUpperCase(Copy(sURL,1,Length('http://213.200.64.229/') )) = AnsiUpperCase( 'http://213.200.64.229/' ) ) then //nacamar or nacmar ip (redirect) begin if AnsiUpperCase(Copy(sURL,Length(sURL) - Length('frameset.html') + 1)) = AnsiUpperCase('frameset.html') then begin sURL := Copy(sURL,1, Length(sURL) - Length('frameset.html')) + 'forwarder_wmt.html'; end else if AnsiUpperCase(Copy(sURL,Length(sURL) - Length('frameset_wmt.html') + 1)) = AnsiUpperCase('frameset_wmt.html') then begin sURL := Copy(sURL,1, Length(sURL) - Length('frameset_wmt.html')) + 'forwarder_wmt.html'; end else if AnsiUpperCase(Copy(sURL,Length(sURL) - Length('frameset_real.html') + 1)) = AnsiUpperCase('frameset_real.html') then begin sURL := Copy(sURL,1, Length(sURL) - Length('frameset_real.html')) + 'forwarder.html'; end; HTMLData.parString := ''; try HTMLData := GetHTML(sURL, '', '', 5000, NO_CACHE, DownloadingInfo); except end; if HTMLData.OK = True then begin sURL := FoundStr(HTMLData.parString, 'url=', '"',1, iFS , iFS1, iFS2 ); HTMLData.parString := ''; try HTMLData := GetHTML(sURL, '', '', 5000, NO_CACHE, DownloadingInfo); except end; if HTMLData.OK = True then begin sToken := FoundStr(HTMLData.parString, 'var token', ';',1, iFS , iFS1, iFS2 ); sToken := FoundStr(sToken, '"', '"',1, iFS , iFS1, iFS2 ); sStream := FoundStr(HTMLData.parString, 'var stream', ';',1, iFS , iFS1, iFS2 ); sStream := FoundStr(sStream, '"', '"',1, iFS , iFS1, iFS2 ); smyAdID := '0'; sPlayURL := 'http://lsd.newmedia.tiscali-business.com/bb/redirect.lsc?adid='+smyAdID+'&stream='+sStream+'&content=live&media=ms&token='+sToken; end; end; end else begin sPlayURL := TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL; end; { http://lsd.newmedia.tiscali-business.com/bb/redirect.lsc?content=download&media=http&stream=freestream/radiotop40/frameset.html forwarder_wmt.html http://213.200.64.229/freestream/download/radiotop40/forwarder_wmt.html http://lsd.newmedia.tiscali-business.com/bb/redirect.lsc?content=download&media=http&stream=freestream/radiotop40/forwarder_wmt.html } (* else if sExt='.WAX' then //result:='WAX'; begin try HTMLData := GetHTML(TSLStream(TSLStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL, Info); except end; if HTMLData.OK = True then begin sPlayURL := Trim(HTMLData.parString); Playlist.Add(sPlayURL); end; end else begin Playlist.Add( TSLStream(TSLStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL ); end; { showmessage(INTTOSTR( Playlist.Count )); for i := 0 to Playlist.Count - 1 do showmessage(Playlist.Strings[i]); } PlaylistNow := -1; *) ; FBassPlayer.BASSPlayer_Play(sPlayURL);//( TSLStream(TSLStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL ); { if sPlayURL<>'' then begin FfrmBassPlayer.BASSPlayer_Play( TSLStream(TSLStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL ); end else begin FfrmBassPlayer.BASSPlayer_Play(TSLStream(TSLStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL); end; } // FfrmBassPlayer.BASSPlayer_Play('mms://netshow3.play.cz/jih48'); // WindowsMediaPlayer1.URL := TSLStream(TSLStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL; Radio_Playing := True; Radio_PlayingError := False; ChangeXstatus := True; end; QIPPlugin.RedrawSpecContact(UniqContactId); //RedrawSpecCnt := True; end else begin //WindowsMediaPlayer1.controls.stop; Radio_Playing := False; Radio_PlayingError := False; Player_Stop; LastRadioFadeMsg := ''; QIPPlugin.RedrawSpecContact(UniqContactId); //RedrawSpecCnt := True; ChangeXstatus := True; end; {showmessage(BoolToStr( XStatus_Boolean) + #13 + BoolToStr( ChangeXstatus)); } // showmessage(INTTOSTR(WindowsMediaPlayer1.settings.volume)) end; procedure TfrmBassPlayer.Player_ChangeVolume(value: Integer); begin FBassPlayer.BASSPlayer_Volume(value); end; procedure LoadNowPlaying; var s: WideString; begin try if (Radio_StationID <> -1) or (Radio_StreamID <> -1) then begin if TStation(Stations.Objects[Radio_StationID]).Streams.Count - 1 >= Radio_StreamID then s := GetNowPlaying( TStream(TStation(Stations.Objects[Radio_StationID]).Streams.Objects[Radio_StreamID]).URL ); if s<>'' then begin if iSong <> s then // pokud se změnila písnička... begin iTime := 0; // ...tak resetuj počítadlo ChangeXstatus := True; end; RadioExternalInfo := True; iSong := s; iRadio := TStation(Stations.Objects[Radio_StationID]).Name; end else RadioExternalInfo := False; end; except end; LoadNowPlayingThread := 0; end; procedure TfrmBassPlayer.tmrLoadNowPlayingTimer(Sender: TObject); var ThreadId: Cardinal; begin if LoadSongsExternal = True then begin if Radio_Playing = True then begin LoadNowPlayingThread := BeginThread(nil, 0, @LoadNowPlaying, nil, 0, ThreadId); end; end; end; end.
unit ts2pas.Main; interface uses NodeJS.Core, NodeJS.FS, NodeJS.https, NodeJS.events, TypeScript, ts2pas.Translator; function TranslateFile(InputFile, OutputFile: String): Boolean; overload; function TranslateFile(InputFile: String): Boolean; overload; procedure LoadAndTranslate(URL: String); {$IFNDEF CommandLine} procedure TranslateDirectory(Directory: String); procedure OutputAst(InputFile: String); procedure ProcesAllUrls; {$ENDIF} implementation var FileSystem := fs; {$IFNDEF CommandLine} procedure TranslateDirectory(Directory: String); var Success: array of String; begin FileSystem.readdir(Directory, lambda(err: JError; files: array of string) for var File in files do begin // only consider files with .d.ts extension if not File.EndsWith('.d.ts') then continue; if TranslateFile(Directory + File) then Success.Add(File) else // Exit; end; end); end; {$ENDIF} function TranslateFile(InputFile, OutputFile: String): Boolean; overload; begin var InputName := InputFile.Before('.d.ts'); if InputFile = InputName then InputFile += '.d.ts'; var Data := FileSystem.readFileSync(InputFile); if not Assigned(data) then Exit; var InputText := data.toString('utf8'); {$IFDEF DEBUG} Console.Log('Converting file ' + InputFile); {$ENDIF} var Translator := TTranslator.Create; Translator.Name := InputName; var OutputText := Translator.Translate(InputText); Result := OutputText <> ''; if OutputText.Length > 5 then FileSystem.writeFileSync(OutputFile, OutputText); {$IFDEF DEBUG} Console.Log('Done!'); Console.Log(''); {$ENDIF} Translator := nil; end; function TranslateFile(InputFile: String): Boolean; overload; begin Result := TranslateFile(InputFile, InputFile.Before('.d.ts') + '.pas'); end; {$IFNDEF CommandLine} function DelintNode(Node: JNode): Variant; begin case Node.Kind of TSyntaxKind.StringLiteral: Console.Log(JIdentifier(Node).Text); TSyntaxKind.Identifier: Console.Log(JIdentifier(Node).Text); TSyntaxKind.TypeReference: Console.Log(JIdentifier(Node).Text); TSyntaxKind.DeclareKeyword: Console.Log('declare'); (* TSyntaxKind.ModuleBlock: Console.Log(JModuleBlock(Node).) *) TSyntaxKind.QualifiedName: Console.Log(JQualifiedName(Node).left); else Console.Log(Node.Kind); end; TypeScriptExport.forEachChild(Node, @DelintNode); end; procedure Delint(SourceFile: JSourceFile); begin DelintNode(SourceFile); end; procedure OutputAst(InputFile: String); begin if InputFile = InputFile.Before('.d.ts') then InputFile += '.d.ts'; FileSystem.readFile(InputFile, lambda(err: Variant; data: JNodeBuffer) var InputText := data.toString('utf8'); var SourceFile := TypeScriptExport.createSourceFile(InputFile, InputText, TScriptTarget.ES6, true); delint(SourceFile); end); end; {$ENDIF} procedure LoadAndTranslate(Url: String); begin var Https := NodeJS.https.https; var Options := new JRequestOptions; Options.hostname := 'raw.githubusercontent.com'; Options.path := Url; Console.Log('Fetching: ' + URL); var Translator := TTranslator.Create; var ClientRequest := Https.get(Options, lambda(EventEmitter: JNodeEventEmitter) var InputText := ''; var URLParts := Url.Split('/'); var InputName := URLParts[High(URLParts)].Before('.d.ts'); var OutputFile := InputName + '.pas'; // concat each chunk of data EventEmitter.on('data', lambda(ChunkText: Variant) InputText += ChunkText; end); // done EventEmitter.on('end', lambda Console.Log('Translating: ' + InputName); Translator.Name := InputName; var OutputText := Translator.Translate(InputText); Console.Log('Writing: ' + OutputFile); if OutputText.Length > 5 then FileSystem.writeFile(OutputFile, OutputText, lambda(Error: Variant) end); {$IFDEF DEBUG} Console.Log('Done!'); Console.Log(''); {$ENDIF} end); end); ClientRequest.on('error', lambda(Error: variant) Console.Log('Error: ', Error); end); end; {$IFNDEF CommandLine} procedure ProcesAllUrls; begin var URLs = [ 'abs/abs.d.ts', 'absolute/absolute.d.ts', 'accounting/accounting.d.ts', 'acc-wizard/acc-wizard.d.ts', 'amazon-product-api/amazon-product-api.d.ts', 'amcharts/AmCharts.d.ts', 'amplifyjs/amplifyjs.d.ts', 'box2d/box2dweb.d.ts', 'browserify/browserify.d.ts', 'd3/d3.d.ts', 'devextreme/devextreme.d.ts', 'dojo/dijit.d.ts', 'dojo/dojo.d.ts', 'easeljs/easeljs.d.ts', 'ember/ember.d.ts', 'express/express.d.ts', 'fabricjs/fabricjs.d.ts', 'gruntjs/gruntjs.d.ts', 'hapi/hapi.d.ts', 'jquery/jquery.d.ts', 'jquerymobile/jquerymobile.d.ts', 'kendo-ui/kendo-ui.d.ts', 'leapmotionTS/LeapMotionTS.d.ts', 'linq/linq.d.ts', 'matter-js/matter-js.d.ts', 'office-js/office-js.d.ts', 'openlayers/openlayers.d.ts', 'phantom/phantom.d.ts', 'phantomjs/phantomjs.d.ts', 'phonegap/phonegap.d.ts', 'plottable/plottable.d.ts', 'preloadjs/preloadjs.d.ts', 'socket.io/socket.io.d.ts', 'soundjs/soundjs.d.ts', 'titanium/titanium.d.ts', 'tweenjs/tweenjs.d.ts', 'typescript/typescript.d.ts', 'ui-grid/ui-grid.d.ts', 'webix/webix.d.ts', 'winjs/winjs.d.ts', 'winrt/winrt.d.ts', 'youtube/youtube.d.ts' ]; for var URL in URLs do LoadAndTranslate('/DefinitelyTyped/DefinitelyTyped/master/' + URL); end; {$ENDIF} end.
unit DAO.Entregas; interface uses Model.Entregas, System.Classes, FireDAC.Comp.Client, DAO.Conexao, Control.Sistema, System.DateUtils; type TEntregasDAO = class private FConexao : TConexao; public constructor Create; function Insert(aEntregas: Model.Entregas.Tentregas): Boolean; function Update(aEntregas: Model.Entregas.TEntregas): Boolean; function Delete(aEntregas: Model.Entregas.TEntregas): Boolean; function FindEntrega(aParam: array of Variant): TFDQuery; function ChangeConferencia(sNN: String; iStatus: Integer): Boolean; function ExisteNN(sNN: String): Boolean; function Previas(aParam: Array of variant): TFDQuery; function ForaPadrao(aParam: Array of variant): TFDQuery; function EntregasExtrato(aParam: Array of variant): TFDQuery; function EntregasExtratoNew(aParam: Array of variant): TFDQuery; function ExtratoBase(aParam: array of variant): TFDQuery; function ExtratoEntregador(aParam: array of variant): TFDQuery; end; const TABLENAME = 'tbentregas'; implementation uses System.SysUtils, Data.DB; function TEntregasDAO.Insert(aEntregas: TEntregas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.Connection.Ping; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + '(NUM_NOSSONUMERO, COD_AGENTE, COD_ENTREGADOR, COD_CLIENTE, NUM_NF, NOM_CONSUMIDOR, DES_ENDERECO, DES_COMPLEMENTO, ' + 'DES_BAIRRO, NOM_CIDADE, NUM_CEP, NUM_TELEFONE, DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO, QTD_VOLUMES, DAT_ATRIBUICAO, ' + 'DAT_BAIXA, DOM_BAIXADO, DAT_PAGAMENTO, DOM_PAGO, DOM_FECHADO, COD_STATUS, DAT_ENTREGA, QTD_PESO_REAL, ' + 'QTD_PESO_FRANQUIA, VAL_VERBA_FRANQUIA, VAL_ADVALOREM, VAL_PAGO_FRANQUIA, VAL_VERBA_ENTREGADOR, NUM_EXTRATO, ' + 'QTD_DIAS_ATRASO, QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO, DES_TIPO_PESO, DAT_RECEBIDO, DOM_RECEBIDO, ' + 'NUM_CTRC, NUM_MANIFESTO, DES_RASTREIO, NUM_LOTE_REMESSA, DES_RETORNO, DAT_CREDITO, DOM_CREDITO, NUM_CONTAINER, ' + 'VAL_PRODUTO, QTD_ALTURA, QTD_LARGURA, QTD_COMPRIMENTO, COD_FEEDBACK, DAT_FEEDBACK, DOM_CONFERIDO, NUM_PEDIDO, ' + 'COD_CLIENTE_EMPRESA) ' + 'VALUES ' + '(:NUM_NOSSONUMERO, :COD_AGENTE, :COD_ENTREGADOR, :COD_CLIENTE, :NUM_NF, :NOM_CONSUMIDOR, :DES_ENDERECO, ' + ':DES_COMPLEMENTO, :DES_BAIRRO, :NOM_CIDADE, :NUM_CEP, :NUM_TELEFONE, :DAT_EXPEDICAO, :DAT_PREV_DISTRIBUICAO, ' + ':QTD_VOLUMES, :DAT_ATRIBUICAO, :DAT_BAIXA, :DOM_BAIXADO, :DAT_PAGAMENTO, :DOM_PAGO, :DOM_FECHADO, :COD_STATUS, ' + ':DAT_ENTREGA, :QTD_PESO_REAL, :QTD_PESO_FRANQUIA, :VAL_VERBA_FRANQUIA, :VAL_ADVALOREM, :VAL_PAGO_FRANQUIA, ' + ':VAL_VERBA_ENTREGADOR, :NUM_EXTRATO, :QTD_DIAS_ATRASO, :QTD_VOLUMES_EXTRA, :VAL_VOLUMES_EXTRA, :QTD_PESO_COBRADO, ' + ':DES_TIPO_PESO, :DAT_RECEBIDO, :DOM_RECEBIDO, :NUM_CTRC, :NUM_MANIFESTO, :DES_RASTREIO, :NUM_LOTE_REMESSA, ' + ':DES_RETORNO, :DAT_CREDITO, :DOM_CREDITO, :NUM_CONTAINER, :VAL_PRODUTO, :QTD_ALTURA, :QTD_LARGURA, :QTD_COMPRIMENTO, ' + ':COD_FEEDBACK, :DAT_FEEDBACK, :DOM_CONFERIDO, :NUM_PEDIDO, :COD_CLIENTE_EMPRESA);', [aEntregas.NN, aEntregas.Distribuidor, aEntregas.Entregador, aEntregas.Cliente, aEntregas.NF, aEntregas.Consumidor, aEntregas.Endereco, aEntregas.Complemento, aEntregas.Bairro, aEntregas.Cidade, aEntregas.CEP, aEntregas.Telefone, aEntregas.Expedicao, aEntregas.Previsao, aEntregas.Volumes, aEntregas.Atribuicao, aEntregas.Baixa, aEntregas.Baixado, aEntregas.Pagamento, aEntregas.Pago, aEntregas.Fechado, aEntregas.Status, aEntregas.Entrega, aEntregas.PesoReal, aEntregas.PesoFranquia, aEntregas.VerbaFranquia, aEntregas.Advalorem, aEntregas.PagoFranquia, aEntregas.VerbaEntregador, aEntregas.Extrato, aEntregas.Atraso, aEntregas.VolumesExtra, aEntregas.ValorVolumes, aEntregas.PesoCobrado, aEntregas.TipoPeso, aEntregas.Recebimento, aEntregas.Recebido, aEntregas.CTRC, aEntregas.Manifesto, aEntregas.Rastreio, aEntregas.Lote, aEntregas.Retorno, aEntregas.Credito, aEntregas.Creditado, aEntregas.Container, aEntregas.ValorProduto, aEntregas.Altura, aEntregas.Largura, aEntregas.Comprimento, aEntregas.CodigoFeedback, aEntregas.DataFeedback, aEntregas.Conferido, aEntregas.Pedido, aEntregas.CodCliente]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEntregasDAO.Previas(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; datInicio: TDate; datFinal: TDate; sSQL: String; i : Integer; iDias: Integer; datData: TDate; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) = 0 then begin Exit; end; datInicio := aParam[1]; datFinal := aParam[2]; iDias := DaysBetween(datInicio, datFinal); FDQuery.SQL.Clear; FDQuery.SQL.Add('select distinct(tbentregas.cod_entregador) as Entregador, '); datData := datInicio; sSQL := ''; for i := 1 to iDias + 1 do begin if not sSQL.IsEmpty then sSQL := sSQL + ', '; sSQL := sSQL + 'SUM(IF(day(' + TABLENAME + '.dat_baixa) = ' + IntToStr(DayOf(datData)) +', 1, 0)) as ' + QuotedStr(Copy(FormatDateTime('dd/mm/yyyy', datData),1,5)); datData := IncDay(datData,1); end; FDQuery.SQL.Add(sSQL); FDQuery.SQL.Add('from ' + TABLENAME); FDQuery.SQL.Add('where cod_agente = :agente and dat_baixa between :data1 and :data2 group by ' + TABLENAME + '.cod_entregador'); FDQuery.ParamByName('agente').AsInteger := aParam[0]; FDQuery.ParamByName('data1').AsDate := aParam[1]; FDQuery.ParamByName('data2').AsDate := aParam[2]; FDQuery.Open(); Result := FDQuery; end; function TEntregasDAO.Update(aEntregas: TEntregas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.Connection.Ping; FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' ' + 'SET ' + 'COD_AGENTE = :COD_AGENTE, COD_ENTREGADOR = :COD_ENTREGADOR, ' + 'COD_CLIENTE = :COD_CLIENTE, NUM_NF = :NUM_NF, NOM_CONSUMIDOR = :NOM_CONSUMIDOR, DES_ENDERECO = :DES_ENDERECO, ' + 'DES_COMPLEMENTO = :DES_COMPLEMENTO, DES_BAIRRO = :DES_BAIRRO, NOM_CIDADE = :NOM_CIDADE, NUM_CEP = :NUM_CEP, ' + 'NUM_TELEFONE = :NUM_TELEFONE, DAT_EXPEDICAO = :DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO = :DAT_PREV_DISTRIBUICAO, ' + 'QTD_VOLUMES = :QTD_VOLUMES, DAT_ATRIBUICAO = :DAT_ATRIBUICAO, DAT_BAIXA = :DAT_BAIXA, DOM_BAIXADO = :DOM_BAIXADO, ' + 'DAT_PAGAMENTO = :DAT_PAGAMENTO, DOM_PAGO = :DOM_PAGO, DOM_FECHADO = :DOM_FECHADO, COD_STATUS = :COD_STATUS, ' + 'DAT_ENTREGA = :DAT_ENTREGA, QTD_PESO_REAL = :QTD_PESO_REAL, QTD_PESO_FRANQUIA = :QTD_PESO_FRANQUIA, ' + 'VAL_VERBA_FRANQUIA = :VAL_VERBA_FRANQUIA, VAL_ADVALOREM = :VAL_ADVALOREM, VAL_PAGO_FRANQUIA = :VAL_PAGO_FRANQUIA, ' + 'VAL_VERBA_ENTREGADOR = :VAL_VERBA_ENTREGADOR, NUM_EXTRATO = :NUM_EXTRATO, QTD_DIAS_ATRASO = :QTD_DIAS_ATRASO, ' + 'QTD_VOLUMES_EXTRA = :QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA = :VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO = :QTD_PESO_COBRADO, ' + 'DES_TIPO_PESO = :DES_TIPO_PESO, DAT_RECEBIDO = :DAT_RECEBIDO, DOM_RECEBIDO = :DOM_RECEBIDO, NUM_CTRC = :NUM_CTRC, ' + 'NUM_MANIFESTO = :NUM_MANIFESTO, DES_RASTREIO = :DES_RASTREIO, NUM_LOTE_REMESSA = :NUM_LOTE_REMESSA, ' + 'DES_RETORNO = :DES_RETORNO, DAT_CREDITO = :DAT_CREDITO, DOM_CREDITO = :DOM_CREDITO, NUM_CONTAINER = :NUM_CONTAINER, ' + 'VAL_PRODUTO = :VAL_PRODUTO, QTD_ALTURA = :QTD_ALTURA, QTD_LARGURA = :QTD_LARGURA, QTD_COMPRIMENTO = :QTD_COMPRIMENTO, ' + 'COD_FEEDBACK = :COD_FEEDBACK, DAT_FEEDBACK = :DAT_FEEDBACK, DOM_CONFERIDO = :DOM_CONFERIDO, ' + 'NUM_PEDIDO = :NUM_PEDIDO, COD_CLIENTE_EMPRESA = :COD_CLIENTE_EMPRESA ' + 'WHERE ' + 'NUM_NOSSONUMERO = :NUM_NOSSONUMERO;' ,[aEntregas.Distribuidor, aEntregas.Entregador, aEntregas.Cliente, aEntregas.NF, aEntregas.Consumidor, aEntregas.Endereco, aEntregas.Complemento, aEntregas.Bairro, aEntregas.Cidade, aEntregas.CEP, aEntregas.Telefone, aEntregas.Expedicao, aEntregas.Previsao, aEntregas.Volumes, aEntregas.Atribuicao, aEntregas.Baixa, aEntregas.Baixado, aEntregas.Pagamento, aEntregas.Pago, aEntregas.Fechado, aEntregas.Status, aEntregas.Entrega, aEntregas.PesoReal, aEntregas.PesoFranquia, aEntregas.VerbaFranquia, aEntregas.Advalorem, aEntregas.PagoFranquia, aEntregas.VerbaEntregador, aEntregas.Extrato, aEntregas.Atraso, aEntregas.VolumesExtra, aEntregas.ValorVolumes, aEntregas.PesoCobrado, aEntregas.TipoPeso, aEntregas.Recebimento, aEntregas.Recebido, aEntregas.CTRC, aEntregas.Manifesto, aEntregas.Rastreio, aEntregas.Lote, aEntregas.Retorno, aEntregas.Credito, aEntregas.Creditado, aEntregas.Container, aEntregas.ValorProduto, aEntregas.Altura, aEntregas.Largura, aEntregas.Comprimento, aEntregas.CodigoFeedback, aEntregas.DataFeedback, aEntregas.Conferido, aEntregas.Pedido, aEntregas.CodCliente, aEntregas.NN]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEntregasDAO.ChangeConferencia(sNN: String; iStatus: Integer): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET DOM_CONFERIDO = :DOM_CONFERIDO WHERE ' + 'NUM_NOSSONUMERO = :NUM_NOSSONUMERO;',[iStatus, sNN]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TEntregasDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TEntregasDAO.Delete(aEntregas: TEntregas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where NUM_NOSSONUMERO = :NUM_NOSSONUMERO', [aEntregas.NN]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TEntregasDAO.EntregasExtrato(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; sSQL: String; begin sSQL := 'select cod_cliente_empresa, cod_entregador, count(num_nossonumero) as entregas, val_verba_entregador, ' + '(count(num_nossonumero) * val_verba_entregador) as total from '+ TABLENAME + ' where dat_baixa between :data1 and :data2 ' + 'and dom_baixado = :dom and cod_agente = :agente and qtd_peso_cobrado <= 25 group by cod_cliente_empresa, cod_entregador, val_verba_entregador'; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Text := sSQL; FDQuery.ParamByName('data1').Value := FloatToDateTime(aParam[0]); FDQuery.ParamByName('data2').Value := FloatToDateTime(aParam[1]); FDQuery.ParamByName('agente').Value := aParam[2]; FDQuery.ParamByName('dom').Value := aParam[3]; FDQuery.Open(); Result := FDQuery; end; function TEntregasDAO.EntregasExtratoNew(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; sSQL: String; begin sSQL := 'select tbentregas.cod_agente as cod_agente, tbagentes.nom_fantasia as nom_agente, ' + 'tbentregas.cod_entregador as cod_entregador, tbcodigosentregadores.nom_fantasia as nom_entregador, ' + '(100 - ((sum(if(tbentregas.qtd_dias_atraso > 0,1,0)) / count(tbentregas.num_nossonumero))) * 100) as val_percentual_sla, ' + 'sum(tbentregas.qtd_volumes) as qtd_volumes, sum(1) as qtd_entregas, '; if aParam[3] = True then begin sSQL := sSQL + 'if(tbentregas.qtd_peso_cobrado <= 25,((sum(tbentregas.qtd_volumes) -sum(if(tbentregas.qtd_peso_cobrado <= 25 , 1 , 0))) / 2), 0) as qtd_volumes_extra, '; end else begin sSQL := sSQL + ' 0 as qtd_volumes_extra, '; end; sSQL := sSQL + 'sum(if(tbentregas.qtd_peso_cobrado > 25 , 1 , 0)) as qtd_pfp, tbentregas.val_verba_entregador as val_verba, ' + 'sum(if(tbentregas.qtd_dias_atraso > 0,1,0)) as qtd_itens_atraso ' + 'from ' + TABLENAME + ' join tbagentes on tbagentes.cod_agente = tbentregas.cod_agente ' + 'join tbcodigosentregadores on tbcodigosentregadores.cod_entregador = tbentregas.cod_entregador ' + 'where tbentregas.dom_baixado = :dom and dom_fechado <> :fechado '; if aParam[4] = True then begin sSQL := sSQL + 'and bentregas.dat_baixa <= :data2 '; end else begin sSQL := sSQL + 'and tbentregas.dat_baixa between :data1 and :data2 '; end; if aParam[2] > 0 then begin sSQL := sSQL + ' and cod_cliente_empresa = :cliente ' end; sSQL := sSQL + 'group by tbentregas.cod_agente, tbentregas.cod_entregador, tbentregas.val_verba_entregador;'; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Text := sSQL; FDQuery.ParamByName('data1').Value := FloatToDateTime(aParam[0]); FDQuery.ParamByName('data2').Value := FloatToDateTime(aParam[1]); if aParam[2] > 0 then begin FDQuery.ParamByName('cliente').Value := aParam[2]; end; FDQuery.ParamByName('dom').Value := 'S'; FDQuery.ParamByName('fechado').Value := 'S'; FDQuery.Open(); Result := FDQuery; end; function TEntregasDAO.ExisteNN(sNN: String): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME + ' WHERE NUM_NOSSONUMERO = :NN'); FDQuery.ParamByName('NN').AsString := sNN; FDQuery.Open(); if FDQuery.IsEmpty then Exit; Result := True finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEntregasDAO.ExtratoBase(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; sSQL: String; begin sSQL := 'select tbentregas.cod_agente as cod_expressa, sum(tbentregas.qtd_volumes) as qtd_volumes, ' + 'count(tbentregas.num_nossonumero) as qtd_entregas, ' + 'sum(tbentregas.val_verba_entregador) as val_producao, '; if aParam[3] = True then begin sSQL := sSQL + '(sum(tbentregas.qtd_volumes) - sum(if(tbentregas.qtd_peso_cobrado <= 25 , 1 , 0))) / 2 as qtd_volumes_extra, '; sSQL := sSQL + '((sum(tbentregas.qtd_volumes) - sum(if(tbentregas.qtd_peso_cobrado <= 25 , 1 , 0))) / 2) * ' + '(if(tbentregas.qtd_peso_cobrado <= 25 , tbentregas.val_verba_entregador , 0)) as val_volume_extra, '; end else begin sSQL := sSQL + ' 0 as qtd_volumes_extra, '; sSQL := sSQL + ' 0 as val_volumes_extra, '; end; sSQL := sSQL + 'sum(if(tbentregas.qtd_dias_atraso > 0,1,0)) as qtd_atraso, ' + '(100 - ((sum(if(tbentregas.qtd_dias_atraso > 0,1,0)) / count(tbentregas.num_nossonumero))) * 100) as val_performance, ' + 'sum(tbentregas.val_verba_franquia) as val_total_ticket, ' + '0 as val_ticket_medio, ' + 'if(tbagentes.des_forma_pagamento <> "NENHUMA",1,0) as cod_tipo_expressa, ' + 'tbagentes.nom_fantasia as nom_expressa, ' + 'tbbancos.nom_banco as nom_banco, ' + 'tbagentes.des_tipo_conta as des_tipo_conta, ' + 'tbagentes.cod_agencia as num_agencia, ' + 'tbagentes.num_conta as num_conta, ' + 'tbagentes.nom_favorecido as nom_favorecido, ' + 'tbagentes.num_cpf_cnpj_favorecido as num_cpf_cnpj, ' + 'sum(if(tbentregas.qtd_peso_cobrado > 25,1,0)) as qtd_pfp ' + 'from ' + TABLENAME + ' join tbagentes on tbagentes.cod_agente = tbentregas.cod_agente ' + 'join tbbancos on tbbancos.cod_banco = tbagentes.cod_banco '; if aParam[4] = True then begin sSQL := sSQL + 'where tbentregas.dat_baixa <= :data2 and '; end else begin sSQL := sSQL + 'where tbentregas.dat_baixa between :data1 and :data2 and '; end; sSQL := sSQL + 'tbentregas.dom_baixado = :dom and dom_fechado <> :fechado and ' + 'tbagentes.des_forma_pagamento <> "NENHUMA"'; if aParam[2] <> 0 then begin sSQL := sSQL + ' and cod_cliente_empresa = :cliente '; end; sSQL := sSQL + 'group by tbentregas.cod_agente;'; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Text := sSQL; FDQuery.ParamByName('data1').Value := FloatToDateTime(aParam[0]); FDQuery.ParamByName('data2').Value := FloatToDateTime(aParam[1]); FDQuery.ParamByName('fechado').Value := 'S'; if aParam[2] <> 0 then begin FDQuery.ParamByName('cliente').Value := FloatToDateTime(aParam[2]); end; FDQuery.ParamByName('dom').Value := 'S'; FDQuery.Open(); Result := FDQuery; end; function TEntregasDAO.ExtratoEntregador(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; sSQL: String; begin sSQL := 'select tbentregas.cod_entregador as cod_expressa, sum(tbentregas.qtd_volumes) as qtd_volumes, ' + 'count(tbentregas.num_nossonumero) as qtd_entregas, ' + 'sum(tbentregas.val_verba_entregador) as val_producao, '; if aParam[3] = True then begin sSQL := sSQL + '(sum(tbentregas.qtd_volumes) - sum(if(tbentregas.qtd_peso_cobrado <= 25 , 1 , 0))) / 2 as qtd_volumes_extra, '; sSQL := sSQL + '((sum(tbentregas.qtd_volumes) - sum(if(tbentregas.qtd_peso_cobrado <= 25 , 1 , 0))) / 2) * ' + '(if(tbentregas.qtd_peso_cobrado <= 25 , tbentregas.val_verba_entregador , 0)) as val_volume_extra, '; end else begin sSQL := sSQL + ' 0 as qtd_volumes_extra, '; sSQL := sSQL + ' 0 as val_volumes_extra, '; end; sSQL := sSQL + 'sum(if(tbentregas.qtd_dias_atraso > 0,1,0)) as qtd_atraso, ' + '(100 - ((sum(if(tbentregas.qtd_dias_atraso > 0,1,0)) / count(tbentregas.num_nossonumero))) * 100) as val_performance, ' + 'sum(tbentregas.val_verba_franquia) as val_total_ticket, ' + '0 as val_ticket_medio, ' + 'if(tbagentes.des_forma_pagamento = "NENHUMA",2,0) as cod_tipo_expressa, ' + 'tbcodigosentregadores.nom_fantasia as nom_expressa, ' + 'tbbancos.nom_banco as nom_banco, ' + 'tbentregadores.des_tipo_conta as des_tipo_conta, ' + 'tbentregadores.cod_agencia as num_agencia, ' + 'tbentregadores.num_conta as num_conta, ' + 'tbentregadores.nom_favorecido as nom_favorecido, ' + 'tbentregadores.num_cpf_cnpj_favorecido as num_cpf_cnpj, ' + 'sum(if(tbentregas.qtd_peso_cobrado > 25,1,0)) as qtd_pfp ' + 'from ' + TABLENAME + ' join tbagentes on tbagentes.cod_agente = tbentregas.cod_agente ' + 'join tbcodigosentregadores on tbcodigosentregadores.cod_entregador = tbentregas.cod_entregador ' + 'join tbentregadores on tbentregadores.cod_cadastro = tbcodigosentregadores.cod_cadastro ' + 'left join tbbancos on tbbancos.cod_banco = tbentregadores.cod_banco '; if aParam[4] = True then begin sSQL := sSQL + 'where tbentregas.dat_baixa <= :data2 and '; end else begin sSQL := sSQL + 'where tbentregas.dat_baixa between :data1 and :data2 and '; end; sSQL := sSQL + 'tbentregas.dom_baixado = :dom and dom_fechado <> :fechado and ' + 'tbagentes.des_forma_pagamento = "NENHUMA"'; if aParam[2] <> 0 then begin sSQL := sSQL + ' and tbentregas.cod_cliente_empresa = :cliente '; end; sSQL := sSQL + 'group by tbentregas.cod_entregador;'; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Text := sSQL; FDQuery.ParamByName('data1').Value := FloatToDateTime(aParam[0]); FDQuery.ParamByName('data2').Value := FloatToDateTime(aParam[1]); FDQuery.ParamByName('fechado').Value := 'S'; if aParam[2] <> 0 then begin FDQuery.ParamByName('cliente').Value := FloatToDateTime(aParam[2]); end; FDQuery.ParamByName('dom').Value := 'S'; FDQuery.Open(); Result := FDQuery; end; function TEntregasDAO.FindEntrega(aParam: array of Variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) = 0 then begin Exit; end; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT NUM_NOSSONUMERO, COD_AGENTE, COD_ENTREGADOR, COD_CLIENTE, NUM_NF, NOM_CONSUMIDOR, DES_ENDERECO, ' + 'DES_COMPLEMENTO, DES_BAIRRO, NOM_CIDADE, NUM_CEP, NUM_TELEFONE, DAT_EXPEDICAO, DAT_PREV_DISTRIBUICAO, QTD_VOLUMES, ' + 'DAT_ATRIBUICAO, DAT_BAIXA, DOM_BAIXADO, DAT_PAGAMENTO, DOM_PAGO, DOM_FECHADO, COD_STATUS, DAT_ENTREGA, QTD_PESO_REAL,'+ 'QTD_PESO_FRANQUIA, VAL_VERBA_FRANQUIA, VAL_ADVALOREM, VAL_PAGO_FRANQUIA, VAL_VERBA_ENTREGADOR, NUM_EXTRATO, ' + 'QTD_DIAS_ATRASO, QTD_VOLUMES_EXTRA, VAL_VOLUMES_EXTRA, QTD_PESO_COBRADO, DES_TIPO_PESO, DAT_RECEBIDO, DOM_RECEBIDO, ' + 'NUM_CTRC, NUM_MANIFESTO, DES_RASTREIO, NUM_LOTE_REMESSA, DES_RETORNO, DAT_CREDITO, DOM_CREDITO, NUM_CONTAINER, ' + 'VAL_PRODUTO, QTD_ALTURA, QTD_LARGURA, QTD_COMPRIMENTO, COD_FEEDBACK, DAT_FEEDBACK, DOM_CONFERIDO, NUM_PEDIDO, ' + 'COD_CLIENTE_EMPRESA FROM ' + TABLENAME); if aParam[0] = 'NN' then begin FDQuery.SQL.Add('WHERE NUM_NOSSONUMERO = :NN'); FDQuery.ParamByName('NN').AsString := aParam[1]; end; if aParam[0] = 'DISTRIBUIDOR' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :AGENTE'); FDQuery.ParamByName('AGENTE').AsInteger := aParam[1]; end; if aParam[0] = 'ENTREGADOR' then begin FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); FDQuery.ParamByName('ENTREGADOR').AsInteger := aParam[1]; end; if aParam[0] = 'CONTAINER' then begin FDQuery.SQL.Add('WHERE NUM_CONTAINER = :CONTAINER'); FDQuery.ParamByName('CONTAINER').AsString := aParam[1]; end; if aParam[0] = 'EXPEDICAO' then begin FDQuery.SQL.Add('WHERE DAT_EXPEDICAO BETWEEN :EXPEDICAO AND :EXPEDICAO1'); FDQuery.ParamByName('EXPEDICAO').AsDate := aParam[1]; FDQuery.ParamByName('EXPEDICAO1').AsDate := aParam[2]; end; if aParam[0] = 'ATRIBUICAO' then begin FDQuery.SQL.Add('WHERE DAT_ATRIBUICAO BETWEEN :ATRIBUICAO AND :ATRIBUICAO1'); FDQuery.ParamByName('ATRIBUICAO').AsDate := aParam[1]; FDQuery.ParamByName('ATRIBUICAO1').AsDate := aParam[2]; end; if aParam[0] = 'BAIXA' then begin FDQuery.SQL.Add('WHERE DAT_BAIXA BETWEEN :BAIXA AND :BAIXA1'); FDQuery.ParamByName('BAIXA').AsDate := aParam[1]; FDQuery.ParamByName('BAIXA1').AsDate := aParam[2]; end; if aParam[0] = 'ENTREGA' then begin FDQuery.SQL.Add('WHERE DAT_ENTREGA BETWEEN :ENTREGA AND :ENTREGA1'); FDQuery.ParamByName('ENTREGA').AsDate := aParam[1]; FDQuery.ParamByName('ENTREGA').AsDate := aParam[2]; end; if aParam[0] = 'VENCIMENTO' then begin FDQuery.SQL.Add('WHERE DAT_PREV_DISTRIBUICAO BETWEEN :PREVISAO AND :PREVISAO1'); FDQuery.ParamByName('PREVISAO').AsDate := aParam[1]; FDQuery.ParamByName('PREVISAO1').AsDate := aParam[2]; end; if aParam[0] = 'EXTRATO' then begin FDQuery.SQL.Add('WHERE NUM_EXTRATO = :EXTRATO'); FDQuery.ParamByName('EXTRATO').AsString := aParam[1]; end; if aParam[0] = 'CLIENTE' then begin FDQuery.SQL.Add('WHERE COD_CLIENTE = :CLIENTE'); FDQuery.ParamByName('CLIENTE').AsInteger := aParam[1]; end; if aParam[0] = 'NF' then begin FDQuery.SQL.Add('WHERE NUM_NF = :NF'); FDQuery.ParamByName('NF').AsString := aParam[1]; end; if aParam[0] = 'PEDIDO' then begin FDQuery.SQL.Add('WHERE NUM_PEDIDO = :PEDIDO'); FDQuery.ParamByName('PEDIDO').AsString := aParam[1]; end; if aParam[0] = 'CTRC' then begin FDQuery.SQL.Add('WHERE NUM_CTRC = :CTRC'); FDQuery.ParamByName('CTRC').AsInteger := aParam[1]; end; if aParam[0] = 'MANIFESTO' then begin FDQuery.SQL.Add('WHERE NUM_MANIFESTO = :MANIFESTO'); FDQuery.ParamByName('MANIFESTO').AsInteger := aParam[1]; end; if aParam[0] = 'CONSUMIDOR' then begin FDQuery.SQL.Add('WHERE NOM_CONSUMIDOR LIKE :CONSUMIDOR'); FDQuery.ParamByName('CONSUMIDOR').AsString := aParam[1]; end; if aParam[0] = 'CEP' then begin FDQuery.SQL.Add('WHERE NUM_CEP = :CEP'); FDQuery.ParamByName('CEP').AsString := aParam[1]; end; if aParam[0] = 'LOTE' then begin FDQuery.SQL.Add('WHERE NUM_LOTE_REMESSA = :LOTE'); FDQuery.ParamByName('LOTE').AsInteger := aParam[1]; end; if aParam[0] = 'CODFEEDBACK' then begin FDQuery.SQL.Add('WHERE COD_FEEDBACK = :CODIGO'); FDQuery.ParamByName('CODIGO').AsInteger := aParam[1]; end; if aParam[0] = 'DATFEEDBACK' then begin FDQuery.SQL.Add('WHERE DAT_FEEDBACK = :DATA'); FDQuery.ParamByName('DATA').AsDateTime := aParam[1]; end; if aParam[0] = 'MOVFEEDBACK' then begin FDQuery.SQL.Add('WHERE COD_FEEDBACK = :CODIGO AND DAT_FEEDBACK = :DATA'); FDQuery.ParamByName('CODIGO').AsInteger := aParam[1]; FDQuery.ParamByName('DATA').AsDateTime := aParam[2]; end; if aParam[0] = 'LOTFEEDBACK' then begin FDQuery.SQL.Add('WHERE NUM_LOTE_REMESSA = :LOTE AND COD_FEEDBACK = :CODIGO'); FDQuery.ParamByName('LOTE').AsInteger := aParam[1]; FDQuery.ParamByName('CODIGO').AsInteger := aParam[2]; end; if aParam[0] = 'FECHAMENTO' then begin FDQuery.SQL.Add('WHERE DAT_BAIXA BETWEEN :DATA AND :DATA1 AND DOM_BAIXADO = :BAIXADO'); FDQuery.ParamByName('DATA').AsDateTime := aParam[1]; FDQuery.ParamByName('DATA1').AsDateTime := aParam[2]; FDQuery.ParamByName('BAIXADO').AsString := aParam[3]; end; if aParam[0] = 'PREVIAPEDIDOS' then begin FDQuery.SQL.Add('WHERE DAT_BAIXA BETWEEN :DATA AND :DATA1 AND COD_ENTREGADOR = :ENTREGADOR'); FDQuery.ParamByName('DATA').AsDateTime := aParam[1]; FDQuery.ParamByName('DATA1').AsDateTime := aParam[2]; FDQuery.ParamByName('ENTREGADOR').AsString := aParam[3]; end; if aParam[0] = 'PREVIAPFP' then begin FDQuery.SQL.Add('WHERE DAT_BAIXA BETWEEN :DATA AND :DATA1 AND COD_ENTREGADOR = :ENTREGADOR AND QTD_PESO_COBRADO > 25'); FDQuery.ParamByName('DATA').AsDateTime := aParam[1]; FDQuery.ParamByName('DATA1').AsDateTime := aParam[2]; FDQuery.ParamByName('ENTREGADOR').AsString := aParam[3]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add(aParam[1]); end; FDQuery.Open(); Result := FDQuery; end; function TEntregasDAO.ForaPadrao(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; begin FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Add('select distinct(cod_entregador) as Entregador, count(num_nossonumero) as Entregas, val_verba_entregador, sum(val_verba_entregador) as Verba from ' + TABLENAME); FDQuery.SQL.Add('where dat_baixa between :data1 and :data2 and cod_agente = :agente and qtd_peso_cobrado > 25 and dom_baixado = :baixado group by cod_entregador'); FDQuery.ParamByName('data1').Value := FloatToDateTime(aParam[0]); FDQuery.ParamByName('data2').Value := FloatToDateTime(aParam[1]); FDQuery.ParamByName('agente').Value := aParam[2]; FDQuery.ParamByName('baixado').Value := aParam[3]; FDQuery.Open(); Result := FDQuery; end; end.
unit Thread.CapaDIRECT; interface uses System.Classes, Control.Bases, Control.EntregadoresExpressas, Control.Entregas, Control.VerbasExpressas, Control.CapaDIRECT, System.SysUtils, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type Thread_CapaDirect = class(TThread) private FPlanilha : TCapaDirectControl; FArquivo: String; FProcesso: Boolean; FLog: String; FTotalGravados: Integer; FTotalRegistros: Integer; FTotalInconsistencias: Integer; FProgresso: Double; FCliente: Integer; FCancelar: Boolean; FMemTab: TFDMemTable; procedure UpdateLOG(sMensagem: String); function RetornaVerba(aParam: array of variant): Double; { Private declarations } protected procedure Execute; override; public property Arquivo: String read FArquivo write FArquivo; property Processo: Boolean read FProcesso write FProcesso; property Log: String read FLog write FLog; property Progresso: Double read FProgresso write FProgresso; property TotalRegistros: Integer read FTotalRegistros write FTotalRegistros; property TotalGravados: Integer read FTotalGravados write FTotalGravados; property TotalInconsistencias: Integer read FTotalInconsistencias write FTotalInconsistencias; property Cliente: Integer read FCliente write FCliente; property Cancelar: Boolean read FCancelar write FCancelar; property MemTab: TFDMemTable read FMemTab write FMemTab; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_CapaDirect.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses Common.ENum; { Thread_CapaDirect } procedure Thread_CapaDirect.Execute; var aParam: Array of variant; iPos, i: Integer; dVerba: Double; sMensagem: String; FEntregas: TEntregasControl; FVerbas: TVerbasExpressasControl; FBases: TBasesControl; FEntregadores: TEntregadoresExpressasControl; begin { Place thread code here } try FProcesso := True; FCancelar := False; FPlanilha := TCapaDirectControl.Create; if FPLanilha.GetPlanilha(FArquivo) then begin iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FTotalGravados := 0; FTotalInconsistencias := 0; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin dVerba := 0; FEntregas := TEntregasControl.Create; SetLength(aParam,3); aParam := ['NNCLIENTE', FPlanilha.Planilha.Planilha[i].Remessa,FCliente]; if FEntregas.LocalizarExata(aParam) then begin if FEntregas.Entregas.Baixado <> 'S' then begin sMensagem := 'Entrega ainda não foi baixada;' + FPlanilha.Planilha.Planilha[i].Remessa + ';' + FEntregas.Entregas.PesoReal.ToString + ';' + FPlanilha.Planilha.Planilha[i].KGM3.ToString + ';' + FEntregas.Entregas.VerbaEntregador.ToString + ';' + FPlanilha.Planilha.Planilha[i].ValorPagar.ToString + ';' + FPlanilha.Planilha.Planilha[i].Motorista + ';' + FEntregas.Entregas.CEP; UpdateLOG(sMensagem); Inc(FTotalInconsistencias,1); dVerba := 0; end else begin if FEntregas.Entregas.Fechado <> 'S' then begin SetLength(aParam,8); aParam := [FEntregas.Entregas.Distribuidor, FEntregas.Entregas.Entregador, FEntregas.Entregas.CEP, FPlanilha.Planilha.Planilha[i].KGM3, FEntregas.Entregas.Baixa, 0, 0, FEntregas.Entregas.TipoPeso]; dVerba := RetornaVerba(aParam); if dVerba = 0 then begin sMensagem := 'Verba do entregador não foi localizada;' + FPlanilha.Planilha.Planilha[i].Remessa + ';' + FEntregas.Entregas.PesoReal.ToString + ';' + FPlanilha.Planilha.Planilha[i].KGM3.ToString + ';' + FEntregas.Entregas.VerbaEntregador.ToString + ';' + FPlanilha.Planilha.Planilha[i].ValorPagar.ToString + ';' + FPlanilha.Planilha.Planilha[i].Motorista + ';' + FEntregas.Entregas.CEP; UpdateLOG(sMensagem); Inc(FTotalInconsistencias,1); end end else begin dVerba := FEntregas.Entregas.VerbaEntregador; end; end; if FPlanilha.Planilha.Planilha[i].KGM3 <> FEntregas.Entregas.PesoReal then begin sMensagem := 'Peso da baixa DIFERENTE do peso da capa;' + FPlanilha.Planilha.Planilha[i].Remessa + ';' + FEntregas.Entregas.PesoReal.ToString + ';' + FPlanilha.Planilha.Planilha[i].KGM3.ToString + ';' + FEntregas.Entregas.VerbaEntregador.ToString + ';' + FPlanilha.Planilha.Planilha[i].ValorPagar.ToString + ';' + FPlanilha.Planilha.Planilha[i].Motorista + ';' + FEntregas.Entregas.CEP; UpdateLOG(sMensagem); Inc(FTotalInconsistencias,1); end; FEntregas.Entregas.PesoCobrado := FPlanilha.Planilha.Planilha[i].KGM3; FEntregas.Entregas.VerbaEntregador := dVerba; FEntregas.Entregas.VerbaFranquia := FPlanilha.Planilha.Planilha[i].ValorPagar; FEntregas.Entregas.Endereco := FPlanilha.Planilha.Planilha[i].EnderecoEntrega; FEntregas.Entregas.Conferido := 1; FEntregas.Entregas.Acao := tacAlterar; if not Fentregas.Gravar() then begin sMensagem := 'Erro ao gravar;' + FPlanilha.Planilha.Planilha[i].Remessa + ';' + FEntregas.Entregas.PesoReal.ToString + ';' + FPlanilha.Planilha.Planilha[i].KGM3.ToString + ';' + FEntregas.Entregas.VerbaEntregador.ToString + ';' + FEntregas.Entregas.VerbaFranquia.ToString + ';' + FPlanilha.Planilha.Planilha[i].Motorista + ';' + FEntregas.Entregas.CEP; UpdateLOG(sMensagem); Inc(FTotalInconsistencias,1); end else begin Inc(FTotalGravados,1); end; end else begin sMensagem := 'Remessa NÃO ENCONTRADA;' + FPlanilha.Planilha.Planilha[i].Remessa + ';0,0;' + FPlanilha.Planilha.Planilha[i].KGM3.ToString + ';0,00;0,00;' + FPlanilha.Planilha.Planilha[i].Motorista + ';' + FPlanilha.Planilha.Planilha[i].CEPEntrega; Inc(FTotalInconsistencias,1); UpdateLOG(sMensagem); end; FEntregas.Free; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; end else begin UpdateLOG(FPlanilha.Planilha.Mensagem); end; Except on E: Exception do begin sMensagem := '** ERROR **' + 'Classe:' + E.ClassName + chr(13) + 'Mensagem:' + E.Message; UpdateLOG(sMensagem); FProcesso := False; end; end; end; function Thread_CapaDirect.RetornaVerba(aParam: array of variant): Double; var FBase: TBasesControl; FEntregador: TEntregadoresExpressasControl; FVerbas: TVerbasExpressasControl; iTabela, iFaixa: Integer; dVerba, dVerbaEntregador: Double; FParam: array of variant; FTipoVerba: array of string; begin Result := 0; iTabela := 0; iFaixa := 0; dVerba := 0; dVerbaEntregador := 0; SetLength(FTipoVerba,8); // procura dos dados da base referentes à verba FBase := TBasesControl.Create; SetLength(FParam,2); FParam := ['CODIGO',aParam[0]]; if FBase.LocalizarExato(FParam) then begin iTabela := FBase.Bases.Tabela; iFaixa := FBase.Bases.Grupo; dVerba := FBase.Bases.ValorVerba; end; Finalize(FParam); FBase.Free; // se a base não possui uma verba fixa, verifica se a base possui uma vinculação a uma // tabela e faixa. if dVerba = 0 then begin if iTabela <> 0 then begin if iFaixa <> 0 then begin FVerbas := TVerbasExpressasControl.Create; FVerbas.Verbas.Tipo := iTabela; FVerbas.Verbas.Cliente := FCliente; FVerbas.Verbas.Grupo := iFaixa; FVerbas.Verbas.Vigencia := aParam[4]; FVerbas.Verbas.CepInicial := aParam[2]; FVerbas.Verbas.PesoInicial := aParam[3]; FVerbas.Verbas.Roteiro := aParam[5]; FVerbas.Verbas.Performance := aParam[6]; dVerba := FVerbas.RetornaVerba(); FVerbas.Free; end; end; end; // pesquisa a tabela de entregadores e apanha os dados referente à verba FEntregador := TEntregadoresExpressasControl.Create; SetLength(FParam,2); FParam := ['ENTREGADOR', aParam[1]]; if not Fentregador.Localizar(FParam).IsEmpty then begin iTabela := FEntregador.Entregadores.Tabela; iFaixa := FEntregador.Entregadores.Grupo; dVerbaEntregador := FEntregador.Entregadores.Verba; end; Finalize(FParam); FEntregador.Free; // verifica se o entregador possui uma verba fixa, se estiver zerada, verifica com as informações // de tabela e faixa. if dVerbaEntregador = 0 then begin if iTabela <> 0 then begin if iFaixa <> 0 then begin FVerbas := TVerbasExpressasControl.Create; FVerbas.Verbas.Tipo := iTabela; FVerbas.Verbas.Cliente := FCliente; FVerbas.Verbas.Grupo := iFaixa; FVerbas.Verbas.Vigencia := aParam[4]; FVerbas.Verbas.CepInicial := aParam[2]; FVerbas.Verbas.PesoInicial := aParam[3]; FVerbas.Verbas.Roteiro := aParam[5]; FVerbas.Verbas.Performance := aParam[6]; dVerbaEntregador := FVerbas.RetornaVerba(); FVerbas.Free; end; end; end; if dVerbaEntregador > 0 then begin dVerba := dVerbaEntregador; if UpperCase(aParam[7]) = 'LOJA' then begin dVerba := dVerbaEntregador / 2; end; end; Result := dVerba; end; procedure Thread_CapaDirect.UpdateLOG(sMensagem: String); var sDetalhe: TStringList; begin sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; sDetalhe.DelimitedText := sMensagem; if sDetalhe.Count = 8 then begin memTab.Insert; memTab.Fields[0].Value := sDetalhe[0]; memTab.Fields[1].Value := sDetalhe[1]; memTab.Fields[2].Value := StrToFloatDef(sDetalhe[2], 0); memTab.Fields[3].Value := StrToFloatDef(sDetalhe[3], 0); memTab.Fields[4].Value := StrToFloatDef(sDetalhe[4], 0); memTab.Fields[5].Value := StrToFloatDef(sDetalhe[5], 0); memTab.Fields[6].Value := sDetalhe[6]; memTab.Fields[7].Value := sDetalhe[7]; MemTab.Post; end else begin memTab.Insert; memTab.Fields[0].Value := sDetalhe[0]; MemTab.Post; end; end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPSysTray; interface uses Classes, QExtCtrls, uCommon, QControls, QStdCtrls, SysUtils, QGraphics; type TXPSysTray=class(TPanel) private separator: TPanel; client: TPanel; clock: TLabel; timer: TTimer; public procedure updatewidth; procedure SetParent(const Value: TWidgetControl); override; procedure setup; procedure updateclock(sender:TObject); constructor Create(AOwner:TComponent);override; destructor Destroy;override; end; implementation { TXPSysTray } constructor TXPSysTray.Create(AOwner: TComponent); begin inherited; setup; end; destructor TXPSysTray.Destroy; begin separator.free; clock.free; timer.free; client.free; inherited; end; procedure TXPSysTray.SetParent(const Value: TWidgetControl); begin inherited; { TODO : Colors must be taken from the theme } clock.Font.color:=clWhite; end; procedure TXPSysTray.setup; var dir: string; begin BevelOuter:=bvNone; dir:=getSystemInfo(XP_TASKBAR_DIR); { TODO : Allow add tray icons, configure width according to clock, icons and height } width:=100; //Just temp separator:=TPanel.create(nil); separator.bevelouter:=bvNone; separator.bitmap.loadfromfile(dir+'/taskbar_separator.png'); separator.width:=separator.Bitmap.Width; separator.align:=alLeft; separator.parent:=self; client:=TPanel.create(nil); client.BevelOuter:=bvNone; { TODO : This probably will be another background } client.bitmap.LoadFromFile(dir+'/taskbar_background_bottom.png'); client.align:=alClient; client.parent:=self; clock:=TLabel.create(nil); clock.align:=alRight; clock.transparent:=true; clock.autosize:=true; clock.Layout:=tlCenter; clock.parent:=client; updateclock(nil); timer:=TTimer.create(nil); timer.Interval:=20000; timer.OnTimer:=updateclock; updatewidth; end; procedure TXPSysTray.updateclock(sender:TObject); begin clock.Caption:=formatdatetime(' hh:nn ',now()); end; procedure TXPSysTray.updatewidth; begin width:=clock.width+separator.width; end; end.
unit afwPreviewPageSpy; {* Следилка за TafwPreviewPage, для [RequestLink:235873282] } // Модуль: "w:\common\components\gui\Garant\AFW\implementation\Visual\afwPreviewPageSpy.pas" // Стереотип: "SimpleClass" // Элемент модели: "TafwPreviewPageSpy" MUID: (4CB6DFDE0374) {$Include w:\common\components\gui\Garant\AFW\afwDefine.inc} interface {$If Defined(nsTest)} uses l3IntfUses , l3ProtoObject , afwPreviewPage ; type TafwPreviewPageSpy = class; IafwPagesLogger = interface ['{19361554-2DE2-4E58-B896-503677BDD13B}'] procedure LogPage(aPage: TafwPreviewPage; aCounter: Boolean); procedure IncCounterPageNumer; end;//IafwPagesLogger TafwPreviewPageSpy = class(Tl3ProtoObject) {* Следилка за TafwPreviewPage, для [RequestLink:235873282] } private f_Logger: IafwPagesLogger; protected procedure ClearFields; override; public class function Exists: Boolean; procedure SetLogger(const aLogger: IafwPagesLogger); procedure RemoveLogger(const aLogger: IafwPagesLogger); procedure LogPage(aPage: TafwPreviewPage; aCounter: Boolean); procedure IncCounterNumber; class function Instance: TafwPreviewPageSpy; {* Метод получения экземпляра синглетона TafwPreviewPageSpy } end;//TafwPreviewPageSpy {$IfEnd} // Defined(nsTest) implementation {$If Defined(nsTest)} uses l3ImplUses , SysUtils , l3Base //#UC START# *4CB6DFDE0374impl_uses* //#UC END# *4CB6DFDE0374impl_uses* ; var g_TafwPreviewPageSpy: TafwPreviewPageSpy = nil; {* Экземпляр синглетона TafwPreviewPageSpy } procedure TafwPreviewPageSpyFree; {* Метод освобождения экземпляра синглетона TafwPreviewPageSpy } begin l3Free(g_TafwPreviewPageSpy); end;//TafwPreviewPageSpyFree class function TafwPreviewPageSpy.Exists: Boolean; begin Result := g_TafwPreviewPageSpy <> nil; end;//TafwPreviewPageSpy.Exists procedure TafwPreviewPageSpy.SetLogger(const aLogger: IafwPagesLogger); //#UC START# *4CB6E54D0386_4CB6DFDE0374_var* //#UC END# *4CB6E54D0386_4CB6DFDE0374_var* begin //#UC START# *4CB6E54D0386_4CB6DFDE0374_impl* Assert(f_Logger = nil); f_Logger := aLogger; //#UC END# *4CB6E54D0386_4CB6DFDE0374_impl* end;//TafwPreviewPageSpy.SetLogger procedure TafwPreviewPageSpy.RemoveLogger(const aLogger: IafwPagesLogger); //#UC START# *4CB6E5690252_4CB6DFDE0374_var* //#UC END# *4CB6E5690252_4CB6DFDE0374_var* begin //#UC START# *4CB6E5690252_4CB6DFDE0374_impl* Assert(f_Logger = aLogger); f_Logger := nil; //#UC END# *4CB6E5690252_4CB6DFDE0374_impl* end;//TafwPreviewPageSpy.RemoveLogger procedure TafwPreviewPageSpy.LogPage(aPage: TafwPreviewPage; aCounter: Boolean); //#UC START# *4CB6E596010B_4CB6DFDE0374_var* //#UC END# *4CB6E596010B_4CB6DFDE0374_var* begin //#UC START# *4CB6E596010B_4CB6DFDE0374_impl* if (f_Logger <> nil) then f_Logger.LogPage(aPage, aCounter); //#UC END# *4CB6E596010B_4CB6DFDE0374_impl* end;//TafwPreviewPageSpy.LogPage procedure TafwPreviewPageSpy.IncCounterNumber; //#UC START# *51ADB624017D_4CB6DFDE0374_var* //#UC END# *51ADB624017D_4CB6DFDE0374_var* begin //#UC START# *51ADB624017D_4CB6DFDE0374_impl* if (f_Logger <> nil) then f_Logger.IncCounterPageNumer; //#UC END# *51ADB624017D_4CB6DFDE0374_impl* end;//TafwPreviewPageSpy.IncCounterNumber class function TafwPreviewPageSpy.Instance: TafwPreviewPageSpy; {* Метод получения экземпляра синглетона TafwPreviewPageSpy } begin if (g_TafwPreviewPageSpy = nil) then begin l3System.AddExitProc(TafwPreviewPageSpyFree); g_TafwPreviewPageSpy := Create; end; Result := g_TafwPreviewPageSpy; end;//TafwPreviewPageSpy.Instance procedure TafwPreviewPageSpy.ClearFields; begin f_Logger := nil; inherited; end;//TafwPreviewPageSpy.ClearFields {$IfEnd} // Defined(nsTest) end.
{**************************************************************************************************} { } { Project JEDI } { } { 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 MediaWikiUtils.pas } { } { The Initial Developer of the Original Code is Florent Ouchet. } { Portions created by Florent Ouchet are Copyright Florent Ouchet. All rights reserved. } { } { Contributor(s): } { } {**************************************************************************************************} unit MediaWikiUtils; interface uses SysUtils, Classes, Math, JclBase, JclSimpleXml; type EMediaWikiException = class(Exception) private FInfo: string; public constructor Create(const AInfo: string); procedure AfterConstruction; override; property Info: string read FInfo; end; EMediaWikiWarning = class(EMediaWikiException) private FQuery: string; public constructor Create(const AInfo, AQuery: string); procedure AfterConstruction; override; property Query: string read FQuery; end; EMediaWikiError = class(EMediaWikiException) private FCode: string; public constructor Create(const AInfo, ACode: string); procedure AfterConstruction; override; property Code: string read FCode; end; TMediaWikiID = Integer; type TMediaWikiXMLWarningCallback = procedure (const AInfo, AQuery: string) of object; TMediaWikiXMLErrorCallback = procedure (const AInfo, ACode: string) of object; procedure MediaWikiCheckXML(XML: TJclSimpleXML; WarningCallback: TMediaWikiXMLWarningCallback; ErrorCallback: TMediaWikiXMLErrorCallback); type TMediaWikiOutputFormat = (mwoJSON, // JSON format mwoPHP, // serialized PHP format mwoWDDX, // WDDX format mwoXML, // XML format mwoYAML, // YAML format mwoDebugJSON, // JSON format with the debugging elements (HTML) mwoText, // PHP print_r() format mwoDebug); // PHP var_export() format TMediaWikiLoginResult = (mwlNoName, // You didn't set the lgname parameter mwlIllegal, // You provided an illegal username mwlNotExists, // The username you provided doesn't exist mwlEmptyPass, // You didn't set the lgpassword parameter or you left it empty mwlWrongPass, // The password you provided is incorrect mwlWrongPluginPass, // Same as WrongPass, returned when an authentication plugin rather than MediaWiki itself rejected the password mwlCreateBlocked, // The wiki tried to automatically create a new account for you, but your IP address has been blocked from account creation mwlThrottled, // You've logged in too many times in a short time. See also throttling mwlBlocked, // User is blocked mwlMustBePosted, // The login module requires a POST request mwlNeedToken, // Either you did not provide the login token or the sessionid cookie. Request again with the token and cookie given in this response mwlSuccess); // Login success const MediaWikiOutputFormats: array [TMediaWikiOutputFormat] of string = ( 'json', // JSON format 'php', // serialized PHP format 'wddx', // WDDX format 'xml', // XML format 'yaml', // YAML format 'rawfm', // JSON format with the debugging elements (HTML) 'txt', // PHP print_r() format 'dbg' ); // PHP var_export() format MediaWikiLoginResults: array [TMediaWikiLoginResult] of string = ( 'NoName', // You didn't set the lgname parameter 'Illegal', // You provided an illegal username 'NotExists', // The username you provided doesn't exist 'EmptyPass', // You didn't set the lgpassword parameter or you left it empty 'WrongPass', // The password you provided is incorrect 'WrongPluginPass', // Same as WrongPass, returned when an authentication plugin rather than MediaWiki itself rejected the password 'CreateBlocked', // The wiki tried to automatically create a new account for you, but your IP address has been blocked from account creation 'Throttled', // You've logged in too many times in a short time. See also throttling 'Blocked', // User is blocked 'mustbeposted', // The login module requires a POST request 'NeedToken', // Either you did not provide the login token or the sessionid cookie. Request again with the token and cookie given in this response 'Success' ); // Login success function FindMediaWikiLoginResult(const AString: string): TMediaWikiLoginResult; function StrISO8601ToDateTime(const When: string): TDateTime; function DateTimeToStrISO8601(When: TDateTime): string; type TMediaWikiContinueInfo = record ParameterName: string; ParameterValue: string; end; // post stuff procedure MediaWikiQueryAdd(Queries: TStrings; const AName: string; const AValue: string = ''; RawValue: Boolean = False; Content: TStream = nil); overload; procedure MediaWikiQueryAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo); overload; procedure MediaWikiQueryPost(Queries: TStrings; ASendStream: TStream; out ContentType: string); // login stuff procedure MediaWikiQueryLoginAdd(Queries: TStrings; const lgName, lgPassword, lgToken: string; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryLoginParseXmlResult(XML: TJclSimpleXML; out LoginResult: TMediaWikiLoginResult; out LoginUserID: TMediaWikiID; out LoginUserName: string); // logout stuff procedure MediaWikiQueryLogoutAdd(Queries: TStrings; const token: string; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryLogoutParseXmlResult(XML: TJclSimpleXML); // query, site info general procedure MediaWikiQuerySiteInfoGeneralAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoGeneralParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info namespaces procedure MediaWikiQuerySiteInfoNamespacesAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoNamespacesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info, namespace aliases procedure MediaWikiQuerySiteInfoNamespaceAliasesAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoNamespaceAliasesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info, special page aliases procedure MediaWikiQuerySiteInfoSpecialPageAliasesAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoSpecialPageAliasesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info, magic words procedure MediaWikiQuerySiteInfoMagicWordsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoMagicWordsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info, statistics procedure MediaWikiQuerySiteInfoStatisticsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoStatisticsParseXmlResult(XML: TJclSimpleXML; Info: TStrings); // query, site info, inter wiki map procedure MediaWikiQuerySiteInfoInterWikiMapAdd(Queries: TStrings; Local: Boolean; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoInterWikiMapParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info , DB replication lag procedure MediaWikiQuerySiteInfoDBReplLagAdd(Queries: TStrings; ShowAllDB: Boolean; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoDBReplLagParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info, user groups procedure MediaWikiQuerySiteInfoUserGroupsAdd(Queries: TStrings; IncludeUserCount: Boolean; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoUserGroupsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, site info, extensions type TMediaWikiExtension = record ExtensionType: string; ExtensionName: string; ExtensionDescription: string; ExtensionDescriptionMsg: string; ExtensionAuthor: string; ExtensionVersion: string; end; TMediaWikiExtensions = array of TMediaWikiExtension; procedure MediaWikiQuerySiteInfoExtensionsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQuerySiteInfoExtensionsParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiExtensions); // query token stuff type TMediaWikiToken = (mwtCreateAccount, mwtCsrf, mwtDeleteGlobalAccount, mwtLogin, mwtPatrol, mwtRollback, mwtSetGlobalAccountStatus, mwtUserRights, mwtWatch); TMediaWikiTokens = set of TMediaWikiToken; TMediaWikiTokenValues = array [TMediaWikiToken] of string; const MediaWikiTokenNames: array [TMediaWikiToken] of string = ( 'createaccount', 'csrf', 'deleteglobalaccount', 'login', 'patrol', 'rollback', 'setglobalaccountstatus', 'userrights', 'watch' ); procedure MediaWikiQueryTokensAdd(Queries: TStrings; Tokens: TMediaWikiTokens; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryTokensParseXmlResult(XML: TJclSimpleXML; out TokenValues: TMediaWikiTokenValues); // query, user info, block info procedure MediaWikiQueryUserInfoBlockInfoAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoBlockInfoParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, user info, has msg procedure MediaWikiQueryUserInfoHasMsgAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoHasMsgParseXmlResult(XML: TJclSimpleXML; out HasMessage: Boolean); // query, user info, groups procedure MediaWikiQueryUserInfoGroupsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoGroupsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); //query, user info, rights procedure MediaWikiQueryUserInfoRightsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoRightsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, user info, changeable groups procedure MediaWikiQueryUserInfoChangeableGroupsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoChangeableGroupsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, user info, options procedure MediaWikiQueryUserInfoOptionsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoOptionsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, user info, edit count procedure MediaWikiQueryUserInfoEditCountAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoEditCountParseXmlResult(XML: TJclSimpleXML; out EditCount: Integer); // query, user info, rate limits type TMediaWikiRateLimit = record RateLimitAction: string; RateLimitGroup: string; RateLimitHits: Integer; RateLimitSeconds: Integer; end; TMediaWikiRateLimits = array of TMediaWikiRateLimit; procedure MediaWikiQueryUserInfoRateLimitsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryUserInfoRateLimitsParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiRateLimits); // query, messages procedure MediaWikiQueryMessagesAdd(Queries: TStrings; const NameFilter, ContentFilter, Lang: string; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryMessagesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); // query, page info type TMediaWikiPageBasics = record PageID: TMediaWikiID; PageNamespace: Integer; PageTitle: string; end; TMediaWikiPageProtection = record PageProtectionAction: string; PageProtectionGroup: string; PageProtectionExpiry: string; end; TMediaWikiPageProtections = array of TMediaWikiPageProtection; TMediaWikiPageFlag = (mwfPageIsNew, mwfPageIsRedirect); TMediaWikiPageFlags = set of TMediaWikiPageFlag; TMediaWikiPageInfo = record PageBasics: TMediaWikiPageBasics; PageLastTouched: TDateTime; PageRevisionID: TMediaWikiID; PageViews: Integer; PageSize: Integer; PageFlags: TMediaWikiPageFlags; PageProtections: TMediaWikiPageProtections; // on request, use mwfIncludeProtection PageTalkID: TMediaWikiID; // on request, use mwfIncludeTalkID PageSubjectID: TMediaWikiID; // on request, mwfIncludeSubjectID PageFullURL: string; // on request, mwfIncludeURL PageEditURL: string; // on request, mwfIncludeURL end; TMediaWikiPageInfos = array of TMediaWikiPageInfo; TMediaWikiPageInfoFlag = (mwfIncludeProtection, mwfIncludeTalkID, mwfIncludeSubjectID, mwfIncludeURL); TMediaWikiPageInfoFlags = set of TMediaWikiPageInfoFlag; procedure MediaWikiQueryPageInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryPageInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageInfos); // query, page info, revision info type TMediaWikiPageRevisionFlag = (mwfMinorEdit); TMediaWikiPageRevisionFlags = set of TMediaWikiPageRevisionFlag; TMediaWikiPageRevisionInfo = record PageRevisionInfoPageBasics: TMediaWikiPageBasics; PageRevisionInfoID: TMediaWikiID; PageRevisionInfoFlags: TMediaWikiPageRevisionFlags; PageRevisionInfoDateTime: TDateTime; PageRevisionInfoAuthor: string; PageRevisionInfoComment: string; PageRevisionInfoSize: Integer; PageRevisionInfoContent: string; // TODO RevisionTags: string; PageRevisionInfoRollbackToken: string; end; TMediaWikiPageRevisionInfos = array of TMediaWikiPageRevisionInfo; TMediaWikiPageRevisionInfoFlag = (mwfIncludeRevisionID, mwfIncludeRevisionFlags, mwfIncludeRevisionTimeStamp, mwfIncludeRevisionAuthor, mwfIncludeRevisionComment, mwfIncludeRevisionSize, mwfIncludeRevisionContent, mwfIncludeRevisionRollbackToken, mwfRevisionReverseOrder, mwfRevisionContentXml, mwfRevisionContentExpandTemplates, mwfRevisionContinue); TMediaWikiPageRevisionInfoFlags = set of TMediaWikiPageRevisionInfoFlag; procedure MediaWikiQueryPageRevisionInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxRevisions, Section: Integer; StartRevisionID, EndRevisionID: TMediaWikiID; const StartDateTime, EndDateTime: TDateTime; const IncludeUser, ExcludeUser: string; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryPageRevisionInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageRevisionInfos; out ContinueInfo: TMediaWikiContinueInfo); // query, page info, category info type TMediaWikiPageCategoryInfo = record CategoryPageBasics: TMediaWikiPageBasics; CategoryTitle: string; CategoryNameSpace: Integer; CategoryTimeStamp: TDateTime; // on request CategorySortKey: string; // on request end; TMediaWikiPageCategoryInfos = array of TMediaWikiPageCategoryInfo; TMediaWikiPageCategoryInfoFlag = (mwfIncludeCategorySortKey, mwfIncludeCategoryTimeStamp, mwfCategoryHidden); TMediaWikiPageCategoryInfoFlags = set of TMediaWikiPageCategoryInfoFlag; procedure MediaWikiQueryPageCategoryInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer; const CategoryTitles: string; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryPageCategoryInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageCategoryInfos; out ContinueInfo: TMediaWikiContinueInfo); // query, page info, link info type TMediaWikiPageLinkInfo = record LinkSourceBasics: TMediaWikiPageBasics; LinkTargetTitle: string; LinkTargetNameSpace: Integer; end; TMediaWikiPageLinkInfos = array of TMediaWikiPageLinkInfo; procedure MediaWikiQueryPageLinkInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks, Namespace: Integer; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryPageLinkInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); // query, page info, template info type TMediaWikiPageTemplateInfo = record TemplatePageBasics: TMediaWikiPageBasics; TemplateTitle: string; TemplateNameSpace: Integer; end; TMediaWikiPageTemplateInfos = array of TMediaWikiPageTemplateInfo; procedure MediaWikiQueryPageTemplateInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxTemplates, Namespace: Integer; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryPageTemplateInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageTemplateInfos; out ContinueInfo: TMediaWikiContinueInfo); // query, page info, ext links type TMediaWikiPageExtLinkInfo = record ExtLinkPageBasics: TMediaWikiPageBasics; ExtLinkTarget: string; end; TMediaWikiPageExtLinkInfos = array of TMediaWikiPageExtLinkInfo; procedure MediaWikiQueryPageExtLinkInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryPageExtLinkInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageExtLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); // query, list, all pages type TMediaWikiAllPageInfos = array of TMediaWikiPageBasics; TMediaWikiAllPageFilterRedir = (mwfAllPageFilterAll, mwfAllPageFilterRedirect, mwfAllPageFilterNonRedirect); TMediaWikiAllPageFilterLang = (mwfAllPageLangAll, mwfAllPageLangOnly, mwfAllPageLangNone); TMediaWikiAllPageFilterProtection = (mwfAllPageProtectionNone, mwfAllPageProtectionEdit, mwfAllPageProtectionMove); TMediaWikiAllPageFilterLevel = (mwfAllPageLevelNone, mwfAllPageLevelAutoConfirmed, mwfAllPageLevelSysops); TMediaWikiAllPageDirection = (mwfAllPageAscending, mwfAllPageDescending); procedure MediaWikiQueryAllPageAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxPage: Integer; Namespace: Integer; RedirFilter: TMediaWikiAllPageFilterRedir; LangFilter: TMediaWikiAllPageFilterLang; MinSize, MaxSize: Integer; ProtectionFilter: TMediaWikiAllPageFilterProtection; LevelFilter: TMediaWikiAllPageFilterLevel; Direction: TMediaWikiAllPageDirection; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryAllPageParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiAllPageInfos; out ContinueInfo: TMediaWikiContinueInfo); // query, list, alllinks: Returns a list of (unique) links to pages in a given namespace starting ordered by link title. type TMediaWikiAllLinkInfo = record LinkTitle: string; PageID: TMediaWikiID; LinkNamespace: Integer; end; TMediaWikiAllLinkInfos = array of TMediaWikiAllLinkInfo; TMediaWikiAllLinkInfoFlag = (mwfLinkUnique, mwfLinkIncludePageID); TMediaWikiAllLinkInfoFlags = set of TMediaWikiAllLinkInfoFlag; procedure MediaWikiQueryAllLinkAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxLink: Integer; Namespace: Integer; Flags: TMediaWikiAllLinkInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryAllLinkParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiAllLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); type TMediaWikiAllCategoryInfoFlag = (mwfCategoryDescending); TMediaWikiAllCategoryInfoFlags = set of TMediaWikiAllCategoryInfoFlag; procedure MediaWikiQueryAllCategoryAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxCategory: Integer; Flags: TMediaWikiAllCategoryInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryAllCategoryParseXmlResult(XML: TJclSimpleXML; Infos: TStrings; out ContinueInfo: TMediaWikiContinueInfo); type TMediaWikiAllUserInfo = record UserName: string; UserGroups: TDynStringArray; UserEditCount: Integer; UserRegistration: TDateTime; end; TMediaWikiAllUserInfos = array of TMediaWikiAllUserInfo; TMediaWikiAllUserInfoFlag = (mwfIncludeUserEditCount, mwfIncludeUserGroups, mwfIncludeUserRegistration); TMediaWikiAllUserInfoFlags = set of TMediaWikiAllUserInfoFlag; procedure MediaWikiQueryAllUserAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix, Group: string; MaxUser: Integer; Flags: TMediaWikiAllUserInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryAllUserParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiAllUserInfos; out ContinueInfo: TMediaWikiContinueInfo); type TMediaWikiBackLinkFlag = (mwfBackLinkIsRedirect, // BackLinkPageID is redirected to BackLinkTitle mwfBackLinkToRedirect); // BackLinkFromPageID links to BackLinkPageID which is redirected to BackLinkTitle TMediaWikiBackLinkFlags = set of TMediaWikiBackLinkFlag; TMediaWikiBackLinkInfo = record BackLinkPageBasics: TMediaWikiPageBasics; BackLinkFlags: TMediaWikiBackLinkFlags; BackLinkRedirFromPageBasics: TMediaWikiPageBasics; end; TMediaWikiBackLinkInfos = array of TMediaWikiBackLinkInfo; TMediaWikiBackLinkInfoFlag = (mwfExcludeBackLinkRedirect, mwfExcludeBackLinkNonRedirect, mwfIncludeBackLinksFromRedirect); TMediaWikiBackLinkInfoFlags = set of TMediaWikiBackLinkInfoFlag; procedure MediaWikiQueryBackLinkAdd(Queries: TStrings; const BackLinkTitle: string; const ContinueInfo: TMediaWikiContinueInfo; Namespace, MaxLink: Integer; Flags: TMediaWikiBackLinkInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryBackLinkParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiBackLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); type TMediaWikiBlockFlag = (mwfBlockAutomatic, mwfBlockAnonymousEdits, mwfBlockNoAccountCreate, mwfBlockAutomaticBlocking, mwfBlockNoEmail, mwfBlockHidden); TMediaWikiBlockFlags = set of TMediaWikiBlockFlag; TMediaWikiBlockInfo = record BlockID: TMediaWikiID; BlockUser: string; BlockUserID: TMediaWikiID; BlockByUser: string; BlockByUserID: TMediaWikiID; BlockDateTime: TDateTime; BlockExpirityDateTime: TDateTime; BlockReason: string; BlockIPRangeStart: string; BlockIPRangeStop: string; BlockFlags: TMediaWikiBlockFlags; end; TMediaWikiBlockInfos = array of TMediaWikiBlockInfo; TMediaWikiBlockInfoFlag = (mwfBlockID, mwfBlockUser, mwfBlockByUser, mwfBlockDateTime, mwfBlockExpiry, mwfBlockReason, mwfBlockIPRange, mwfBlockFlags, mwfBlockDescending); TMediaWikiBlockInfoFlags = set of TMediaWikiBlockInfoFlag; procedure MediaWikiQueryBlockAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const StartDateTime, StopDateTime: TDateTime; const BlockIDs, Users, IP: string; MaxBlock: Integer; Flags: TMediaWikiBlockInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryBlockParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiBlockInfos; out ContinueInfo: TMediaWikiContinueInfo); type TMediaWikiCategoryMemberInfo = record CategoryMemberPageBasics: TMediaWikiPageBasics; CategoryMemberDateTime: TDateTime; CategoryMemberSortKey: string; end; TMediaWikiCategoryMemberInfos = array of TMediaWikiCategoryMemberInfo; TMediaWikiCategoryMemberInfoFlag = (mwfCategoryMemberPageID, mwfCategoryMemberPageTitle, mwfCategoryMemberPageDateTime, mwfCategoryMemberPageSortKey, mwfCategoryMemberDescending); TMediaWikiCategoryMemberInfoFlags = set of TMediaWikiCategoryMemberInfoFlag; procedure MediaWikiQueryCategoryMemberAdd(Queries: TStrings; const CategoryTitle: string; const ContinueInfo: TMediaWikiContinueInfo; PageNamespace: Integer; const StartDateTime, StopDateTime: TDateTime; const StartSortKey, StopSortKey: string; MaxCategoryMember: Integer; Flags: TMediaWikiCategoryMemberInfoFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiQueryCategoryMemberParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiCategoryMemberInfos; out ContinueInfo: TMediaWikiContinueInfo); type TMediaWikiEditFlag = (mwfEditMinor, mwfEditNotMinor, mwfEditBot, mwfEditAlwaysRecreate, mwfEditMustCreate, mwfEditMustExist, mwfEditWatchAdd, mwfEditWatchRemove, mwfEditWatchNoChange, mwfEditUndoAfterRev); TMediaWikiEditFlags = set of TMediaWikiEditFlag; TMediaWikiEditInfo = record EditSuccess: Boolean; EditPageTitle: string; EditPageID: TMediaWikiID; EditOldRevID: TMediaWikiID; EditNewRevID: TMediaWikiID; EditCaptchaType: string; EditCaptchaURL: string; EditCaptchaMime: string; EditCaptchaID: string; EditCaptchaQuestion: string; end; procedure MediaWikiEditAdd(Queries: TStrings; const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary, MD5, CaptchaID, CaptchaWord: string; const BaseDateTime, StartDateTime: TDateTime; UndoRevisionID: TMediaWikiID; Flags: TMediaWikiEditFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiEditParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiEditInfo); type TMediaWikiMoveFlag = (mwfMoveTalk, mwfMoveSubPages, mwfMoveNoRedirect, mwfMoveAddToWatch, mwfMoveNoWatch); TMediaWikiMoveFlags = set of TMediaWikiMoveFlag; TMediaWikiMoveInfo = record MoveSuccess: Boolean; MoveFromPage: string; MoveToPage: string; MoveReason: string; MoveFromTalk: string; MoveToTalk: string; end; procedure MediaWikiMoveAdd(Queries: TStrings; const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiMoveParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiMoveInfo); // DeleteRevision requires some modifications in the MediaWiki API running in the server type TMediaWikiDeleteInfo = record DeleteSuccess: Boolean; DeletePage: string; DeleteReason: string; end; procedure MediaWikiDeleteAdd(Queries: TStrings; const PageTitle, DeleteToken, Reason: string; PageID: TMediaWikiID; Suppress: Boolean; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiDeleteParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiDeleteInfo); type TMediaWikiDeleteRevisionInfo = record DeleteRevisionSuccess: Boolean; DeleteRevisionPage: string; DeleteRevisionID: TMediaWikiID; DeleteRevisionReason: string; end; procedure MediaWikiDeleteRevisionAdd(Queries: TStrings; const PageTitle, DeleteToken, Reason: string; PageID, RevisionID: TMediaWikiID; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiDeleteRevisionParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiDeleteRevisionInfo); type TMediaWikiUploadFlag = (mwfUploadWatch, mwfUploadIgnoreWarnings); TMediaWikiUploadFlags = set of TMediaWikiUploadFlag; TMediaWikiUploadInfo = record UploadSuccess: Boolean; UploadFileName: string; UploadImageDataTime: TDateTime; UploadImageUser: string; UploadImageSize: Int64; UploadImageWidth: Int64; UploadImageHeight: Int64; UploadImageURL: string; UploadImageDescriptionURL: string; UploadImageComment: string; UploadImageSHA1: string; UploadImageMetaData: string; UploadImageMime: string; UploadImageBitDepth: Int64; end; procedure MediaWikiUploadAdd(Queries: TStrings; const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiUploadParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiUploadInfo); type TMediaWikiUserMergeInfo = record UserMergeSuccess: Boolean; UserMergeOldUser: string; UserMergeNewUser: string; end; procedure MediaWikiUserMergeAdd(Queries: TStrings; const OldUser, NewUser, Token: string; DeleteUser: Boolean; OutputFormat: TMediaWikiOutputFormat); procedure MediaWikiUserMergeParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiUserMergeInfo); implementation uses DateUtils, OverbyteIcsUrl, JclAnsiStrings, JclMime, JclStrings; //=== { EMediaWikiException } ================================================ constructor EMediaWikiException.Create(const AInfo: string); begin inherited Create(''); FInfo := AInfo; end; procedure EMediaWikiException.AfterConstruction; begin Message := Format('MediaWiki exception with message: "%s"', [Info]); end; //=== { EMediaWikiWarning } ================================================== constructor EMediaWikiWarning.Create(const AInfo, AQuery: string); begin inherited Create(AInfo); FQuery := AQuery; end; procedure EMediaWikiWarning.AfterConstruction; begin Message := Format('MediaWiki warning during query "%s" with info "%s"', [Query, Info]); end; //=== { EMediaWikiError } ==================================================== constructor EMediaWikiError.Create(const AInfo, ACode: string); begin inherited Create(AInfo); FCode := ACode; end; procedure EMediaWikiError.AfterConstruction; begin Message := Format('MediaWiki error code "%s" with info "%s"', [Code, Info]); end; procedure MediaWikiCheckXML(XML: TJclSimpleXML; WarningCallback: TMediaWikiXMLWarningCallback; ErrorCallback: TMediaWikiXMLErrorCallback); var ErrorElem, WarningsElem, WarningElem: TJclSimpleXMLElem; Info, Code: string; Index: Integer; begin XML.Options := XML.Options - [sxoAutoCreate]; // check errors and warnings ErrorElem := XML.Root.Items.ItemNamed['error']; WarningsElem := XML.Root.Items.ItemNamed['warnings']; if Assigned(ErrorElem) then begin XML.Options := XML.Options + [sxoAutoCreate]; Info := ErrorElem.Properties.ItemNamed['info'].Value; Code := ErrorElem.Properties.ItemNamed['code'].Value; ErrorCallback(Info, Code); end; if Assigned(WarningsElem) then begin XML.Options := XML.Options - [sxoAutoCreate]; for Index := 0 to WarningsElem.Items.Count - 1 do begin WarningElem := WarningsElem.Items.Item[Index]; WarningCallback(WarningElem.Value, WarningElem.Name); end; end; end; function FindMediaWikiLoginResult(const AString: string): TMediaWikiLoginResult; begin for Result := Low(TMediaWikiLoginResult) to High(TMediaWikiLoginResult) do if SameText(AString, MediaWikiLoginResults[Result]) then Exit; raise EMediaWikiException.Create('not a valid login result'); end; function StrISO8601ToDateTime(const When: string): TDateTime; var Year, Month, Day, Hour, Min, Sec: Integer; ErrCode: Integer; begin Result := 0; if (Length(When) = 20) and (When[5] = '-') and (When[8] = '-') and (When[11] = 'T') and (When[14] = ':') and (When[17] = ':') and (When[20] = 'Z') then begin Val(Copy(When, 1, 4), Year, ErrCode); if (ErrCode <> 0) or (Year < 0) then Exit; Val(Copy(When, 6, 2), Month, ErrCode); if (ErrCode <> 0) or (Month < 1) or (Month > 12) then Exit; Val(Copy(When, 9, 2), Day, ErrCode); if (ErrCode <> 0) or (Day < 1) or (Day > 31) then Exit; Val(Copy(When, 12, 2), Hour, ErrCode); if (ErrCode <> 0) or (Hour < 0) or (Hour > 23) then Exit; Val(Copy(When, 15, 2), Min, ErrCode); if (ErrCode <> 0) or (Min < 0) or (Min > 59) then Exit; Val(Copy(When, 18, 2), Sec, ErrCode); if (ErrCode <> 0) or (Sec < 0) or (Sec > 59) then Exit; Result := DateUtils.EncodeDateTime(Year, Month, Day, Hour, Min, Sec, 0); end else if When = 'infinity' then Result := Infinity; end; function DateTimeToStrISO8601(When: TDateTime): string; var Year, Month, Day, Hour, Min, Sec, MSec: Word; begin if When = Infinity then Result := 'infinity' else begin DateUtils.DecodeDateTime(When, Year, Month, Day, Hour, Min, Sec, MSec); Result := Format('%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ', [Year, Month, Day, Hour, Min, Sec]); end; end; // post stuff procedure MediaWikiQueryAdd(Queries: TStrings; const AName, AValue: AnsiString; RawValue: Boolean; Content: TStream); var NamePos: Integer; CurrentValue: string; Values: TStringList; begin NamePos := Queries.IndexOfName(string(AName)); if Assigned(Content) then begin if NamePos >= 0 then Queries.Delete(NamePos); NamePos := Queries.IndexOf(string(AName)); if NamePos >= 0 then Queries.Delete(NamePos); Queries.Values[AName] := AValue; NamePos := Queries.IndexOfName(AName); Queries.Objects[NamePos] := Content; end else if (NamePos >= 0) and (AValue <> '') then begin // avoid duplicate values CurrentValue := Queries.Values[AName]; if (CurrentValue <> AValue) and (Pos('|', CurrentValue) > 0) then begin Values := TStringList.Create; try StrToStrings(CurrentValue, '|', Values, True); if Values.IndexOf(AValue) < 0 then Queries.Values[AName] := CurrentValue + '|' + AValue; finally Values.Free; end; end else if CurrentValue <> AValue then Queries.Values[AName] := CurrentValue + '|' + AValue; if RawValue then Queries.Objects[NamePos] := Queries; end else if AValue = '' then begin Queries.Values[AName] := 'true'; if RawValue then begin NamePos := Queries.IndexOfName(AName); Queries.Objects[NamePos] := Queries; end; end else begin Queries.Values[AName] := AValue; if RawValue then begin NamePos := Queries.IndexOfName(AName); Queries.Objects[NamePos] := Queries; end; end; end; procedure MediaWikiQueryAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo); begin if ContinueInfo.ParameterName <> '' then MediaWikiQueryAdd(Queries, ContinueInfo.ParameterName, ContinueInfo.ParameterValue, True, nil); end; procedure MediaWikiQueryPostAdd(ASendStream: TStream; const Data: AnsiString); begin if Length(Data) > 0 then ASendStream.WriteBuffer(Data[1], Length(Data)); end; procedure MediaWikiQueryPostWWWFormUrlEncoded(Queries: TStrings; ASendStream: TStream); var AName: string; I, J: Integer; Values: TStrings; begin Values := TStringList.Create; try for I := 0 to Queries.Count - 1 do begin if I > 0 then MediaWikiQueryPostAdd(ASendStream, '&'); AName := Queries.Names[I]; if AName = '' then MediaWikiQueryPostAdd(ASendStream, AnsiString(Queries.Strings[I])) else begin if Queries.Objects[I] = nil then begin // call UrlEncodeToA StrToStrings(Queries.ValueFromIndex[I], '|', Values, False); for J := 0 to Values.Count - 1 do Values.Strings[J] := UrlEncodeToA(Values.Strings[J]); MediaWikiQueryPostAdd(ASendStream, AnsiString(AName) + '=' + AnsiString(StringsToStr(Values, '|', False))); end else // skip UrlEncodeToA MediaWikiQueryPostAdd(ASendStream, AnsiString(Queries.Strings[I])); end; end; //MediaWikiQueryPostAdd(ASendStream, AnsiCarriageReturn); finally Values.Free; end; end; procedure MediaWikiQueryPostFormData(Queries: TStrings; ASendStream: TStream); var AName: string; Boundary: AnsiString; Index: Integer; Content: TStream; begin Boundary := Format('--%.4x%.4x%.8x', [Cardinal(Queries), Cardinal(ASendStream), DateTimeToUnix(Now)]); for Index := 0 to Queries.Count - 1 do begin MediaWikiQueryPostAdd(ASendStream, Boundary + AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, 'Content-Disposition: form-data; '); AName := Queries.Names[Index]; if Queries.Objects[Index] is TStream then begin Content := TStream(Queries.Objects[Index]); MediaWikiQueryPostAdd(ASendStream, 'name="' + AnsiString(AName) + '"; filename="' + Queries.Values[AName] + '"' + AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, 'content-type: application/octet-stream' + AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, 'Content-Transfer-Encoding: base64' + AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, AnsiLineBreak); MimeEncodeStream(Content, ASendStream); //ASendStream.CopyFrom(Content, Content.Size); MediaWikiQueryPostAdd(ASendStream, AnsiLineBreak); end else if AName = '' then begin MediaWikiQueryPostAdd(ASendStream, 'name="' + AnsiString(Queries.Strings[Index]) + '"' + AnsiLineBreak); //MediaWikiQueryPostAdd(ASendStream, 'content-type: text/plain' + AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, AnsiLineBreak); end else begin MediaWikiQueryPostAdd(ASendStream, 'name="' + AnsiString(AName) + '"' + AnsiLineBreak); //MediaWikiQueryPostAdd(ASendStream, 'content-type: text/plain' + AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, AnsiLineBreak); MediaWikiQueryPostAdd(ASendStream, AnsiString(Queries.Values[AName]) + AnsiLineBreak); end; end; MediaWikiQueryPostAdd(ASendStream, Boundary + '--' + AnsiLineBreak); end; procedure MediaWikiQueryPost(Queries: TStrings; ASendStream: TStream; out ContentType: string); var Index: Integer; begin for Index := 0 to Queries.Count - 1 do if Queries.Objects[Index] is TStream then begin ContentType := 'multipart/form-data'; MediaWikiQueryPostFormData(Queries, ASendStream); Exit; end; ContentType := 'application/x-www-form-urlencoded'; MediaWikiQueryPostWWWFormUrlEncoded(Queries, ASendStream); end; // login stuff procedure MediaWikiQueryLoginAdd(Queries: TStrings; const lgName, lgPassword, lgToken: string; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'login'); MediaWikiQueryAdd(Queries, 'lgname', lgName, True); MediaWikiQueryAdd(Queries, 'lgpassword', lgPassword); MediaWikiQueryAdd(Queries, 'lgtoken', lgToken); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryLoginParseXmlResult(XML: TJclSimpleXML; out LoginResult: TMediaWikiLoginResult; out LoginUserID: TMediaWikiID; out LoginUserName: string); var Login: TJclSimpleXMLElem; begin XML.Options := XML.Options + [sxoAutoCreate]; Login := XML.Root.Items.ItemNamed['login']; LoginResult := FindMediaWikiLoginResult(Login.Properties.ItemNamed['result'].Value); LoginUserID := Login.Properties.ItemNamed['lguserid'].IntValue; LoginUserName := Login.Properties.ItemNamed['lgusername'].Value; end; // logout stuff procedure MediaWikiQueryLogoutAdd(Queries: TStrings; const token: string; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'logout'); MediaWikiQueryAdd(Queries, 'token', token); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryLogoutParseXmlResult(XML: TJclSimpleXML); begin // nothing special to be done end; // query, site info general procedure MediaWikiQuerySiteInfoGeneralAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'general'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoGeneralParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, General: TJclSimpleXMLElem; Index: Integer; Prop: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; General := Query.Items.ItemNamed['general']; Infos.BeginUpdate; try for Index := 0 to General.Properties.Count - 1 do begin Prop := General.Properties.Item[Index]; Infos.Values[Prop.Name] := Prop.Value; end; finally Infos.EndUpdate; end; end; // query, site info namespaces procedure MediaWikiQuerySiteInfoNamespacesAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'namespaces'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoNamespacesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, Namespaces, NameSpace: TJclSimpleXMLElem; Index: Integer; IDProp, CanonicalProp: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Namespaces := Query.Items.ItemNamed['namespaces']; Infos.BeginUpdate; try for Index := 0 to Namespaces.Items.Count - 1 do begin NameSpace := Namespaces.Items.Item[Index]; IDProp := NameSpace.Properties.ItemNamed['id']; CanonicalProp := NameSpace.Properties.ItemNamed['canonical']; Infos.Values[CanonicalProp.Value] := IDProp.Value; end; finally Infos.EndUpdate; end; end; // query, site info, namespace aliases procedure MediaWikiQuerySiteInfoNamespaceAliasesAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'namespacealiases'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoNamespaceAliasesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, NamespaceAliases, Namespace: TJclSimpleXMLElem; Index: Integer; Prop: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; NamespaceAliases := Query.Items.ItemNamed['namespacealiases']; Infos.BeginUpdate; try for Index := 0 to NamespaceAliases.Items.Count - 1 do begin Namespace := NamespaceAliases.Items.Item[Index]; Prop := Namespace.Properties.ItemNamed['id']; Infos.Values[Namespace.Value] := Prop.Value; end; finally Infos.EndUpdate; end; end; // query, site info, special page aliases procedure MediaWikiQuerySiteInfoSpecialPageAliasesAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'specialpagealiases'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoSpecialPageAliasesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, SpecialPageAliases, SpecialPage, Aliases, Alias: TJclSimpleXMLElem; I, J: Integer; RealName: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; SpecialPageAliases := Query.Items.ItemNamed['specialpagealiases']; Infos.BeginUpdate; try for I := 0 to SpecialPageAliases.Items.Count - 1 do begin SpecialPage := SpecialPageAliases.Items.Item[I]; RealName := SpecialPage.Properties.ItemNamed['realname']; Aliases := SpecialPage.Items.ItemNamed['aliases']; for J := 0 to Aliases.Items.Count - 1 do begin Alias := Aliases.Items.Item[J]; Infos.Values[Alias.Value] := RealName.Value; end; end; finally Infos.EndUpdate; end; end; // query, site info, magic words procedure MediaWikiQuerySiteInfoMagicWordsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'magicwords'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoMagicWordsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, MagicWords, MagicWord, Aliases, Alias: TJclSimpleXMLElem; I, J: Integer; NameProp: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; MagicWords := Query.Items.ItemNamed['magicwords']; Infos.BeginUpdate; try for I := 0 to MagicWords.Items.Count - 1 do begin MagicWord := MagicWords.Items.Item[I]; NameProp := MagicWord.Properties.ItemNamed['name']; Aliases := MagicWord.Items.ItemNamed['aliases']; for J := 0 to Aliases.Items.Count - 1 do begin Alias := Aliases.Items.Item[J]; Infos.Values[Alias.Value] := NameProp.Value; end; end; finally Infos.EndUpdate; end; end; // query, site info, statistics procedure MediaWikiQuerySiteInfoStatisticsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'statistics'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoStatisticsParseXmlResult(XML: TJclSimpleXML; Info: TStrings); var Query, Statistics: TJclSimpleXMLElem; Index: Integer; Prop: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Statistics := Query.Items.ItemNamed['statistics']; Info.BeginUpdate; try for Index := 0 to Statistics.Properties.Count - 1 do begin Prop := Statistics.Properties.Item[Index]; Info.Values[Prop.Name] := Prop.Value; end; finally Info.EndUpdate; end; end; // query, site info, inter wiki map procedure MediaWikiQuerySiteInfoInterWikiMapAdd(Queries: TStrings; Local: Boolean; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'interwikimap'); if Local then MediaWikiQueryAdd(Queries, 'sifilteriw', 'local') else MediaWikiQueryAdd(Queries, 'sifilteriw', '!local'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoInterWikiMapParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, InterWikiMap, InterWiki: TJclSimpleXMLElem; Index: Integer; PrefixProp, UrlProp: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; InterWikiMap := Query.Items.ItemNamed['interwikimap']; Infos.BeginUpdate; try for Index := 0 to InterWikiMap.Items.Count - 1 do begin InterWiki := InterWikiMap.Items.Item[Index]; PrefixProp := InterWiki.Properties.ItemNamed['prefix']; UrlProp := InterWiki.Properties.ItemNamed['url']; Infos.Values[PrefixProp.Value] := UrlProp.Value; end; finally Infos.EndUpdate; end; end; // query, site info , DB replication lag procedure MediaWikiQuerySiteInfoDBReplLagAdd(Queries: TStrings; ShowAllDB: Boolean; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'dbrepllag'); if ShowAllDB then MediaWikiQueryAdd(Queries, 'sishowalldb'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoDBReplLagParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, DBReplLag, DB: TJclSimpleXMLElem; Index: Integer; Host, Lag: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; DBReplLag := Query.Items.ItemNamed['dbrepllag']; Infos.BeginUpdate; try for Index := 0 to DBReplLag.Items.Count - 1 do begin DB := DBReplLag.Items.Item[Index]; Host := DB.Properties.ItemNamed['host']; Lag := DB.Properties.ItemNamed['lag']; Infos.Values[Host.Name] := Lag.Value; end; finally Infos.EndUpdate; end; end; // query, site info, user groups procedure MediaWikiQuerySiteInfoUserGroupsAdd(Queries: TStrings; IncludeUserCount: Boolean; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'usergroups'); if IncludeUserCount then MediaWikiQueryAdd(Queries, 'sinumberingroup'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoUserGroupsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, UserGroups, Group, Rights, Permission: TJclSimpleXMLElem; I, J: Integer; Name: TJclSimpleXMLProp; Permissions: string; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserGroups := Query.Items.ItemNamed['usergroups']; Infos.BeginUpdate; try for I := 0 to UserGroups.Items.Count - 1 do begin Group := UserGroups.Items.Item[I]; Name := Group.Properties.ItemNamed['name']; Rights := Group.Items.ItemNamed['rights']; Permissions := ''; for J := 0 to Rights.Items.Count - 1 do begin Permission := Rights.Items.Item[J]; if Permissions <> '' then Permissions := Permissions + '|' + Permission.Value else Permissions := Permission.Value; end; Infos.Values[Name.Value] := Permissions; end; finally Infos.EndUpdate; end; end; // query, site info, extensions procedure MediaWikiQuerySiteInfoExtensionsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'siteinfo'); MediaWikiQueryAdd(Queries, 'siprop', 'extensions'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQuerySiteInfoExtensionsParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiExtensions); var Query, Extensions, Extension: TJclSimpleXMLElem; Index: Integer; TypeProp, NameProp, DescriptionProp, DescriptionMsgProp, AuthorProp, VersionProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Extensions := Query.Items.ItemNamed['extensions']; SetLength(Infos, Extensions.Items.Count); for Index := 0 to Extensions.Items.Count - 1 do begin Extension := Extensions.Items.Item[Index]; TypeProp := Extension.Properties.ItemNamed['type']; NameProp := Extension.Properties.ItemNamed['name']; DescriptionProp := Extension.Properties.ItemNamed['description']; DescriptionMsgProp := Extension.Properties.ItemNamed['descriptionmsg']; AuthorProp := Extension.Properties.ItemNamed['author']; VersionProp := Extension.Properties.ItemNamed['version']; Infos[Index].ExtensionType := TypeProp.Value; Infos[Index].ExtensionName := NameProp.Value; Infos[Index].ExtensionDescription := DescriptionProp.Value; Infos[Index].ExtensionDescriptionMsg := DescriptionMsgProp.Value; Infos[Index].ExtensionAuthor := AuthorProp.Value; Infos[Index].ExtensionVersion := VersionProp.Value; end; end; // query meta token stuff procedure MediaWikiQueryTokensAdd(Queries: TStrings; Tokens: TMediaWikiTokens; OutputFormat: TMediaWikiOutputFormat); var Type_: string; Token: TMediaWikiToken; begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'tokens'); Type_ := ''; for Token := Low(TMediaWikiToken) to High(TMediaWikiToken) do if Token in Tokens then begin if Type_ <> '' then Type_ := Type_ + '|' + MediaWikiTokenNames[Token] else Type_ := MediaWikiTokenNames[Token]; end; MediaWikiQueryAdd(Queries, 'type', Type_); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryTokensParseXmlResult(XML: TJclSimpleXML; out TokenValues: TMediaWikiTokenValues); var Query, Tokens: TJclSimpleXMLElem; Token: TMediaWikiToken; TokenName: string; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Tokens := Query.Items.ItemNamed['tokens']; for Token := Low(TMediaWikiToken) to High(TMediaWikiToken) do begin TokenName := MediaWikiTokenNames[Token]; TokenValues[Token] := Tokens.Properties.ItemNamed[TokenName+'token'].Value; end; end; // query, user info, block info procedure MediaWikiQueryUserInfoBlockInfoAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'blockinfo'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoBlockInfoParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, BlockInfo: TJclSimpleXMLElem; Index: Integer; Prop: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; BlockInfo := Query.Items.ItemNamed['userinfo']; Infos.BeginUpdate; try for Index := 0 to BlockInfo.Properties.Count - 1 do begin Prop := BlockInfo.Properties.Item[Index]; Infos.Values[Prop.Name] := Prop.Value; end; finally Infos.EndUpdate; end; end; // query, user info, has msg procedure MediaWikiQueryUserInfoHasMsgAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'hasmsg'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoHasMsgParseXmlResult(XML: TJclSimpleXML; out HasMessage: Boolean); var Query, UserInfo: TJclSimpleXMLElem; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; XML.Options := XML.Options - [sxoAutoCreate]; HasMessage := Assigned(UserInfo.Properties.ItemNamed['messages']); end; // query, user info, groups procedure MediaWikiQueryUserInfoGroupsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'groups'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoGroupsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, UserInfo, Groups, Group: TJclSimpleXMLElem; Index: Integer; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; Groups := UserInfo.Items.ItemNamed['groups']; Infos.BeginUpdate; try for Index := 0 to Groups.Items.Count - 1 do begin Group := Groups.Items.Item[Index]; Infos.Add(Group.Value); end; finally Infos.EndUpdate; end; end; //query, user info, rights procedure MediaWikiQueryUserInfoRightsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'rights'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoRightsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, UserInfo, Rights, Right: TJclSimpleXMLElem; Index: Integer; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; Rights := UserInfo.Items.ItemNamed['rights']; Infos.BeginUpdate; try for Index := 0 to Rights.Items.Count - 1 do begin Right := Rights.Items.Item[Index]; Infos.Add(Right.Value); end; finally Infos.EndUpdate; end; end; // query, user info, changeable groups procedure MediaWikiQueryUserInfoChangeableGroupsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'changeablegroups'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoChangeableGroupsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, UserInfo, ChangeableGroups: TJclSimpleXMLElem; Index: Integer; Prop: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; ChangeableGroups := UserInfo.Items.ItemNamed['changeablegroups']; Infos.BeginUpdate; try for Index := 0 to ChangeableGroups.Properties.Count - 1 do begin Prop := ChangeableGroups.Properties.Item[Index]; Infos.Values[Prop.Name] := Prop.Value; end; finally Infos.EndUpdate; end; end; // query, user info, options procedure MediaWikiQueryUserInfoOptionsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'options'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoOptionsParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, UserInfo, Options: TJclSimpleXMLElem; Index: Integer; Prop: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; Options := UserInfo.Items.ItemNamed['options']; Infos.BeginUpdate; try for Index := 0 to Options.Properties.Count - 1 do begin Prop := Options.Properties.Item[Index]; Infos.Values[Prop.Name] := Prop.Value; end; finally Infos.EndUpdate; end; end; // query, user info, edit count procedure MediaWikiQueryUserInfoEditCountAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'editcount'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoEditCountParseXmlResult(XML: TJclSimpleXML; out EditCount: Integer); var Query, UserInfo: TJclSimpleXMLElem; EditCountProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; EditCountProp := UserInfo.Properties.ItemNamed['editcount']; EditCount := EditCountProp.IntValue; end; // query, user info, rate limits procedure MediaWikiQueryUserInfoRateLimitsAdd(Queries: TStrings; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'userinfo'); MediaWikiQueryAdd(Queries, 'uiprop', 'ratelimits'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryUserInfoRateLimitsParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiRateLimits); var Query, UserInfo, RateLimits, RateLimit, Group: TJclSimpleXMLElem; I, J, K: Integer; HitsProp, SecondsProp: TJclSimpleXMLProp; begin SetLength(Infos, 0); XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; UserInfo := Query.Items.ItemNamed['userinfo']; RateLimits := UserInfo.Items.ItemNamed['ratelimits']; for I := 0 to RateLimits.Items.Count - 1 do begin RateLimit := RateLimits.Items.Item[I]; for J := 0 to RateLimit.Items.Count - 1 do begin Group := RateLimit.Items.Item[J]; HitsProp := Group.Properties.ItemNamed['hits']; SecondsProp := Group.Properties.ItemNamed['seconds']; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].RateLimitAction := RateLimit.Name; Infos[K].RateLimitGroup := Group.Name; Infos[K].RateLimitHits := HitsProp.IntValue; Infos[K].RateLimitSeconds := SecondsProp.IntValue; end; end; end; // query, messages procedure MediaWikiQueryMessagesAdd(Queries: TStrings; const NameFilter, ContentFilter, Lang: string; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'meta', 'allmessages'); if NameFilter <> '' then MediaWikiQueryAdd(Queries, 'ammessages', NameFilter); if ContentFilter <> '' then MediaWikiQueryAdd(Queries, 'amfilter', ContentFilter); if Lang <> '' then MediaWikiQueryAdd(Queries, 'amlang', Lang); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryMessagesParseXmlResult(XML: TJclSimpleXML; Infos: TStrings); var Query, AllMessages, Message: TJclSimpleXMLElem; Index: Integer; Name: TJclSimpleXMLProp; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; AllMessages := Query.Items.ItemNamed['allmessages']; Infos.BeginUpdate; try for Index := 0 to AllMessages.Items.Count - 1 do begin Message := AllMessages.Items.Item[Index]; Name := Message.Properties.ItemNamed['name']; Infos.Values[Name.Value] := Message.Value; end; finally Infos.EndUpdate; end; end; // query, page info procedure MediaWikiQueryPageInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; Flags: TMediaWikiPageInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'prop', 'info'); if PageID then MediaWikiQueryAdd(Queries, 'pageids', Titles) else MediaWikiQueryAdd(Queries, 'titles', Titles); if mwfIncludeProtection in Flags then MediaWikiQueryAdd(Queries, 'inprop', 'protection'); if mwfIncludeTalkID in Flags then MediaWikiQueryAdd(Queries, 'inprop', 'talkid'); if mwfIncludeSubjectID in Flags then MediaWikiQueryAdd(Queries, 'inprop', 'subjectid'); if mwfIncludeURL in Flags then MediaWikiQueryAdd(Queries, 'inprop', 'url'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryPageInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageInfos); var Query, Pages, Page, Protections, Protection: TJclSimpleXMLElem; I, J: Integer; ID, Namespace, Title, LastTouched, RevID, Views, Size, Redirect, New, TalkID, SubjectID, FullURL, EditURL, TypeProp, Level, Expiry: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Pages := Query.Items.ItemNamed['pages']; SetLength(Infos, Pages.Items.Count); for I := 0 to Pages.Items.Count - 1 do begin Page := Pages.Items.Item[I]; ID := Page.Properties.ItemNamed['pageid']; Namespace := Page.Properties.ItemNamed['ns']; Title := Page.Properties.ItemNamed['title']; LastTouched := Page.Properties.ItemNamed['touched']; RevID := Page.Properties.ItemNamed['lastrevid']; Views := Page.Properties.ItemNamed['counter']; Size := Page.Properties.ItemNamed['length']; XML.Options := XML.Options - [sxoAutoCreate]; Redirect := Page.Properties.ItemNamed['redirect']; New := Page.Properties.ItemNamed['new']; Protections := Page.Items.ItemNamed['protection']; TalkID := Page.Properties.ItemNamed['talkid']; SubjectID := Page.Properties.ItemNamed['subjectid']; FullURL := Page.Properties.ItemNamed['fullurl']; EditURL := Page.Properties.ItemNamed['editurl']; XML.Options := XML.Options + [sxoAutoCreate]; Infos[I].PageBasics.PageID := ID.IntValue; Infos[I].PageBasics.PageNamespace := Namespace.IntValue; Infos[I].PageBasics.PageTitle := Title.Value; Infos[I].PageLastTouched := StrISO8601ToDateTime(LastTouched.Value); Infos[I].PageRevisionID := RevID.IntValue; Infos[I].PageViews := Views.IntValue; Infos[I].PageSize := Size.IntValue; if Assigned(Redirect) then Include(Infos[I].PageFlags, mwfPageIsRedirect); if Assigned(New) then Include(Infos[I].PageFlags, mwfPageIsNew); if Assigned(Protections) then begin SetLength(Infos[I].PageProtections, Protections.Items.Count); for J := 0 to Protections.Items.Count - 1 do begin Protection := Protections.Items.Item[J]; TypeProp := Protection.Properties.ItemNamed['type']; Level := Protection.Properties.ItemNamed['level']; Expiry := Protection.Properties.ItemNamed['expiry']; Infos[I].PageProtections[J].PageProtectionAction := TypeProp.Value; Infos[I].PageProtections[J].PageProtectionGroup := Level.Value; Infos[I].PageProtections[J].PageProtectionExpiry := Expiry.Value; end; end; if Assigned(TalkID) then Infos[I].PageTalkID := TalkID.IntValue; if Assigned(SubjectID) then Infos[I].PageSubjectID := SubjectID.IntValue; if Assigned(FullURL) then Infos[I].PageFullURL := FullURL.Value; if Assigned(EditURL) then Infos[I].PageEditURL := EditURL.Value; end; end; // query, page info, revision info procedure MediaWikiQueryPageRevisionInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; Flags: TMediaWikiPageRevisionInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxRevisions, Section: Integer; StartRevisionID, EndRevisionID: TMediaWikiID; const StartDateTime, EndDateTime: TDateTime; const IncludeUser, ExcludeUser: string; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'prop', 'revisions'); if PageID then MediaWikiQueryAdd(Queries, 'pageids', Titles) else MediaWikiQueryAdd(Queries, 'titles', Titles); if mwfIncludeRevisionID in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'ids'); if mwfIncludeRevisionFlags in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'flags'); if mwfIncludeRevisionTimeStamp in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'timestamp'); if mwfIncludeRevisionAuthor in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'user'); if mwfIncludeRevisionComment in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'comment'); if mwfIncludeRevisionSize in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'size'); if mwfIncludeRevisionContent in Flags then MediaWikiQueryAdd(Queries, 'rvprop', 'content'); //if mwfTags in Flags then // MediaWikiQueryAdd(Queries, 'rvprop', 'tags'); if mwfRevisionReverseOrder in Flags then MediaWikiQueryAdd(Queries, 'rvdir', 'newer') else MediaWikiQueryAdd(Queries, 'rvdir', 'older'); if mwfIncludeRevisionRollbackToken in Flags then MediaWikiQueryAdd(Queries, 'rvtoken', 'rollback'); if mwfRevisionContentXml in Flags then MediaWikiQueryAdd(Queries, 'rvgeneratexml'); if mwfRevisionContentExpandTemplates in Flags then MediaWikiQueryAdd(Queries, 'rvexpandtemplates'); if mwfRevisionContinue in Flags then MediaWikiQueryAdd(Queries, 'rvcontinue'); if MaxRevisions > 0 then MediaWikiQueryAdd(Queries, 'rvlimit', IntToStr(MaxRevisions)); if Section >= 0 then MediaWikiQueryAdd(Queries, 'rvsection', IntToStr(Section)); if StartRevisionID >= 0 then MediaWikiQueryAdd(Queries, 'rvstartid', IntToStr(StartRevisionID)); if EndRevisionID >= 0 then MediaWikiQueryAdd(Queries, 'rvendid', IntToStr(EndRevisionID)); if (StartRevisionID < 0) and (StartDateTime <> 0.0) then MediaWikiQueryAdd(Queries, 'rvstart', DateTimeToStrISO8601(StartDateTime), True); if (EndRevisionID < 0) and (EndDateTime <> 0.0) then MediaWikiQueryAdd(Queries, 'rvend', DateTimeToStrISO8601(EndDateTime), True); if IncludeUser <> '' then MediaWikiQueryAdd(Queries, 'rvuser', IncludeUser); if ExcludeUser <> '' then MediaWikiQueryAdd(Queries, 'rvexcludeuser', ExcludeUser); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryPageRevisionInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageRevisionInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, Pages, Page, Revisions, Revision, Continue: TJclSimpleXMLElem; I, J, K: Integer; PageID, NameSpace, Title, RevID, Minor, Author, TimeStamp, Size, Comment, RollbackToken: TJclSimpleXMLProp; begin SetLength(Infos, 0); XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Pages := Query.Items.ItemNamed['pages']; for I := 0 to Pages.Items.Count - 1 do begin Page := Pages.Items.Item[I]; PageID := Page.Properties.ItemNamed['pageid']; NameSpace := Page.Properties.ItemNamed['ns']; Title := Page.Properties.ItemNamed['title']; Revisions := Page.Items.ItemNamed['revisions']; for J := 0 to Revisions.Items.Count - 1 do begin Revision := Revisions.Items.Item[J]; RevID := Revision.Properties.ItemNamed['revid']; Author := Revision.Properties.ItemNamed['user']; TimeStamp := Revision.Properties.ItemNamed['timestamp']; Size := Revision.Properties.ItemNamed['size']; Comment := Revision.Properties.ItemNamed['comment']; RollbackToken := Revision.Properties.ItemNamed['rollbacktoken']; XML.Options := XML.Options - [sxoAutoCreate]; Minor := Revision.Properties.ItemNamed['minor']; XML.Options := XML.Options + [sxoAutoCreate]; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].PageRevisionInfoPageBasics.PageTitle := Title.Value; Infos[K].PageRevisionInfoPageBasics.PageNamespace := NameSpace.IntValue; Infos[K].PageRevisionInfoPageBasics.PageID := PageID.IntValue; Infos[K].PageRevisionInfoID := RevID.IntValue; if Assigned(Minor) then Include(Infos[K].PageRevisionInfoFlags, mwfMinorEdit); Infos[K].PageRevisionInfoDateTime := StrISO8601ToDateTime(TimeStamp.Value); Infos[K].PageRevisionInfoAuthor := Author.Value; Infos[K].PageRevisionInfoComment := Comment.Value; Infos[K].PageRevisionInfoSize := Size.IntValue; Infos[K].PageRevisionInfoContent := Revision.Value; Infos[K].PageRevisionInfoRollbackToken := RollbackToken.Value; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; // query, page info, category info procedure MediaWikiQueryPageCategoryInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; Flags: TMediaWikiPageCategoryInfoFlags; const ContinueInfo: TMediaWikiContinueInfo; MaxCategories: Integer; const CategoryTitles: string; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'prop', 'categories'); if PageID then MediaWikiQueryAdd(Queries, 'pageids', Titles) else MediaWikiQueryAdd(Queries, 'titles', Titles); if mwfIncludeCategorySortKey in Flags then MediaWikiQueryAdd(Queries, 'clprop', 'sortkey'); if mwfIncludeCategoryTimeStamp in Flags then MediaWikiQueryAdd(Queries, 'clprop', 'timestamp'); if mwfCategoryHidden in Flags then MediaWikiQueryAdd(Queries, 'clshow', 'hidden') else MediaWikiQueryAdd(Queries, 'clshow', '!hidden'); if MaxCategories > 0 then MediaWikiQueryAdd(Queries, 'cllimit', IntToStr(MaxCategories)); if CategoryTitles <> '' then MediaWikiQueryAdd(Queries, 'clcategories', CategoryTitles); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryPageCategoryInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageCategoryInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, Pages, Page, Categories, Category, Continue: TJclSimpleXMLElem; I, J, K: Integer; PageID, PageNamespace, PageTitle, Namespace, Title, SortKey, TimeStamp: TJclSimpleXMLProp; begin SetLength(Infos, 0); XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Pages := Query.Items.ItemNamed['pages']; for I := 0 to Pages.Items.Count - 1 do begin Page := Pages.Items.Item[I]; PageID := Page.Properties.ItemNamed['pageid']; PageNamespace := Page.Properties.ItemNamed['ns']; PageTitle := Page.Properties.ItemNamed['title']; Categories := Page.Items.ItemNamed['categories']; for J := 0 to Categories.Items.Count - 1 do begin Category := Categories.Items.Item[J]; Namespace := Category.Properties.ItemNamed['ns']; Title := Category.Properties.ItemNamed['title']; SortKey := Category.Properties.ItemNamed['sortkey']; TimeStamp := Category.Properties.ItemNamed['timestamp']; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].CategoryPageBasics.PageTitle := PageTitle.Value; Infos[K].CategoryPageBasics.PageNamespace := PageNamespace.IntValue; Infos[K].CategoryPageBasics.PageID := PageID.IntValue; Infos[K].CategoryTitle := Title.Value; Infos[K].CategoryNameSpace := Namespace.IntValue; Infos[K].CategoryTimeStamp := StrISO8601ToDateTime(TimeStamp.Value); Infos[K].CategorySortKey := SortKey.Value; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; // query, page info, link info procedure MediaWikiQueryPageLinkInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks, Namespace: Integer; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'prop', 'links'); if PageID then MediaWikiQueryAdd(Queries, 'pageids', Titles) else MediaWikiQueryAdd(Queries, 'titles', Titles); if MaxLinks > 0 then MediaWikiQueryAdd(Queries, 'pllimit', IntToStr(MaxLinks)); if Namespace >= 0 then MediaWikiQueryAdd(Queries, 'plnamespace', IntToStr(Namespace)); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryPageLinkInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, Pages, Page, Links, Link, Continue: TJclSimpleXMLElem; I, J, K: Integer; PageID, PageTitle, PageNamespace, TargetNamespace, TargetTitle: TJclSimpleXMLProp; begin SetLength(Infos, 0); XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Pages := Query.Items.ItemNamed['pages']; for I := 0 to Pages.Items.Count - 1 do begin Page := Pages.Items.Item[I]; PageID := Page.Properties.ItemNamed['pageid']; PageTitle := Page.Properties.ItemNamed['title']; PageNamespace := Page.Properties.ItemNamed['ns']; Links := Page.Items.ItemNamed['links']; for J := 0 to Links.Items.Count - 1 do begin Link := Links.Items.Item[J]; TargetNamespace := Link.Properties.ItemNamed['ns']; TargetTitle := Link.Properties.ItemNamed['title']; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].LinkSourceBasics.PageTitle := PageTitle.Value; Infos[K].LinkSourceBasics.PageNamespace := PageNamespace.IntValue; Infos[K].LinkSourceBasics.PageID := PageID.IntValue; Infos[K].LinkTargetTitle := TargetTitle.Value; Infos[K].LinkTargetNameSpace := TargetNamespace.IntValue; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; // query, page info, template info procedure MediaWikiQueryPageTemplateInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxTemplates, Namespace: Integer; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'prop', 'templates'); if PageID then MediaWikiQueryAdd(Queries, 'pageids', Titles) else MediaWikiQueryAdd(Queries, 'titles', Titles); if MaxTemplates > 0 then MediaWikiQueryAdd(Queries, 'tllimit', IntToStr(MaxTemplates)); if Namespace >= 0 then MediaWikiQueryAdd(Queries, 'tlnamespace', IntToStr(Namespace)); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryPageTemplateInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageTemplateInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, Pages, Page, Templates, Template, Continue: TJclSimpleXMLElem; I, J, K: Integer; PageTitle, PageID, PageNamespace, TemplateNamespace, TemplateTitle: TJclSimpleXMLProp; begin SetLength(Infos, 0); XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Pages := Query.Items.ItemNamed['pages']; for I := 0 to Pages.Items.Count - 1 do begin Page := Pages.Items.Item[I]; PageTitle := Page.Properties.ItemNamed['title']; PageID := Page.Properties.ItemNamed['pageid']; PageNamespace := Page.Properties.ItemNamed['ns']; Templates := Page.Items.ItemNamed['templates']; for J := 0 to Templates.Items.Count - 1 do begin Template := Templates.Items.Item[J]; TemplateNamespace := Template.Properties.ItemNamed['ns']; TemplateTitle := Template.Properties.ItemNamed['title']; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].TemplatePageBasics.PageTitle := PageTitle.Value; Infos[K].TemplatePageBasics.PageNamespace := PageNamespace.IntValue; Infos[K].TemplatePageBasics.PageID := PageID.IntValue; Infos[K].TemplateTitle := TemplateTitle.Value; Infos[K].TemplateNameSpace := TemplateNamespace.IntValue; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; // query, page info, ext links procedure MediaWikiQueryPageExtLinkInfoAdd(Queries: TStrings; const Titles: string; PageID: Boolean; const ContinueInfo: TMediaWikiContinueInfo; MaxLinks: Integer; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'prop', 'extlinks'); if PageID then MediaWikiQueryAdd(Queries, 'pageids', Titles) else MediaWikiQueryAdd(Queries, 'titles', Titles); if MaxLinks > 0 then MediaWikiQueryAdd(Queries, 'ellimit', IntToStr(MaxLinks)); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryPageExtLinkInfoParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiPageExtLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, Pages, Page, ExtLinks, ExtLink, Continue: TJclSimpleXMLElem; I, J, K: Integer; PageTitle, PageID, PageNamespace: TJclSimpleXMLProp; begin SetLength(Infos, 0); XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Pages := Query.Items.ItemNamed['pages']; for I := 0 to Pages.Items.Count - 1 do begin Page := Pages.Items.Item[I]; PageTitle := Page.Properties.ItemNamed['title']; PageID := Page.Properties.ItemNamed['pageid']; PageNamespace := Page.Properties.ItemNamed['ns']; ExtLinks := Page.Items.ItemNamed['extlinks']; for J := 0 to ExtLinks.Items.Count - 1 do begin ExtLink := ExtLinks.Items.Item[J]; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].ExtLinkPageBasics.PageTitle := PageTitle.Value; Infos[K].ExtLinkPageBasics.PageID := PageID.IntValue; Infos[K].ExtLinkPageBasics.PageNamespace := PageNamespace.IntValue; Infos[K].ExtLinkTarget := ExtLink.Value; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; // query, list, all pages procedure MediaWikiQueryAllPageAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxPage: Integer; Namespace: Integer; RedirFilter: TMediaWikiAllPageFilterRedir; LangFilter: TMediaWikiAllPageFilterLang; MinSize, MaxSize: Integer; ProtectionFilter: TMediaWikiAllPageFilterProtection; LevelFilter: TMediaWikiAllPageFilterLevel; Direction: TMediaWikiAllPageDirection; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'allpages'); if Prefix <> '' then MediaWikiQueryAdd(Queries, 'apprefix', Prefix); if MaxPage > 0 then MediaWikiQueryAdd(Queries, 'aplimit', IntToStr(MaxPage)); if Namespace >= 0 then MediaWikiQueryAdd(Queries, 'apnamespace', IntToStr(Namespace)); if RedirFilter = mwfAllPageFilterRedirect then MediaWikiQueryAdd(Queries, 'apfilterredir', 'redirects') else if RedirFilter = mwfAllPageFilterNonRedirect then MediaWikiQueryAdd(Queries, 'apfilterredir', 'nonredirects'); if LangFilter = mwfAllPageLangOnly then MediaWikiQueryAdd(Queries, 'apfilterlanglinks', 'withlanglinks') else if LangFilter = mwfAllPageLangNone then MediaWikiQueryAdd(Queries, 'apfilterlanglinks', 'withoutlanglinks'); if MinSize >= 0 then MediaWikiQueryAdd(Queries, 'apminsize', IntToStr(MinSize)); if MaxSize >= 0 then MediaWikiQueryAdd(Queries, 'apmaxsize', IntToStr(MaxSize)); if ProtectionFilter = mwfAllPageProtectionEdit then MediaWikiQueryAdd(Queries, 'apprtype', 'edit') else if ProtectionFilter = mwfAllPageProtectionMove then MediaWikiQueryAdd(Queries, 'apprtype', 'move'); if LevelFilter = mwfAllPageLevelAutoConfirmed then MediaWikiQueryAdd(Queries, 'apprlevel', 'autoconfirmed') else if LevelFilter = mwfAllPageLevelSysops then MediaWikiQueryAdd(Queries, 'apprlevel', 'sysop'); if Direction = mwfAllPageAscending then MediaWikiQueryAdd(Queries, 'apdir', 'ascending') else MediaWikiQueryAdd(Queries, 'apdir', 'descending'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryAllPageParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiAllPageInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, AllPages, Page, Continue: TJclSimpleXMLElem; Index: Integer; PageTitle, PageID, PageNamespace: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; AllPages := Query.Items.ItemNamed['allpages']; SetLength(Infos, AllPages.Items.Count); for Index := 0 to AllPages.Items.Count - 1 do begin Page := AllPages.Items.Item[Index]; PageTitle := Page.Properties.ItemNamed['title']; PageID := Page.Properties.ItemNamed['pageid']; PageNamespace := Page.Properties.ItemNamed['ns']; Infos[Index].PageTitle := PageTitle.Value; Infos[Index].PageID := PageID.IntValue; Infos[Index].PageNamespace := PageNamespace.IntValue; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiQueryAllLinkAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxLink: Integer; Namespace: Integer; Flags: TMediaWikiAllLinkInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'alllinks'); if Prefix <> '' then MediaWikiQueryAdd(Queries, 'alprefix', Prefix); if MaxLink > 0 then MediaWikiQueryAdd(Queries, 'allimit', IntToStr(MaxLink)); if Namespace >= 0 then MediaWikiQueryAdd(Queries, 'alnamespace', IntToStr(Namespace)); if mwfLinkUnique in Flags then MediaWikiQueryAdd(Queries, 'alunique') else if mwfLinkIncludePageID in Flags then MediaWikiQueryAdd(Queries, 'alprop', 'ids'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryAllLinkParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiAllLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, AllLinks, Link, Continue: TJclSimpleXMLElem; Index: Integer; LinkTitle, PageID, LinkNamespace: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; AllLinks := Query.Items.ItemNamed['alllinks']; SetLength(Infos, AllLinks.Items.Count); for Index := 0 to AllLinks.Items.Count - 1 do begin Link := AllLinks.Items.Item[Index]; LinkTitle := Link.Properties.ItemNamed['title']; PageID := Link.Properties.ItemNamed['fromid']; LinkNamespace := Link.Properties.ItemNamed['ns']; Infos[Index].LinkTitle := LinkTitle.Value; Infos[Index].PageID := PageID.IntValue; Infos[Index].LinkNamespace := LinkNamespace.IntValue; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiQueryAllCategoryAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix: string; MaxCategory: Integer; Flags: TMediaWikiAllCategoryInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'allcategories'); if Prefix <> '' then MediaWikiQueryAdd(Queries, 'acprefix', Prefix); if MaxCategory > 0 then MediaWikiQueryAdd(Queries, 'aclimit', IntToStr(MaxCategory)); if mwfCategoryDescending in Flags then MediaWikiQueryAdd(Queries, 'acdir', 'descending'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryAllCategoryParseXmlResult(XML: TJclSimpleXML; Infos: TStrings; out ContinueInfo: TMediaWikiContinueInfo); var Query, AllCategories, Category, Continue: TJclSimpleXMLElem; Index: Integer; begin Infos.Clear; XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; AllCategories := Query.Items.ItemNamed['allcategories']; Infos.BeginUpdate; try for Index := 0 to AllCategories.Items.Count - 1 do begin Category := AllCategories.Items.Item[Index]; Infos.Add(Category.Value); end; finally Infos.EndUpdate end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiQueryAllUserAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const Prefix, Group: string; MaxUser: Integer; Flags: TMediaWikiAllUserInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'allusers'); if Prefix <> '' then MediaWikiQueryAdd(Queries, 'auprefix', Prefix); if Group <> '' then MediaWikiQueryAdd(Queries, 'augroup', Group); if MaxUser > 0 then MediaWikiQueryAdd(Queries, 'aulimit', IntToStr(MaxUser)); if mwfIncludeUserEditCount in Flags then MediaWikiQueryAdd(Queries, 'auprop', 'editcount'); if mwfIncludeUserGroups in Flags then MediaWikiQueryAdd(Queries, 'auprop', 'groups'); if mwfIncludeUserRegistration in Flags then MediaWikiQueryAdd(Queries, 'auprop', 'registration'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryAllUserParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiAllUserInfos; out ContinueInfo: TMediaWikiContinueInfo); var Continue, Query, AllUsers, User, Groups, Group: TJclSimpleXMLElem; I, J: Integer; Name, EditCount, Registration: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; AllUsers := Query.Items.ItemNamed['allusers']; SetLength(Infos, AllUsers.Items.Count); for I := 0 to AllUsers.Items.Count - 1 do begin User := AllUsers.Items.Item[I]; Name := User.Properties.ItemNamed['name']; EditCount := User.Properties.ItemNamed['editcount']; Registration := User.Properties.ItemNamed['registration']; Infos[I].UserName := Name.Value; Infos[I].UserEditCount := EditCount.IntValue; Infos[I].UserRegistration := StrISO8601ToDateTime(Registration.Value); Groups := User.Items.ItemNamed['groups']; SetLength(Infos[I].UserGroups, Groups.Items.Count); for J := 0 to Groups.Items.Count - 1 do begin Group := Groups.Items.Item[J]; Infos[I].UserGroups[J] := Group.Value; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiQueryBackLinkAdd(Queries: TStrings; const BackLinkTitle: string; const ContinueInfo: TMediaWikiContinueInfo; Namespace, MaxLink: Integer; Flags: TMediaWikiBackLinkInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'backlinks'); if BackLinkTitle <> '' then MediaWikiQueryAdd(Queries, 'bltitle', BackLinkTitle); if NameSpace >= 0 then MediaWikiQueryAdd(Queries, 'blnamespace', IntToStr(Namespace)); if MaxLink > 0 then MediaWikiQueryAdd(Queries, 'bllimit', IntToStr(MaxLink)); if mwfIncludeBackLinksFromRedirect in Flags then MediaWikiQueryAdd(Queries, 'blredirect'); if mwfExcludeBackLinkRedirect in Flags then MediaWikiQueryAdd(Queries, 'blfilterredir', 'nonredirects') else if mwfExcludeBackLinkNonRedirect in Flags then MediaWikiQueryAdd(Queries, 'blfilterredir', 'redirects') else MediaWikiQueryAdd(Queries, 'blfilterredir', 'all'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryBackLinkParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiBackLinkInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, BackLinks, BackLink, RedirLinks, RedirLink, Continue: TJclSimpleXMLElem; I, J, K: Integer; PageID, PageNamespace, PageTitle, Redirect, RedirPageID, RedirPageNamespace, RedirPageTitle: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; BackLinks := Query.Items.ItemNamed['backlinks']; SetLength(Infos, 0); for I := 0 to BackLinks.Items.Count - 1 do begin BackLink := BackLinks.Items.Item[I]; PageID := BackLink.Properties.ItemNamed['pageid']; PageNamespace := BackLink.Properties.ItemNamed['ns']; PageTitle := BackLink.Properties.ItemNamed['title']; XML.Options := XML.Options - [sxoAutoCreate]; Redirect := BackLink.Properties.ItemNamed['redirect']; XML.Options := XML.Options + [sxoAutoCreate]; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].BackLinkPageBasics.PageTitle := PageTitle.Value; Infos[K].BackLinkPageBasics.PageID := PageID.IntValue; Infos[K].BackLinkPageBasics.PageNamespace := PageNamespace.IntValue; if Assigned(Redirect) then Infos[K].BackLinkFlags := [mwfBackLinkIsRedirect] else Infos[K].BackLinkFlags := []; Infos[K].BackLinkRedirFromPageBasics.PageID := -1; Infos[K].BackLinkRedirFromPageBasics.PageNamespace := -1; Infos[K].BackLinkRedirFromPageBasics.PageTitle := ''; RedirLinks := BackLink.Items.ItemNamed['redirlinks']; for J := 0 to RedirLinks.Items.Count - 1 do begin RedirLink := RedirLinks.Items.Item[J]; RedirPageID := RedirLink.Properties.ItemNamed['pageid']; RedirPageNamespace := RedirLink.Properties.ItemNamed['ns']; RedirPageTitle := RedirLink.Properties.ItemNamed['title']; K := Length(Infos); SetLength(Infos, K + 1); Infos[K].BackLinkPageBasics.PageTitle := PageTitle.Value; Infos[K].BackLinkPageBasics.PageID := PageID.IntValue; Infos[K].BackLinkPageBasics.PageNamespace := PageNamespace.IntValue; Infos[K].BackLinkFlags := [mwfBackLinkIsRedirect, mwfBackLinkToRedirect]; Infos[K].BackLinkRedirFromPageBasics.PageID := RedirPageID.IntValue; Infos[K].BackLinkRedirFromPageBasics.PageNamespace := RedirPageNamespace.IntValue; Infos[K].BackLinkRedirFromPageBasics.PageTitle := RedirPageTitle.Value; end; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiQueryBlockAdd(Queries: TStrings; const ContinueInfo: TMediaWikiContinueInfo; const StartDateTime, StopDateTime: TDateTime; const BlockIDs, Users, IP: string; MaxBlock: Integer; Flags: TMediaWikiBlockInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'blocks'); if StartDateTime <> 0.0 then MediaWikiQueryAdd(Queries, 'bkstart', DateTimeToStrISO8601(StartDateTime)); if StopDateTime <> 0.0 then MediaWikiQueryAdd(Queries, 'bkend', DateTimeToStrISO8601(StopDateTime)); if BlockIDs <> '' then MediaWikiQueryAdd(Queries, 'bkids', BlockIDs); if Users <> '' then MediaWikiQueryAdd(Queries, 'bkusers', Users); if IP <> '' then MediaWikiQueryAdd(Queries, 'bkip', IP); if MaxBlock > 0 then MediaWikiQueryAdd(Queries, 'bklimit', IntToStr(MaxBlock)); if mwfBlockID in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'id'); if mwfBlockUser in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'user'); if mwfBlockByUser in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'by'); if mwfBlockDateTime in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'timestamp'); if mwfBlockExpiry in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'expiry'); if mwfBlockReason in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'reason'); if mwfBlockIPRange in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'range'); if mwfBlockFlags in Flags then MediaWikiQueryAdd(Queries, 'bkprop', 'flags'); if mwfBlockDescending in Flags then MediaWikiQueryAdd(Queries, 'bkdir', 'older') else MediaWikiQueryAdd(Queries, 'bkdir', 'newer'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryBlockParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiBlockInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, Blocks, Block, Continue: TJclSimpleXMLElem; Index: Integer; ID, User, UserID, By, ByUserID, TimeStamp, Expiry, Reason, RangeStart, RangeEnd, Automatic, AnonOnly, NoCreate, AutoBlock, NoEmail, Hidden: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; Blocks := Query.Items.ItemNamed['blocks']; SetLength(Infos, Blocks.Items.Count); for Index := 0 to Blocks.Items.Count - 1 do begin Block := Blocks.Items.Item[Index]; ID := Block.Properties.ItemNamed['id']; User := Block.Properties.ItemNamed['user']; UserID := Block.Properties.ItemNamed['userid']; By := Block.Properties.ItemNamed['by']; ByUserID := Block.Properties.ItemNamed['byuserid']; TimeStamp := Block.Properties.ItemNamed['timestamp']; Expiry := Block.Properties.ItemNamed['expiry']; Reason := Block.Properties.ItemNamed['reason']; RangeStart := Block.Properties.ItemNamed['rangestart']; RangeEnd := Block.Properties.ItemNamed['rangeend']; XML.Options := XML.Options - [sxoAutoCreate]; Automatic := Block.Properties.ItemNamed['automatic']; AnonOnly := Block.Properties.ItemNamed['anononly']; NoCreate := Block.Properties.ItemNamed['nocreate']; AutoBlock := Block.Properties.ItemNamed['autoblock']; NoEmail := Block.Properties.ItemNamed['noemail']; Hidden := Block.Properties.ItemNamed['hidden']; XML.Options := XML.Options + [sxoAutoCreate]; Infos[Index].BlockID := ID.IntValue; Infos[Index].BlockUser := User.Value; Infos[Index].BlockUserID := UserID.IntValue; Infos[Index].BlockByUser := By.Value; Infos[Index].BlockByUserID := ByUserID.IntValue; Infos[Index].BlockDateTime := StrISO8601ToDateTime(TimeStamp.Value); Infos[Index].BlockExpirityDateTime := StrISO8601ToDateTime(Expiry.Value); Infos[Index].BlockReason := Reason.Value; Infos[Index].BlockIPRangeStart := RangeStart.Value; Infos[Index].BlockIPRangeStop := RangeEnd.Value; Infos[Index].BlockFlags := []; if Assigned(Automatic) then Include(Infos[Index].BlockFlags, mwfBlockAutomatic); if Assigned(AnonOnly) then Include(Infos[Index].BlockFlags, mwfBlockAnonymousEdits); if Assigned(NoCreate) then Include(Infos[Index].BlockFlags, mwfBlockNoAccountCreate); if Assigned(AutoBlock) then Include(Infos[Index].BlockFlags, mwfBlockAutomaticBlocking); if Assigned(NoEmail) then Include(Infos[Index].BlockFlags, mwfBlockNoEmail); if Assigned(Hidden) then Include(Infos[Index].BlockFlags, mwfBlockHidden); end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiQueryCategoryMemberAdd(Queries: TStrings; const CategoryTitle: string; const ContinueInfo: TMediaWikiContinueInfo; PageNameSpace: Integer; const StartDateTime, StopDateTime: TDateTime; const StartSortKey, StopSortKey: string; MaxCategoryMember: Integer; Flags: TMediaWikiCategoryMemberInfoFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'query'); MediaWikiQueryAdd(Queries, 'list', 'categorymembers'); if CategoryTitle <> '' then MediaWikiQueryAdd(Queries, 'cmtitle', CategoryTitle); if PageNamespace >= 0 then MediaWikiQueryAdd(Queries, 'cmnamespace', IntToStr(PageNamespace)); if StartDateTime <> 0.0 then begin MediaWikiQueryAdd(Queries, 'cmsort', 'timestamp'); MediaWikiQueryAdd(Queries, 'cmstart', DateTimeToStrISO8601(StartDateTime)); end; if StopDateTime <> 0.0 then MediaWikiQueryAdd(Queries, 'cmend', DateTimeToStrISO8601(StopDateTime)); if (StartSortKey <> '') and (StartDateTime = 0.0) and (StopDateTime = 0.0) then begin MediaWikiQueryAdd(Queries, 'cmsort', 'sortkey'); MediaWikiQueryAdd(Queries, 'cmstartsortkey', StartSortKey); end; if (StopSortKey <> '') and (StartDateTime = 0.0) and (StopDateTime = 0.0) then MediaWikiQueryAdd(Queries, 'cmendsortkey', StopSortKey); if MaxCategoryMember > 0 then MediaWikiQueryAdd(Queries, 'cmlimit', IntToStr(MaxCategoryMember)); if mwfCategoryMemberPageID in Flags then MediaWikiQueryAdd(Queries, 'cmprop', 'ids'); if mwfCategoryMemberPageTitle in Flags then MediaWikiQueryAdd(Queries, 'cmprop', 'title'); if mwfCategoryMemberPageDateTime in Flags then MediaWikiQueryAdd(Queries, 'cmprop', 'timestamp'); if mwfCategoryMemberPageSortKey in Flags then MediaWikiQueryAdd(Queries, 'cmprop', 'sortkey'); if mwfCategoryMemberDescending in Flags then MediaWikiQueryAdd(Queries, 'cmdir', 'asc') else MediaWikiQueryAdd(Queries, 'cmdir', 'desc'); MediaWikiQueryAdd(Queries, ContinueInfo); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiQueryCategoryMemberParseXmlResult(XML: TJclSimpleXML; out Infos: TMediaWikiCategoryMemberInfos; out ContinueInfo: TMediaWikiContinueInfo); var Query, CategoryMembers, CategoryMember, Continue: TJclSimpleXMLElem; Index: Integer; PageID, NS, Title, SortKey, TimeStamp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; Query := XML.Root.Items.ItemNamed['query']; CategoryMembers := Query.Items.ItemNamed['categorymembers']; SetLength(Infos, CategoryMembers.Items.Count); for Index := 0 to CategoryMembers.Items.Count - 1 do begin CategoryMember := CategoryMembers.Items.Item[Index]; PageID := CategoryMember.Properties.ItemNamed['pageid']; NS := CategoryMember.Properties.ItemNamed['ns']; Title := CategoryMember.Properties.ItemNamed['title']; SortKey := CategoryMember.Properties.ItemNamed['sortkey']; TimeStamp := CategoryMember.Properties.ItemNamed['timestamp']; Infos[Index].CategoryMemberPageBasics.PageID := PageID.IntValue; Infos[Index].CategoryMemberPageBasics.PageNamespace := NS.IntValue; Infos[Index].CategoryMemberPageBasics.PageTitle := Title.Value; Infos[Index].CategoryMemberDateTime := StrISO8601ToDateTime(TimeStamp.Value); Infos[Index].CategoryMemberSortKey := SortKey.Value; end; ContinueInfo.ParameterName := ''; ContinueInfo.ParameterValue := ''; // process continuation XML.Options := XML.Options - [sxoAutoCreate]; Continue := XML.Root.Items.ItemNamed['continue']; if not Assigned(Continue) then Exit; if Continue.Properties.Count = 0 then Exit; ContinueInfo.ParameterName := Continue.Properties.Item[0].Name; ContinueInfo.ParameterValue := Continue.Properties.Item[0].Value; end; procedure MediaWikiEditAdd(Queries: TStrings; const PageTitle, Section, Text, PrependText, AppendText, EditToken, Summary, MD5, CaptchaID, CaptchaWord: string; const BaseDateTime, StartDateTime: TDateTime; UndoRevisionID: TMediaWikiID; Flags: TMediaWikiEditFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'edit'); if PageTitle <> '' then MediaWikiQueryAdd(Queries, 'title', PageTitle); if Section <> '' then MediaWikiQueryAdd(Queries, 'section', Section); if Text <> '' then MediaWikiQueryAdd(Queries, 'text', Text); if PrependText <> '' then MediaWikiQueryAdd(Queries, 'prependtext', PrependText); if AppendText <> '' then MediaWikiQueryAdd(Queries, 'appendtext', AppendText); if EditToken <> '' then MediaWikiQueryAdd(Queries, 'token', EditToken); if Summary <> '' then MediaWikiQueryAdd(Queries, 'summary', Summary); if MD5 <> '' then MediaWikiQueryAdd(Queries, 'md5', MD5); if CaptchaID <> '' then MediaWikiQueryAdd(Queries, 'captchaid', CaptchaID); if CaptchaWord <> '' then MediaWikiQueryAdd(Queries, 'captchaword', CaptchaWord); if BaseDateTime <> 0.0 then MediaWikiQueryAdd(Queries, 'basetimestamp', DateTimeToStrISO8601(BaseDateTime)); if StartDateTime <> 0.0 then MediaWikiQueryAdd(Queries, 'starttimestamp', DateTimeToStrISO8601(StartDateTime)); if UndoRevisionID >= 0 then MediaWikiQueryAdd(Queries, 'undo', IntToStr(UndoRevisionID)); if mwfEditMinor in Flags then MediaWikiQueryAdd(Queries, 'minor', 'true'); if mwfEditNotMinor in Flags then MediaWikiQueryAdd(Queries, 'notminor', 'true'); if mwfEditBot in Flags then MediaWikiQueryAdd(Queries, 'bot'); if mwfEditAlwaysRecreate in Flags then MediaWikiQueryAdd(Queries, 'recreate'); if mwfEditMustCreate in Flags then MediaWikiQueryAdd(Queries, 'createonly'); if mwfEditMustExist in Flags then MediaWikiQueryAdd(Queries, 'nocreate'); if mwfEditWatchAdd in Flags then MediaWikiQueryAdd(Queries, 'watchlist', 'watch') else if mwfEditWatchRemove in Flags then MediaWikiQueryAdd(Queries, 'watchlist', 'unwatch') else if mwfEditWatchNoChange in Flags then MediaWikiQueryAdd(Queries, 'watchlist', 'nochange') else MediaWikiQueryAdd(Queries, 'watchlist', 'preferences'); if mwfEditUndoAfterRev in Flags then MediaWikiQueryAdd(Queries, 'undoafter'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiEditParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiEditInfo); var EditNode, CaptchaNode: TJclSimpleXMLElem; ResultProp, TitleProp, PageIDProp, OldRevIDProp, NewRevIDProp, CaptchaTypeProp, CaptchaURLProp, CaptchaMimeProp, CaptchaIDProp, CaptchaQuestionProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; EditNode := XML.Root.Items.ItemNamed['edit']; CaptchaNode := EditNode.Items.ItemNamed['captcha']; ResultProp := EditNode.Properties.ItemNamed['result']; TitleProp := EditNode.Properties.ItemNamed['title']; PageIDProp := EditNode.Properties.ItemNamed['pageid']; OldRevIDProp := EditNode.Properties.ItemNamed['oldrevid']; NewRevIDProp := EditNode.Properties.ItemNamed['newrevid']; CaptchaTypeProp := CaptchaNode.Properties.ItemNamed['type']; CaptchaURLProp := CaptchaNode.Properties.ItemNamed['url']; CaptchaMimeProp := CaptchaNode.Properties.ItemNamed['mime']; CaptchaIDProp := CaptchaNode.Properties.ItemNamed['id']; CaptchaQuestionProp := CaptchaNode.Properties.ItemNamed['question']; Info.EditSuccess := ResultProp.Value = 'Success'; Info.EditPageTitle := TitleProp.Value; Info.EditPageID := PageIDProp.IntValue; Info.EditOldRevID := OldRevIDProp.IntValue; Info.EditNewRevID := NewRevIDProp.IntValue; Info.EditCaptchaType := CaptchaTypeProp.Value; Info.EditCaptchaURL := CaptchaURLProp.Value; Info.EditCaptchaMime := CaptchaMimeProp.Value; Info.EditCaptchaID := CaptchaIDProp.Value; Info.EditCaptchaQuestion := CaptchaQuestionProp.Value; end; procedure MediaWikiMoveAdd(Queries: TStrings; const FromPageTitle, ToPageTitle, MoveToken, Reason: string; FromPageID: TMediaWikiID; Flags: TMediaWikiMoveFlags; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'move'); if FromPageTitle <> '' then MediaWikiQueryAdd(Queries, 'from', FromPageTitle); if ToPageTitle <> '' then MediaWikiQueryAdd(Queries, 'to', ToPageTitle); if MoveToken <> '' then MediaWikiQueryAdd(Queries, 'token', MoveToken); if Reason <> '' then MediaWikiQueryAdd(Queries, 'reason', Reason); if (FromPageID >= 0) and (FromPageTitle = '') then MediaWikiQueryAdd(Queries, 'fromid', IntToStr(FromPageID)); if mwfMoveTalk in Flags then MediaWikiQueryAdd(Queries, 'movetalk'); if mwfMoveSubPages in Flags then MediaWikiQueryAdd(Queries, 'movesubpages'); if mwfMoveNoRedirect in Flags then MediaWikiQueryAdd(Queries, 'noredirect'); if mwfMoveAddToWatch in Flags then MediaWikiQueryAdd(Queries, 'watch') else if mwfMoveNoWatch in Flags then MediaWikiQueryAdd(Queries, 'unwatch'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiMoveParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiMoveInfo); var MoveNode: TJclSimpleXMLElem; FromProp, ToProp, ReasonProp, TalkFromProp, TalkToProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; MoveNode := XML.Root.Items.ItemNamed['move']; FromProp := MoveNode.Properties.ItemNamed['from']; ToProp := MoveNode.Properties.ItemNamed['to']; ReasonProp := MoveNode.Properties.ItemNamed['reason']; TalkFromProp := MoveNode.Properties.ItemNamed['talkfrom']; TalkToProp := MoveNode.Properties.ItemNamed['talkto']; Info.MoveSuccess := ToProp.Value <> ''; Info.MoveFromPage := FromProp.Value; Info.MoveToPage := ToProp.Value; Info.MoveReason := ReasonProp.Value; Info.MoveFromTalk := TalkFromProp.Value; Info.MoveToTalk := TalkToProp.Value; end; procedure MediaWikiDeleteAdd(Queries: TStrings; const PageTitle, DeleteToken, Reason: string; PageID: TMediaWikiID; Suppress: Boolean; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'delete'); if PageTitle <> '' then MediaWikiQueryAdd(Queries, 'title', PageTitle); if DeleteToken <> '' then MediaWikiQueryAdd(Queries, 'token', DeleteToken); if Reason <> '' then MediaWikiQueryAdd(Queries, 'reason', Reason); if Suppress then MediaWikiQueryAdd(Queries, 'suppress', 'true'); if (PageID >= 0) and (PageTitle = '') then MediaWikiQueryAdd(Queries, 'pageid', IntToStr(PageID)); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiDeleteParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiDeleteInfo); var DeleteNode: TJclSimpleXMLElem; TitleProp, ReasonProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; DeleteNode := XML.Root.Items.ItemNamed['delete']; TitleProp := DeleteNode.Properties.ItemNamed['title']; ReasonProp := DeleteNode.Properties.ItemNamed['reason']; Info.DeleteSuccess := TitleProp.Value <> ''; Info.DeletePage := TitleProp.Value; Info.DeleteReason := ReasonProp.Value; end; procedure MediaWikiDeleteRevisionAdd(Queries: TStrings; const PageTitle, DeleteToken, Reason: string; PageID, RevisionID: TMediaWikiID; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'deleterevision'); if PageTitle <> '' then MediaWikiQueryAdd(Queries, 'title', PageTitle); if DeleteToken <> '' then MediaWikiQueryAdd(Queries, 'token', DeleteToken); if Reason <> '' then MediaWikiQueryAdd(Queries, 'reason', Reason); if (PageID >= 0) and (PageTitle = '') then MediaWikiQueryAdd(Queries, 'pageid', IntToStr(PageID)); if (RevisionID >= 0) then MediaWikiQueryAdd(Queries, 'revid', IntToStr(RevisionID)); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiDeleteRevisionParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiDeleteRevisionInfo); var DeleteRevisionNode: TJclSimpleXMLElem; TitleProp, RevIDProp, ReasonProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; DeleteRevisionNode := XML.Root.Items.ItemNamed['deleterevision']; TitleProp := DeleteRevisionNode.Properties.ItemNamed['title']; RevIDProp := DeleteRevisionNode.Properties.ItemNamed['revid']; ReasonProp := DeleteRevisionNode.Properties.ItemNamed['reason']; Info.DeleteRevisionSuccess := TitleProp.Value <> ''; Info.DeleteRevisionPage := TitleProp.Value; Info.DeleteRevisionID := RevIDProp.IntValue; Info.DeleteRevisionReason := ReasonProp.Value; end; procedure MediaWikiUploadAdd(Queries: TStrings; const FileName, Comment, Text, EditToken: string; Flags: TMediaWikiUploadFlags; Content: TStream; const URL: string; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'upload'); if FileName <> '' then MediaWikiQueryAdd(Queries, 'filename', FileName); if Comment <> '' then MediaWikiQueryAdd(Queries, 'comment', Comment); if Text <> '' then MediaWikiQueryAdd(Queries, 'text', Text); if EditToken <> '' then MediaWikiQueryAdd(Queries, 'token', EditToken); if mwfUploadWatch in Flags then MediaWikiQueryAdd(Queries, 'watch'); if mwfUploadIgnoreWarnings in Flags then MediaWikiQueryAdd(Queries, 'ignorewarnings'); if Assigned(Content) then MediaWikiQueryAdd(Queries, 'file', FileName, False, Content) else MediaWikiQueryAdd(Queries, 'url', URL); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiUploadParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiUploadInfo); var UploadNode, ImageNode: TJclSimpleXMLElem; ResultProp, FileNameProp, TimeStampProp, UserProp, SizeProp, WidthProp, HeightProp, URLProp, DescriptionURLProp, CommentProp, SHA1Prop, MetaDataProp, MimeProp, BitDepthProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; UploadNode := XML.Root.Items.ItemNamed['upload']; ImageNode := UploadNode.Items.ItemNamed['imageinfo']; ResultProp := UploadNode.Properties.ItemNamed['result']; FileNameProp := UploadNode.Properties.ItemNamed['filename']; TimeStampProp := ImageNode.Properties.ItemNamed['timestamp']; UserProp := ImageNode.Properties.ItemNamed['user']; SizeProp := ImageNode.Properties.ItemNamed['size']; WidthProp := ImageNode.Properties.ItemNamed['width']; HeightProp := ImageNode.Properties.ItemNamed['height']; URLProp := ImageNode.Properties.ItemNamed['url']; DescriptionURLProp := ImageNode.Properties.ItemNamed['descriptionurl']; CommentProp := ImageNode.Properties.ItemNamed['comment']; SHA1Prop := ImageNode.Properties.ItemNamed['sha1']; MetaDataProp := ImageNode.Properties.ItemNamed['metadata']; MimeProp := ImageNode.Properties.ItemNamed['mime']; BitDepthProp := ImageNode.Properties.ItemNamed['bitdepth']; Info.UploadSuccess := ResultProp.Value = 'Success'; Info.UploadFileName := FileNameProp.Value; Info.UploadImageDataTime := StrISO8601ToDateTime(TimeStampProp.Value); Info.UploadImageUser := UserProp.Value; Info.UploadImageSize := SizeProp.IntValue; Info.UploadImageWidth := WidthProp.IntValue; Info.UploadImageHeight := HeightProp.IntValue; Info.UploadImageURL := URLProp.Value; Info.UploadImageDescriptionURL := DescriptionURLProp.Value; Info.UploadImageComment := CommentProp.Value; Info.UploadImageSHA1 := SHA1Prop.Value; Info.UploadImageMetaData := MetaDataProp.Value; Info.UploadImageMime := MimeProp.Value; Info.UploadImageBitDepth := BitDepthProp.IntValue; end; procedure MediaWikiUserMergeAdd(Queries: TStrings; const OldUser, NewUser, Token: string; DeleteUser: Boolean; OutputFormat: TMediaWikiOutputFormat); begin MediaWikiQueryAdd(Queries, 'action', 'usermerge'); MediaWikiQueryAdd(Queries, 'token', Token); if OldUser <> '' then MediaWikiQueryAdd(Queries, 'olduser', OldUser); if NewUser <> '' then MediaWikiQueryAdd(Queries, 'newuser', NewUser); if (DeleteUser) then MediaWikiQueryAdd(Queries, 'deleteuser', 'true') else MediaWikiQueryAdd(Queries, 'deleteuser', 'false'); MediaWikiQueryAdd(Queries, 'format', MediaWikiOutputFormats[OutputFormat]); end; procedure MediaWikiUserMergeParseXmlResult(XML: TJclSimpleXML; out Info: TMediaWikiUserMergeInfo); var UserMergeNode: TJclSimpleXMLElem; ResultProp, OldUserProp, NewUserProp: TJclSimpleXMLProp; begin XML.Options := XML.Options + [sxoAutoCreate]; UserMergeNode := XML.Root.Items.ItemNamed['usermerge']; ResultProp := UserMergeNode.Properties.ItemNamed['result']; OldUserProp := UserMergeNode.Properties.ItemNamed['olduser']; NewUserProp := UserMergeNode.Properties.ItemNamed['newuser']; Info.UserMergeSuccess := ResultProp.Value = 'Success'; Info.UserMergeOldUser := OldUserProp.Value; Info.UserMergeNewUser := NewUserProp.Value; end; end.
unit ResidentialSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, InternationalizerComponent; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidCurrBlock = 'CurrBlock'; tidCost = 'Cost'; tidROI = 'ROI'; const facStoppedByTycoon = $04; type TResidentialSheetHandler = class; TResidentialSheetViewer = class(TVisualControl) xfer_Name: TEdit; Label1: TLabel; Label2: TLabel; xfer_Rent: TPercentEdit; xfer_Creator: TLabel; Label4: TLabel; xfer_invCrimeRes: TLabel; Label3: TLabel; Label5: TLabel; xfer_invPollutionRes: TLabel; xfer_invPrivacy: TLabel; Label10: TLabel; xfer_InvBeauty: TLabel; Label6: TLabel; xfer_MetaFacilityName: TLabel; Label7: TLabel; Rent: TLabel; Label12: TLabel; xfer_Maintenance: TPercentEdit; Maintenance: TLabel; btnClose: TFramedButton; btnRepair: TFramedButton; btnDemolish: TFramedButton; NameLabel: TLabel; Label8: TLabel; lbCost: TLabel; Label9: TLabel; lbROI: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure xfer_NameKeyPress(Sender: TObject; var Key: Char); procedure xfer_RentChange(Sender: TObject); procedure xfer_MaintenanceChange(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure xfer_RentMoveBar(Sender: TObject); procedure btnRepairClick(Sender: TObject); procedure btnDemolishClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TResidentialSheetHandler; end; TResidentialSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TResidentialSheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; private procedure SetContainer(aContainer : IPropertySheetContainerHandler); override; function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure SetName(str : string); procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedSetRent(const parms : array of const); procedure threadedSetMaint(const parms : array of const); end; var ResidentialSheetViewer: TResidentialSheetViewer; function ResidentialSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, CacheCommon, Protocol, MathUtils, SheetUtils, Literals; {$R *.DFM} // TResidentialSheetHandler procedure TResidentialSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin inherited; end; function TResidentialSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TResidentialSheetViewer.Create(Owner); fControl.fHandler := self; //fContainer.ChangeHeight(130); result := fControl; end; function TResidentialSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TResidentialSheetHandler.RenderProperties(Properties : TStringList); var trouble : string; roi : integer; roiStr : string; begin LockWindowUpdate(fControl.Handle); try FiveViewUtils.SetViewProp(fControl, Properties); trouble := Properties.Values[tidTrouble]; fOwnsFacility := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId] ); if fOwnsFacility then begin try fCurrBlock := StrToInt(Properties.Values[tidCurrBlock]); except fCurrBlock := 0; end; fControl.NameLabel.Visible := false; fControl.xfer_Name.Visible := true; fControl.xfer_Name.Enabled := true; end else begin fCurrBlock := 0; fControl.xfer_Name.Visible := false; fControl.NameLabel.Caption := fControl.xfer_Name.Text; fControl.NameLabel.Visible := true; end; try if (trouble <> '') and (StrToInt(trouble) and facStoppedByTycoon <> 0) then fControl.btnClose.Text := GetLiteral('Literal71') else fControl.btnClose.Text := GetLiteral('Literal72'); except end; fControl.xfer_Rent.Enabled := fOwnsFacility; fControl.xfer_Maintenance.Enabled := fOwnsFacility; fControl.btnClose.Enabled := fOwnsFacility; fControl.btnDemolish.Enabled := fOwnsFacility; fControl.btnRepair.Enabled := fOwnsFacility; try roiStr := Properties.Values[tidROI]; if roiStr <> '' then begin roi := round(StrToFloat(roiStr)); if roi = 0 then fControl.lbROI.Caption := GetLiteral('Literal73') else if roi > 0 then fControl.lbROI.Caption := GetFormattedLiteral('Literal74', [Properties.Values[tidROI]]) else fControl.lbROI.Caption := GetLiteral('Literal75'); end else fControl.lbROI.Caption := GetLiteral('Literal76'); except fControl.lbROI.Caption := GetLiteral('Literal77'); end; fControl.lbCost.Caption := MathUtils.FormatMoneyStr(Properties.Values[tidCost]); finally LockWindowUpdate(0); end; end; procedure TResidentialSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; FiveViewUtils.GetViewPropNames(fControl, Names); Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); Names.Add(tidCost); Names.Add(tidROI); Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); end; end; procedure TResidentialSheetHandler.Clear; begin inherited; fControl.NameLabel.Caption := NA; fControl.xfer_Name.Text := ''; fControl.xfer_Name.Enabled := false; fControl.xfer_MetaFacilityName.Caption := NA; fControl.xfer_Creator.Caption := NA; fControl.lbCost.Caption := NA; fControl.lbROI.Caption := NA; fControl.xfer_InvBeauty.Caption := NA; fControl.xfer_InvCrimeRes.Caption := NA; fControl.xfer_InvPollutionRes.Caption := NA; fControl.xfer_InvPrivacy.Caption := NA; fControl.xfer_Rent.Value := 0; fControl.xfer_Rent.Enabled := false; fControl.xfer_Maintenance.Value := 0; fControl.xfer_Maintenance.Enabled := false; fControl.Rent.Caption := NA; fControl.Maintenance.Caption := NA; fControl.btnClose.Enabled := false; fControl.btnDemolish.Enabled := false; fControl.btnRepair.Enabled := false; end; procedure TResidentialSheetHandler.SetName(str : string); var MSProxy : OleVariant; begin try try fControl.Cursor := crHourGlass; MSProxy := fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) and fOwnsFacility and CacheCommon.ValidName(str) then MSProxy.Name := str else Beep; finally fControl.Cursor := crDefault; end; except end; end; procedure TResidentialSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; Prop : TStringList; begin try Update := parms[1].vInteger; try if Update = fLastUpdate then Prop := fContainer.GetProperties(Names) else Prop := nil; finally Names.Free; end; if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; except end; end; procedure TResidentialSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then RenderProperties(Prop); finally Prop.Free; end; except end; end; procedure TResidentialSheetHandler.threadedSetRent(const parms : array of const); var Proxy : OleVariant; block : integer; begin block := parms[0].vInteger; if block <> 0 then try Proxy := fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo(block); Proxy.WaitForAnswer := false; Proxy.Rent := parms[1].vInteger; end; except end; end; procedure TResidentialSheetHandler.threadedSetMaint(const parms : array of const); var Proxy : OleVariant; block : integer; begin block := parms[0].vInteger; if block <> 0 then try Proxy := fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo(block); Proxy.WaitForAnswer := false; Proxy.Maintenance := parms[1].vInteger; end; except end; end; // ResidentialSheetHandlerCreator function ResidentialSheetHandlerCreator : IPropertySheetHandler; begin result := TResidentialSheetHandler.Create; end; // TResidentialSheetViewer procedure TResidentialSheetViewer.xfer_NameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then fHandler.SetName(xfer_Name.Text) else if Key in NotAllowedChars then Key := #0; end; procedure TResidentialSheetViewer.xfer_RentMoveBar(Sender: TObject); begin Rent.Caption := IntToStr(xfer_Rent.Value) + '%'; end; procedure TResidentialSheetViewer.xfer_RentChange(Sender: TObject); var rent : integer; begin rent := xfer_Rent.Value; if fHandler.fOwnsFacility then Threads.Fork(fHandler.threadedSetRent, priNormal, [fHandler.fCurrBlock, rent]); end; procedure TResidentialSheetViewer.xfer_MaintenanceChange(Sender: TObject); var maint : integer; begin maint := xfer_Maintenance.Value; if fHandler.fOwnsFacility then Threads.Fork(fHandler.threadedSetMaint, priNormal, [fHandler.fCurrBlock, maint]); end; procedure TResidentialSheetViewer.btnCloseClick(Sender: TObject); begin if btnClose.Text = GetLiteral('Literal78') then begin fHandler.fContainer.GetMSProxy.Stopped := true; btnClose.Text := GetLiteral('Literal79'); end else begin fHandler.fContainer.GetMSProxy.Stopped := false; btnClose.Text := GetLiteral('Literal80'); end end; procedure TResidentialSheetViewer.btnRepairClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo(fHandler.fCurrBlock); Proxy.RdoRepair; end; except end; end; procedure TResidentialSheetViewer.btnDemolishClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo('World'); if Proxy.RDODelFacility(fHandler.GetContainer.GetXPos, fHandler.GetContainer.GetYPos) <> NOERROR then Beep; end; except end; end; procedure TResidentialSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; initialization SheetHandlerRegistry.RegisterSheetHandler('ResGeneral', ResidentialSheetHandlerCreator); end.
unit System.Tray.Helper; interface uses System.Classes, System.SysUtils, JvTrayIcon, System.Classes.Helper, vcl.Forms, WinApi.Windows, System.SysUtils.Helper, vcl.Menus.helpers, vcl.Menus; type IJvTrayIcon = Interface ['{BF0C33CF-49C8-4A21-BCB1-A352CDA29CB6}'] End; TJvTrayIconHelper = class(TJvTrayIcon, IJvTrayIcon) private FPopUp: TPopupmenu; FForm: TForm; FOldOnShow: TNotifyEvent; FClosing: boolean; procedure DoOnShow(sender: TObject); procedure SetForm(const AForm: TForm); procedure SetClosing(const Value: boolean); public class function new: IJvTrayIcon; constructor create(AOwner: TComponent); override; function createItem(ACaption: string; AProc: TProc; AIdx: integer = -1) : TMenuItem; property Closing: boolean read FClosing write SetClosing; end; function CreateTrayIcon(AForm:TForm):TJvTrayIconHelper; implementation function CreateTrayIcon(AForm:TForm):TJvTrayIconHelper; begin result :=TJvTrayIconHelper.Create(AForm); end; { TJvTrayIconHelper } constructor TJvTrayIconHelper.create(AOwner: TComponent); begin inherited; FPopUp := TPopupmenu.create(self); if assigned(AOwner) and AOwner.InheritsFrom(TForm) then begin SetForm(TForm(AOwner)); end; FPopUp.AutoPopup := true; PopupMenu := FPopUp; SetWindowLong(Application.Handle,GWL_EXSTYLE,WS_EX_TOOLWINDOW); end; function TJvTrayIconHelper.createItem(ACaption: string; AProc: TProc; AIdx: integer): TMenuItem; begin FPopUp.CreateItemAnonimous(ACaption, AProc, AIdx); end; procedure TJvTrayIconHelper.DoOnShow(sender: TObject); begin if assigned(FOldOnShow) then FOldOnShow(sender); Active := true; if assigned(FForm) then begin FForm.WindowState := wsMinimized; end; ShowWindow(Application.Handle, SW_HIDE); end; class function TJvTrayIconHelper.new: IJvTrayIcon; begin result := TJvTrayIconHelper.create(nil); end; procedure TJvTrayIconHelper.SetClosing(const Value: boolean); begin FClosing := Value; end; procedure TJvTrayIconHelper.SetForm(const AForm: TForm); begin if FForm = AForm then exit; if assigned(FForm) then begin // desligar FPopUp.Items.Clear; FForm.OnShow := FOldOnShow; FForm := nil; end; FForm := AForm; FOldOnShow := FForm.OnShow; FForm.OnShow := DoOnShow; FPopUp.CreateItemAnonimous('&Abrir', procedure begin if assigned(FForm) then begin FForm.WindowState := wsNormal; FForm.Show; end; end); FPopUp.CreateItemAnonimous('&Minimizar', procedure begin if assigned(FForm) then FForm.WindowState := wsMinimized; end); FPopUp.AddSeparator(); FPopUp.CreateItemAnonimous('&Sair', procedure begin FClosing := true; if assigned(FForm) then FForm.Close; end); end; end.
unit tdADSIEnum; interface uses System.SysUtils, System.StrUtils, System.Classes, System.TypInfo, System.DateUtils, System.Math, System.SyncObjs, System.Generics.Collections, Winapi.Windows, Winapi.ActiveX, ActiveDs_TLB, MSXML2_TLB, JwaActiveDS, ADC.Types, ADC.DC, ADC.Attributes, ADC.ADObject, ADC.ADObjectList, ADC.Common, ADC.AD; type TADSIEnum = class(TThread) private FSyncObject: TCriticalSection; FProgressProc: TProgressProc; FExceptionProc: TExceptionProc; FProgressValue: Integer; FExceptionCode: ULONG; FExceptionMsg: string; FDomainDN: string; FDomainHostName: string; FAttrCatalog: TAttrCatalog; FAttributes: array of WideString; FOutList: TADObjectList<TADObject>; FObj: TADObject; FSearchRes: IDirectorySearch; FSearchHandle: PHandle; FMaxPwdAge_Secs: Int64; FMaxPwdAge_Days: Int64; procedure GetMaxPasswordAge; procedure SyncProgress; procedure SyncException; procedure Clear; protected destructor Destroy; override; procedure Execute; override; procedure DoProgress(AProgress: Integer); overload; procedure DoProgress; overload; procedure DoException(AMsg: string; ACode: ULONG); public constructor Create(ARootDSE: IADs; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); reintroduce; end; implementation { TADObjectInfoEnum } procedure TADSIEnum.Clear; begin if Terminated and (FOutList <> nil) then FOutList.Clear; FProgressProc := nil; FExceptionProc := nil; FProgressValue := 0; FExceptionCode := 0; FExceptionMsg := ''; FDomainDN := ''; FDomainHostName := ''; FMaxPwdAge_Secs := 0; FMaxPwdAge_Days := 0; FAttrCatalog := nil; FOutList := nil; FObj := nil; if Assigned(FSearchHandle) then FSearchRes.CloseSearchHandle(FSearchHandle); FSearchRes := nil; CoUninitialize; if FSyncObject <> nil then begin FSyncObject.Leave; FSyncObject := nil; end; end; constructor TADSIEnum.Create(ARootDSE: IADs; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean); var i: Integer; v: OleVariant; begin inherited Create(CreateSuspended); FreeOnTerminate := True; FSyncObject := ASyncObject; FProgressProc := AProgressProc; FExceptionProc := AExceptionProc; if ARootDSE = nil then begin DoException('No server binding.', 0); Self.Terminate; end else begin v := ARootDSE.Get('defaultNamingContext'); FDomainDN := VariantToStringWithDefault(v, ''); VariantClear(v); v := ARootDSE.Get('dnsHostName'); FDomainHostName := VariantToStringWithDefault(v, ''); VariantClear(v); FAttrCatalog := AAttrCatalog; FOutList := AOutList; SetLength(FAttributes, FAttrCatalog.Count); for i := 0 to FAttrCatalog.Count - 1 do begin if FAttrCatalog[i]^.Name = '' then FAttributes[i] := '<Undefined>' else FAttributes[i] := FAttrCatalog[i]^.Name; end; { Заполняем свойства для плавающего окна } i := FAttrCatalog.Count; SetLength(FAttributes, Length(FAttributes) + 3); FAttributes[i] := 'displayName'; FAttributes[i + 1] := 'title'; FAttributes[i + 2] := 'physicalDeliveryOfficeName'; end; end; destructor TADSIEnum.Destroy; begin inherited; end; procedure TADSIEnum.DoProgress; begin FProgressValue := FProgressValue + 1; Synchronize(SyncProgress); end; procedure TADSIEnum.Execute; var objFilter: string; hRes: HRESULT; SearchPrefs: array of ADS_SEARCHPREF_INFO; begin CoInitialize(nil); if FSyncObject <> nil then if not FSyncObject.TryEnter then begin FSyncObject := nil; FOutList := nil; Self.OnTerminate := nil; Self.Terminate; end; if Terminated then begin Clear; Exit; end; FOutList.Clear; try { Извлекаем срок действия пароля из политики домена } GetMaxPasswordAge; { Осуществляем поиск в домене атрибутов и их значений } hRes := ADsOpenObject( PChar('LDAP://' + FDomainHostName + '/' + FDomainDN), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IDirectorySearch, @FSearchRes ); if Succeeded(hRes) then begin SetLength(SearchPrefs, 3); with SearchPrefs[0] do begin dwSearchPref := ADS_SEARCHPREF_PAGESIZE; vValue.dwType := ADSTYPE_INTEGER; vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADC_SEARCH_PAGESIZE; end; with SearchPrefs[1] do begin dwSearchPref := ADS_SEARCHPREF_PAGED_TIME_LIMIT; vValue.dwType := ADSTYPE_INTEGER; vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 60; end; with SearchPrefs[2] do begin dwSearchPref := ADS_SEARCHPREF_SEARCH_SCOPE; vValue.dwType := ADSTYPE_INTEGER; vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := ADS_SCOPE_SUBTREE; end; { Если раскомментировать параметры ниже, то необходимо увеличить } { размер массива параметров SearchPrefs до необходимого } // with SearchPrefs[3] do // begin // dwSearchPref := ADS_SEARCHPREF_TOMBSTONE; // vValue.dwType := ADSTYPE_BOOLEAN; // vValue.__MIDL____MIDL_itf_ads_0000_00000000.Boolean := 1; // end; // with SearchPrefs[4] do // begin // dwSearchPref := ADS_SEARCHPREF_EXTENDED_DN; // vValue.dwType := ADSTYPE_INTEGER; // vValue.__MIDL____MIDL_itf_ads_0000_00000000.Integer := 1; // end; hRes := FSearchRes.SetSearchPreference(SearchPrefs[0], Length(SearchPrefs)); objFilter := '(|' + '(&(objectCategory=person)(objectClass=user))' + '(objectCategory=group)' + '(objectCategory=computer)' + // '(isDeleted=*)' + ')'; DoProgress(0); FSearchRes.ExecuteSearch( PWideChar(objFilter), PWideChar(@FAttributes[0]), Length(FAttributes), Pointer(FSearchHandle) ); { Обработка объектов } hRes := FSearchRes.GetNextRow(FSearchHandle); while (hRes <> S_ADS_NOMORE_ROWS) do begin if Terminated then Break; FObj := TADObject.Create; FObj.WriteProperties( FSearchRes, FSearchHandle, FAttrCatalog, FDomainHostName, FMaxPwdAge_Secs ); FOutList.Add(FObj); DoProgress; hRes := FSearchRes.GetNextRow(Pointer(FSearchHandle)); end; end; Clear; except on E: Exception do begin DoException(E.Message, hRes); Clear; end; end; end; procedure TADSIEnum.DoProgress(AProgress: Integer); begin FProgressValue := AProgress; Synchronize(SyncProgress); end; procedure TADSIEnum.GetMaxPasswordAge; const ONE_HUNDRED_NANOSECOND = 0.000000100; SECONDS_IN_DAY = 86400; var hRes: HRESULT; pDomain: IADs; v: OleVariant; d: LARGE_INTEGER; begin hRes := ADsOpenObject( PChar('LDAP://' + FDomainHostName + '/' + FDomainDN), nil, nil, ADS_SECURE_AUTHENTICATION or ADS_SERVER_BIND, IID_IADs, @pDomain ); if Succeeded(hRes) then begin v := pDomain.Get('maxPwdAge'); d.HighPart := (IDispatch(v) as IADsLargeInteger).HighPart; d.LowPart := (IDispatch(v) as IADsLargeInteger).LowPart; VariantClear(v); if d.LowPart = 0 then begin FMaxPwdAge_Secs := 0; FMaxPwdAge_Days := 0; end else begin d.QuadPart := d.HighPart; d.QuadPart := d.QuadPart shl 32; d.QuadPart := d.QuadPart + d.LowPart; FMaxPwdAge_Secs := Abs(Round(d.QuadPart * ONE_HUNDRED_NANOSECOND)); FMaxPwdAge_Days := Round(FMaxPwdAge_Secs / SECONDS_IN_DAY); end; end; pDomain := nil; end; procedure TADSIEnum.SyncException; begin if Assigned(FExceptionProc) then FExceptionProc(FExceptionMsg, FExceptionCode); end; procedure TADSIEnum.SyncProgress; begin if Assigned(FProgressProc) then FProgressProc(FObj, FProgressValue); end; procedure TADSIEnum.DoException(AMsg: string; ACode: ULONG); begin FExceptionCode := ACode; FExceptionMsg := AMsg; Synchronize(SyncException); end; end.
program ConsoleMenu; {$APPTYPE CONSOLE} {$MODE DELPHI} {$R *.res} uses SysUtils, Windows, Quick.Commons, Quick.Console; type TTest = class class procedure Option1; class procedure Option2; class procedure Option3; class procedure Option4; class procedure Option5; end; var conmenu : TConsoleMenu; Test : TTest; menuop : TConsoleMenuOption; i : Integer; { TTest } class procedure TTest.Option1; begin coutXY(10,10,'Option 1 pressed',etInfo); end; class procedure TTest.Option2; begin coutXY(10,10,'Option 2 pressed',etInfo); end; class procedure TTest.Option3; begin coutXY(10,10,'Option 3 pressed',etInfo); end; class procedure TTest.Option4; begin coutXY(10,10,'Option 4 pressed',etInfo); end; class procedure TTest.Option5; begin coutXY(10,10,'Option 5 pressed',etInfo); end; begin Application.Title:='Console Menu'; try conmenu := TConsoleMenu.Create; menuop.Caption := 'Option 1'; menuop.Key := VK_F1; menuop.OnKeyPressed := Test.Option1; conmenu.AddMenu(menuop); conmenu.AddMenu('Option 2',VK_F2,Test.Option2); conmenu.AddMenu('Option 3',VK_F3,Test.Option3); conmenu.AddMenu('Option 4',VK_F4,Test.Option4); conmenu.AddMenu('Option 5',VK_F5,Test.Option5); for i := 0 to 30 do writeln('hola que tal'); conmenu.WaitForKeys; conmenu.Free; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Cloth * Implements cloth mesh *********************************************************************************************************************** } Unit TERRA_Cloth; {$I terra.inc} { TODO - add stick and slider constraints GPU ARRAY - 1 texture with each particle position x,y,z, mass - 2 texture with each particle last position x,y,z, fixed - 3 texture with each particle acceleration x,y,z - 4 texture with contrainsts A,B, rest distance } Interface Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} TERRA_Utils, TERRA_GraphicsManager, TERRA_Texture, TERRA_Quaternion, TERRA_Classes, TERRA_Math, TERRA_BoundingBox, TERRA_Vector3D, TERRA_Vector2D, TERRA_Ray, TERRA_Particles, TERRA_VerletParticle, TERRA_Color, TERRA_Shader; Type VerletCloth = Class(TERRAObject) Protected _Shader:Shader; _ParticleSystem:VerletSystem; _Vertices:Array Of ParticleVertex; _VertexCount:Integer; _Triangles:Array Of Triangle; _TriangleCount:Integer; _SourceMesh:Pointer; _NormalIndices:Array Of IntegerArray; _Normals:Array Of Vector3D; { A private method used by drawShaded() and addWindForcesForTriangle() to retrieve the normal vector of the triangle defined by the position of the particles p1, p2, and p3. The magnitude of the normal vector is equal to the area of the parallelogram defined by p1, p2 and p3 } Function calcTriangleNormal(A,B,C:Integer):Vector3D; // A private method used by windForce() to calcualte the wind force for a single triangle defined by p1,p2,p3 Procedure AddWindForcesForTriangle(A,B,C:Integer; direction:Vector3D); Procedure UpdateNormals; Public //This is a important constructor for the entire system of particles and constraints*/ Constructor Create(SourceMeshGroup:Pointer); Procedure Release; { drawing the cloth as a smooth shaded (and colored according to column) OpenGL triangular mesh Called from the display() method The cloth is seen as consisting of triangles for four particles in the grid as follows: (x,y) *--* (x+1,y) | /| |/ | (x,y+1) *--* (x+1,y+1) } Procedure Render(Instance:Pointer); Function GetBoundingBox:BoundingBox; Procedure AddForce(F:Vector3D); // used to add wind forces to all particles, is added for each triangle since the final force is proportional to the triangle area as seen from the wind direction Procedure WindForce(direction:Vector3D); Procedure BallCollision(center:Vector3D; Radius:Single); Procedure PinPoint(Index:Integer); Function Intersect(Const R:Ray; Var T:Single):Boolean; End; Implementation Uses {$IFDEF DEBUG_GL}TERRA_DebugGL{$ELSE}TERRA_GL{$ENDIF}, TERRA_ResourceManager, TERRA_Matrix, TERRA_Mesh, TERRA_MeshInstance, TERRA_Lights; Function VerletCloth.calcTriangleNormal(A,B,C:Integer):Vector3D; Var VA,VB:Vector3D; p1,p2,p3:PVerletParticle; Begin P1 := _ParticleSystem.GetParticle(A); P2 := _ParticleSystem.GetParticle(B); P3 := _ParticleSystem.GetParticle(C); VA := VectorSubtract(P2.Position, P1.Position); VB := VectorSubtract(P3.Position, P1.Position); Result := VectorCross(VA,VB); Result.Normalize; End; Procedure VerletCloth.addWindForcesForTriangle(A,B,C:Integer; direction:Vector3D); Var D, Force, Normal:Vector3D; p1,p2,p3:PVerletParticle; Begin P1 := _ParticleSystem.GetParticle(A); P2 := _ParticleSystem.GetParticle(B); P3 := _ParticleSystem.GetParticle(C); Normal := CalcTriangleNormal(A,B,C); D := Normal; D.Normalize; Force := VectorScale(Normal, VectorDot(D, direction)); p1.addForce(force); p2.addForce(force); p3.addForce(force); End; Constructor VerletCloth.Create(SourceMeshGroup:Pointer); Var Pos:Vector3D; P:PVerletParticle; I,J:Integer; Group:MeshGroup; V:MeshVertex; T:Triangle; MinDist:Single; Begin _SourceMesh := SourceMeshGroup; Group := SourceMeshGroup; _Shader := ResourceManager.Instance.GetShader('cloth'); _VertexCount := Group.VertexCount; SetLength(_Vertices, _VertexCount); For I:=0 To Pred(_VertexCount) Do Begin V := Group.GetVertex(I); _Vertices[I].Position := V.Position; // insert particle in column x at y'th row _Vertices[I].UV := V.TextureCoords; _Vertices[I].Normal := V.Normal; _Vertices[I].Color := ColorWhite; End; _ParticleSystem := VerletSystem.Create(@(_Vertices[0]), _VertexCount, False); // create geometry _TriangleCount := Group.TriangleCount; SetLength(_Triangles, _TriangleCount); SetLength(_NormalIndices, _VertexCount); SetLength(_Normals, _TriangleCount); For I:=0 To Pred(Group.TriangleCount) Do Begin T := Group.GetTriangle(I); _Triangles[I].A := T.A; _Triangles[I].B := T.B; _Triangles[I].C := T.C; _NormalIndices[T.A].Add(I); _NormalIndices[T.B].Add(I); _NormalIndices[T.C].Add(I); End; T := Group.GetTriangle(0); MinDist := _Vertices[T.A].Position.Distance(_Vertices[T.B].Position)* 1.2; For I:=0 To Pred(_VertexCount) Do For J:=0 To Pred(_VertexCount) Do If (I<>J) And (_Vertices[I].Position.Distance(_Vertices[J].Position)<=MinDist) Then _ParticleSystem.AddConstraint(I, J); End; Procedure VerletCloth.Release; Begin ReleaseObject(_ParticleSystem); End; Procedure VerletCloth.PinPoint(Index:Integer); Var P:PVerletParticle; Begin P := _ParticleSystem.GetParticle(Index); // P.offsetPos(VectorCreate(0.0,-0.5,0.0)); // moving the particle a bit towards the center, to make it hang more natural - because I like it ;) P.Fixed := True; End; Function VerletCloth.GetBoundingBox:BoundingBox; Begin Result := _ParticleSystem.BoundingBox; End; Procedure VerletCloth.UpdateNormals; Var I,J,N:Integer; Begin For I:=0 To Pred(_TriangleCount) Do _Normals[I] := calcTriangleNormal(_Triangles[I].A, _Triangles[I].B, _Triangles[I].C); //create smooth per particle normals by adding up all the (hard) triangle normals that each particle is part of For I:=0 To Pred(_VertexCount) Do For J := 0 To Pred(_NormalIndices[I].Count) Do Begin N := _NormalIndices[I].Items[J]; _Vertices[I].Normal.Add(_Normals[N]); End; End; Procedure VerletCloth.Render(Instance:Pointer); Var Normal, Color:Vector3D; I,J:Integer; Group:MeshGroup; Begin Group := MeshGroup(Self._SourceMesh); { If (Assigned(LightManager.Instance.ActiveShadowMap)) Then Begin LightManager.Instance.ActiveShadowMap.SetShader(False); End Else} Begin Texture.Bind(Group.DiffuseMap, 0); Shader.Bind(_Shader); Shader.SetUniform('diffuseMap',0); GraphicsManager.Instance.ActiveViewport.Camera.SetUniforms; End; Shader.SetUniform('modelMatrix', MeshInstance(Instance).Transform); _ParticleSystem.Update; UpdateNormals; {$IFNDEF MOBILE} glDisable(GL_CULL_FACE); glBegin(GL_TRIANGLES); For I:=0 To Pred(_TriangleCount) Do For J:=0 To 2 Do Begin glNormal3fv(@_Vertices[_Triangles[I].Indices[J]].Normal); glColor4fv(@_Vertices[_Triangles[I].Indices[J]].Color); glMultiTexCoord2fv(GL_TEXTURE0, @_Vertices[_Triangles[I].Indices[J]].UV); glVertex3fv(@_Vertices[_Triangles[I].Indices[J]].Position); End; glEnd; glEnable(GL_CULL_FACE); {$ENDIF} End; Procedure VerletCloth.AddForce(F:Vector3D); Begin _ParticleSystem.AddForce(F); End; Procedure VerletCloth.WindForce(direction:Vector3D); Var I:Integer; Begin For I:=0 To Pred(_TriangleCount) Do AddWindForcesForTriangle(_Triangles[I].A, _Triangles[I].B, _Triangles[I].C, direction); End; Procedure VerletCloth.BallCollision(center:Vector3D; Radius:Single); Begin _ParticleSystem.BallCollision(Center, Radius); End; Function VerletCloth.Intersect(Const R:Ray; Var T:Single):Boolean; Begin Result := False; End; End.
unit DBButton; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.Buttons, Data.DB, Vcl.Dialogs, System.UITypes; type TAcao = (taNovo, taExcluir, taEditar, taGravar, taCancelar); TDBButton = class(TBitBtn) private FAcao: TAcao; FDataSource: TDataSource; procedure SetAcao(const Value: TAcao); procedure SetDataSource(const Value: TDataSource); { Private declarations } protected { Protected declarations } procedure Notification(AComponente: TComponent; AOperation: TOperation); override; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure Click; override; published { Published declarations } property Acao: TAcao read FAcao write SetAcao; property DataSource: TDataSource read FDataSource write SetDataSource; end; procedure Register; implementation procedure Register; begin RegisterComponents('componenteOW', [TDBButton]); end; { TDBButton } procedure TDBButton.Click; begin if Assigned(FDataSource) then begin case FAcao of taNovo: FDataSource.DataSet.Insert; taExcluir: if (MessageDlg('Confirma a exclusão?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then FDataSource.DataSet.Delete; taEditar: FDataSource.DataSet.Edit; taGravar: FDataSource.DataSet.Post; taCancelar: FDataSource.DataSet.Cancel; end; end; inherited; end; constructor TDBButton.Create(AOwner: TComponent); begin inherited; FAcao := taNovo; Caption := 'Novo'; end; procedure TDBButton.Notification(AComponente: TComponent; AOperation: TOperation); begin inherited; if (AComponente = FDataSource) and (AOperation = opRemove) then FDataSource := nil; end; procedure TDBButton.SetAcao(const Value: TAcao); begin FAcao := Value; case FAcao of taNovo: Caption := 'Novo'; taExcluir: Caption := 'Excluir'; taEditar: Caption := 'Editar'; taGravar: Caption := 'Gravar'; taCancelar: Caption := 'Cancelar'; end; end; procedure TDBButton.SetDataSource(const Value: TDataSource); begin FDataSource := Value; end; end.
unit uStrUtils; interface type TSplitResult = array of string; function LastPos(const SubStr, Source: string; const IgnoreCase: Boolean = True): Integer; function Explode(const Count: Integer; Source: string): TSplitResult; overload; function Explode(const cSeparator, vString: string): TSplitResult; overload; function Implode(const cSeparator: string; const cArray: TSplitResult): string; overload; function Implode(const cArray: TSplitResult): string; overload; function StrRight(S: string; i: Integer): string; function StrLeft(S: string; i: Integer): string; implementation uses SysUtils; function LastPos(const SubStr, Source: string; const IgnoreCase: Boolean): Integer; var Found, Len, Pos: Integer; begin Pos := Length(Source); Len := Length(SubStr); Found := 0; while (Pos > 0) and (Found = 0) do begin if IgnoreCase then begin if (LowerCase(Copy(Source, Pos, Len)) = LowerCase(SubStr)) then Found := Pos; Dec(Pos); end else begin if Copy(Source, Pos, Len) = SubStr then Found := Pos; Dec(Pos); end; end; Result := Found; end; // Разделить строку на подстроки разделителем D function Explode(const Count: Integer; Source: string): TSplitResult; overload; var A: Integer; S, P: string; begin S := Source; SetLength(Result, 0); while (Length(S) > Count) do begin SetLength(Result, Length(Result) + 1); P := Copy(S, 1, Count); A := LastPos(#32, P); P := Copy(S, 1, A); Result[High(Result)] := P; Delete(S, 1, A); end; SetLength(Result, Length(Result) + 1); Result[High(Result)] := S; end; function Explode(const cSeparator, vString: string): TSplitResult; overload; var i: Integer; S: string; begin S := vString; SetLength(Result, 0); i := 0; while Pos(cSeparator, S) > 0 do begin SetLength(Result, Length(Result) + 1); Result[i] := Copy(S, 1, Pos(cSeparator, S) - 1); inc(i); S := Copy(S, Pos(cSeparator, S) + Length(cSeparator), Length(S)); end; SetLength(Result, Length(Result) + 1); Result[i] := Copy(S, 1, Length(S)); end; // Соединить массив TSplitResult в одну строку, аналог Join function Implode(const cSeparator: string; const cArray: TSplitResult): string; overload; var i: Integer; begin Result := ''; for i := 0 to Length(cArray) - 1 do begin Result := Result + cSeparator + cArray[i]; end; System.Delete(Result, 1, Length(cSeparator)); end; function Implode(const cArray: TSplitResult): string; overload; begin Result := Implode('', cArray); end; // Копия строки справа function StrRight(S: string; i: Integer): string; var l: Integer; begin l := Length(S); Result := Copy(S, l - i + 1, l); end; // Копия строки слева function StrLeft(S: string; i: Integer): string; begin Result := Copy(S, 1, i); end; end.
{ Subroutine SST_W_C_ARMODE_POP * * Restore the current array identifier interpretation mode to what it was before * the last call to SST_W_C_ARMODE_PUSH. This also pops the stack frame from the * stack. } module sst_w_c_ARMODE_POP; define sst_w_c_armode_pop; %include 'sst_w_c.ins.pas'; procedure sst_w_c_armode_pop; {restore previous array interpretation mode} var f_p: frame_array_p_t; {points to stack frame with old data} begin util_stack_last_frame (sst_stack, sizeof(f_p^), f_p); {get pointer to old state} addr_cnt_ar := f_p^.addr_cnt; {restore state from stack frame} array_mode := f_p^.mode; util_stack_pop (sst_stack, sizeof(f_p^)); {remove old frame from stack} %debug; write (sst_stack^.last_p^.curr_adr, ' '); %debug; writeln ('ARMODE POP'); end;
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.15 11/12/2004 11:30:18 AM JPMugaas Expansions for IPv6. Rev 1.14 11/11/04 12:05:32 PM RLebeau Updated ReceiveBuffer() to set AMSec to IdTimeoutInfinite when the ReceiveTimeout property is 0 Rev 1.13 11/7/2004 11:33:30 PM JPMugaas Now uses Connect, Disconnect, Send, and Receive similarly to the TCP Clients. This should prevent unneeded DNS name to IP address conversions that SendTo was doing. Rev 1.12 7/21/04 3:33:10 PM RLebeau Updated TIdUDPBase.ReceiveString() to use new BytesToString() parameters Rev 1.11 09/06/2004 00:29:56 CCostelloe Kylix 3 patch Rev 1.10 2004.02.03 4:17:00 PM czhower For unit name changes. Rev 1.9 21.1.2004 ã. 12:31:00 DBondzhev Fix for Indy source. Workaround for dccil bug now it can be compiled using Compile instead of build Rev 1.7 10/26/2003 12:30:18 PM BGooijen DotNet Rev 1.6 10/24/2003 5:18:36 PM BGooijen Removed boolean shortcutting from .GetActive Rev 1.5 10/22/2003 04:40:58 PM JPMugaas Should compile with some restored functionality. Still not finished. Rev 1.4 10/19/2003 9:34:30 PM BGooijen SetSocketOption Rev 1.3 2003.10.11 9:58:48 PM czhower Started on some todos Rev 1.2 2003.10.11 5:52:10 PM czhower -VCL fixes for servers -Chain suport for servers (Super core) -Scheduler upgrades -Full yarn support Rev 1.1 2003.09.30 1:23:08 PM czhower Stack split for DotNet Rev 1.0 11/13/2002 09:02:06 AM JPMugaas } unit IdUDPBase; interface {$I IdCompilerDefines.inc} //here to flip FPC into Delphi mode uses IdComponent, IdGlobal, IdException, IdSocketHandle; const ID_UDP_BUFFERSIZE = 8192; type TIdUDPBase = class(TIdComponent) protected FBinding: TIdSocketHandle; FBufferSize: Integer; FDsgnActive: Boolean; FHost: String; FPort: TIdPort; FReceiveTimeout: Integer; FReuseSocket: TIdReuseSocket; FIPVersion: TIdIPVersion; // FBroadcastEnabled: Boolean; procedure BroadcastEnabledChanged; dynamic; procedure CloseBinding; virtual; function GetActive: Boolean; virtual; procedure InitComponent; override; procedure SetActive(const Value: Boolean); procedure SetBroadcastEnabled(const AValue: Boolean); function GetBinding: TIdSocketHandle; virtual; abstract; procedure Loaded; override; function GetIPVersion: TIdIPVersion; virtual; procedure SetIPVersion(const AValue: TIdIPVersion); virtual; function GetHost : String; virtual; procedure SetHost(const AValue : String); virtual; function GetPort : TIdPort; virtual; procedure SetPort(const AValue : TIdPort); virtual; property Host: string read GetHost write SetHost; property Port: TIdPort read GetPort write SetPort; public destructor Destroy; override; // property Binding: TIdSocketHandle read GetBinding; procedure Broadcast(const AData: string; const APort: TIdPort; const AIP: String = ''; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF} ); overload; procedure Broadcast(const AData: TIdBytes; const APort: TIdPort; const AIP: String = ''); overload; function ReceiveBuffer(var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; AMSec: Integer = IdTimeoutDefault): integer; overload; virtual; function ReceiveBuffer(var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion; const AMSec: Integer = IdTimeoutDefault): integer; overload; virtual; function ReceiveBuffer(var ABuffer : TIdBytes; const AMSec: Integer = IdTimeoutDefault): Integer; overload; virtual; function ReceiveString(const AMSec: Integer = IdTimeoutDefault; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF} ): string; overload; function ReceiveString(var VPeerIP: string; var VPeerPort: TIdPort; const AMSec: Integer = IdTimeoutDefault; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF} ): string; overload; procedure Send(const AHost: string; const APort: TIdPort; const AData: string; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF} ); procedure SendBuffer(const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion; const ABuffer : TIdBytes); overload; virtual; procedure SendBuffer(const AHost: string; const APort: TIdPort; const ABuffer: TIdBytes); overload; virtual; // property ReceiveTimeout: Integer read FReceiveTimeout write FReceiveTimeout default IdTimeoutInfinite; property ReuseSocket: TIdReuseSocket read FReuseSocket write FReuseSocket default rsOSDependent; published property Active: Boolean read GetActive write SetActive Default False; property BufferSize: Integer read FBufferSize write FBufferSize default ID_UDP_BUFFERSIZE; property BroadcastEnabled: Boolean read FBroadcastEnabled write SetBroadcastEnabled default False; property IPVersion: TIdIPVersion read GetIPVersion write SetIPVersion default ID_DEFAULT_IP_VERSION; end; EIdUDPException = Class(EIdException); EIdUDPReceiveErrorZeroBytes = class(EIdUDPException); implementation uses IdStackConsts, IdStack, SysUtils; { TIdUDPBase } procedure TIdUDPBase.Broadcast(const AData: string; const APort: TIdPort; const AIP: String = ''; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}); begin Binding.Broadcast(AData, APort, AIP, AByteEncoding{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}); end; procedure TIdUDPBase.Broadcast(const AData: TIdBytes; const APort: TIdPort; const AIP: String = ''); begin Binding.Broadcast(AData, APort, AIP); end; procedure TIdUDPBase.BroadcastEnabledChanged; begin if Assigned(FBinding) then begin FBinding.BroadcastEnabled := BroadcastEnabled; end; end; procedure TIdUDPBase.CloseBinding; begin FreeAndNil(FBinding); end; destructor TIdUDPBase.Destroy; begin Active := False; //double check that binding gets freed. //sometimes possible that binding is allocated, but active=false CloseBinding; inherited Destroy; end; function TIdUDPBase.GetActive: Boolean; begin Result := FDsgnActive; if not Result then begin if Assigned(FBinding) then begin Result := FBinding.HandleAllocated; end; end; end; function TIdUDPBase.GetHost: String; begin Result := FHost; end; function TIdUDPBase.GetIPVersion: TIdIPVersion; begin Result := FIPVersion; end; function TIdUDPBase.GetPort: TIdPort; begin Result := FPort; end; procedure TIdUDPBase.InitComponent; begin inherited InitComponent; BufferSize := ID_UDP_BUFFERSIZE; FReceiveTimeout := IdTimeoutInfinite; FReuseSocket := rsOSDependent; FIPVersion := ID_DEFAULT_IP_VERSION; end; procedure TIdUDPBase.Loaded; var b: Boolean; begin inherited Loaded; b := FDsgnActive; FDsgnActive := False; Active := b; end; function TIdUDPBase.ReceiveBuffer(var ABuffer : TIdBytes; const AMSec: Integer = IdTimeoutDefault): Integer; var VoidIP: string; VoidPort: TIdPort; VoidIPVer: TIdIPVersion; begin Result := ReceiveBuffer(ABuffer, VoidIP, VoidPort, VoidIPVer, AMSec); end; function TIdUDPBase.ReceiveBuffer(var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; AMSec: Integer = IdTimeoutDefault): integer; var VoidIPVer : TIdIPVersion; begin Result := ReceiveBuffer(ABuffer, VPeerIP, VPeerPort, VoidIPVer, AMSec); // GBSDStack.CheckForSocketError(Result); end; function TIdUDPBase.ReceiveBuffer(var ABuffer : TIdBytes; var VPeerIP: string; var VPeerPort: TIdPort; var VIPVersion: TIdIPVersion; const AMSec: Integer = IdTimeoutDefault): integer; var LMSec : Integer; begin if AMSec = IdTimeoutDefault then begin if ReceiveTimeOut = 0 then begin LMSec := IdTimeoutInfinite; end else begin LMSec := ReceiveTimeOut; end; end else begin LMSec := AMSec; end; if not Binding.Readable(LMSec) then begin Result := 0; VPeerIP := ''; {Do not Localize} VPeerPort := 0; Exit; end; Result := Binding.RecvFrom(ABuffer, VPeerIP, VPeerPort, VIPVersion); end; function TIdUDPBase.ReceiveString(var VPeerIP: string; var VPeerPort: TIdPort; const AMSec: Integer = IdTimeoutDefault; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF} ): string; var i: Integer; LBuffer : TIdBytes; begin SetLength(LBuffer, BufferSize); i := ReceiveBuffer(LBuffer, VPeerIP, VPeerPort, AMSec); Result := BytesToString(LBuffer, 0, i, AByteEncoding{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}); end; function TIdUDPBase.ReceiveString(const AMSec: Integer = IdTimeoutDefault; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}): string; var VoidIP: string; VoidPort: TIdPort; begin Result := ReceiveString(VoidIP, VoidPort, AMSec, AByteEncoding{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}); end; procedure TIdUDPBase.Send(const AHost: string; const APort: TIdPort; const AData: string; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF} ); begin SendBuffer(AHost, APort, ToBytes(AData, AByteEncoding{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF})); end; procedure TIdUDPBase.SendBuffer(const AHost: string; const APort: TIdPort; const ABuffer: TIdBytes); begin SendBuffer(AHost, APort, IPVersion, ABuffer); end; procedure TIdUDPBase.SendBuffer(const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion; const ABuffer: TIdBytes); var LIP : String; begin LIP := GStack.ResolveHost(AHost, AIPVersion); Binding.SendTo(LIP, APort, ABuffer,AIPVersion); end; procedure TIdUDPBase.SetActive(const Value: Boolean); begin if Active <> Value then begin if not (IsDesignTime or IsLoading) then begin if Value then begin GetBinding; end else begin CloseBinding; end; end else begin // don't activate at designtime (or during loading of properties) {Do not Localize} FDsgnActive := Value; end; end; end; procedure TIdUDPBase.SetBroadcastEnabled(const AValue: Boolean); begin if FBroadCastEnabled <> AValue then begin FBroadcastEnabled := AValue; if Active then begin BroadcastEnabledChanged; end; end; end; procedure TIdUDPBase.SetHost(const AValue: String); begin FHost := Avalue; end; procedure TIdUDPBase.SetIPVersion(const AValue: TIdIPVersion); begin FIPVersion := AValue; end; procedure TIdUDPBase.SetPort(const AValue: TIdPort); begin FPort := AValue; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clHttpHeader; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clUtils, clHeaderFieldList; type TclHttpEntityHeader = class(TPersistent) private FCacheControl: string; FProxyConnection: string; FConnection: string; FContentEncoding: string; FLastModified: string; FContentType: string; FContentLanguage: string; FContentVersion: string; FContentLength: string; FExpires: string; FDate: string; FExtraFields: TStrings; FTransferEncoding: string; FBoundary: string; FUpdateCount: Integer; FKnownFields: TStrings; FOnChanged: TNotifyEvent; FCharSet: string; procedure SetCacheControl(const Value: string); procedure SetConnection(const Value: string); procedure SetContentEncoding(const Value: string); procedure SetContentLanguage(const Value: string); procedure SetContentLength(const Value: string); procedure SetContentType(const Value: string); procedure SetContentVersion(const Value: string); procedure SetDate(const Value: string); procedure SetExpires(const Value: string); procedure SetExtraFields(const Value: TStrings); procedure SetLastModified(const Value: string); procedure SetProxyConnection(const Value: string); procedure SetTransferEncoding(const Value: string); procedure SetBoundary(const Value: string); procedure Changed; procedure DoStringListChanged(Sender: TObject); procedure SetCharSet(const Value: string); protected procedure SetListChangedEvent(AList: TStrings); procedure RegisterField(const AField: string); procedure RegisterFields; virtual; procedure InternalParseHeader(AFieldList: TclHeaderFieldList); virtual; procedure InternalAssignHeader(AFieldList: TclHeaderFieldList); virtual; procedure ParseContentType(AFieldList: TclHeaderFieldList); virtual; procedure AssignContentType(AFieldList: TclHeaderFieldList); virtual; procedure DoCreate; virtual; public constructor Create; destructor Destroy; override; procedure Clear; virtual; procedure Assign(Source: TPersistent); override; procedure ParseHeader(AHeader: TStrings); procedure AssignHeader(AHeader: TStrings); procedure Update; procedure BeginUpdate; procedure EndUpdate; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; published property Boundary: string read FBoundary write SetBoundary; property CharSet: string read FCharSet write SetCharSet; property CacheControl: string read FCacheControl write SetCacheControl; property Connection: string read FConnection write SetConnection; property ContentEncoding: string read FContentEncoding write SetContentEncoding; property ContentLanguage: string read FContentLanguage write SetContentLanguage; property ContentLength: string read FContentLength write SetContentLength; property ContentType: string read FContentType write SetContentType; property ContentVersion: string read FContentVersion write SetContentVersion; property Date: string read FDate write SetDate; property Expires: string read FExpires write SetExpires; property LastModified: string read FLastModified write SetLastModified; property ProxyConnection: string read FProxyConnection write SetProxyConnection; property TransferEncoding: string read FTransferEncoding write SetTransferEncoding; property ExtraFields: TStrings read FExtraFields write SetExtraFields; end; TclHttpRequestHeader = class(TclHttpEntityHeader) private FReferer: string; FAcceptEncoding: string; FAccept: string; FUserAgent: string; FAcceptLanguage: string; FAcceptCharSet: string; FAuthorization: string; FProxyAuthorization: string; FRange: string; FHost: string; procedure SetAccept(const Value: string); procedure SetAcceptCharSet(const Value: string); procedure SetAcceptEncoding(const Value: string); procedure SetAcceptLanguage(const Value: string); procedure SetAuthorization(const Value: string); procedure SetReferer(const Value: string); procedure SetUserAgent(const Value: string); procedure SetProxyAuthorization(const Value: string); procedure SetHost(const Value: string); procedure SetRange(const Value: string); protected procedure RegisterFields; override; procedure InternalParseHeader(AFieldList: TclHeaderFieldList); override; procedure InternalAssignHeader(AFieldList: TclHeaderFieldList); override; public procedure Clear; override; procedure Assign(Source: TPersistent); override; published property Accept: string read FAccept write SetAccept; property AcceptCharSet: string read FAcceptCharSet write SetAcceptCharSet; property AcceptEncoding: string read FAcceptEncoding write SetAcceptEncoding; property AcceptLanguage: string read FAcceptLanguage write SetAcceptLanguage; property Authorization: string read FAuthorization write SetAuthorization; property Host: string read FHost write SetHost; property ProxyAuthorization: string read FProxyAuthorization write SetProxyAuthorization; property Range: string read FRange write SetRange; property Referer: string read FReferer write SetReferer; property UserAgent: string read FUserAgent write SetUserAgent; end; TclHttpResponseHeader = class(TclHttpEntityHeader) private FAge: string; FAcceptRanges: string; FRetryAfter: string; FAuthenticate: TStrings; FAllow: string; FProxyAuthenticate: TStrings; FContentRange: string; FETag: string; FServer: string; FLocation: string; FContentDisposition: string; procedure SetAcceptRanges(const Value: string); procedure SetAge(const Value: string); procedure SetAllow(const Value: string); procedure SetAuthenticate(const Value: TStrings); procedure SetContentRange(const Value: string); procedure SetETag(const Value: string); procedure SetLocation(const Value: string); procedure SetProxyAuthenticate(const Value: TStrings); procedure SetRetryAfter(const Value: string); procedure SetServer(const Value: string); procedure GetAuthChallenge(AFieldList: TclHeaderFieldList; const AuthFieldName: string; AuthChallenge: TStrings); procedure SetAuthChallenge(AFieldList: TclHeaderFieldList; const AuthFieldName: string; AuthChallenge: TStrings); procedure SetContentDisposition(const Value: string); protected procedure RegisterFields; override; procedure InternalParseHeader(AFieldList: TclHeaderFieldList); override; procedure InternalAssignHeader(AFieldList: TclHeaderFieldList); override; procedure DoCreate; override; public destructor Destroy; override; procedure Clear; override; procedure Assign(Source: TPersistent); override; published property AcceptRanges: string read FAcceptRanges write SetAcceptRanges; property Age: string read FAge write SetAge; property Allow: string read FAllow write SetAllow; property Authenticate: TStrings read FAuthenticate write SetAuthenticate; property ContentRange: string read FContentRange write SetContentRange; property ContentDisposition: string read FContentDisposition write SetContentDisposition; property ETag: string read FETag write SetETag; property Location: string read FLocation write SetLocation; property ProxyAuthenticate: TStrings read FProxyAuthenticate write SetProxyAuthenticate; property RetryAfter: string read FRetryAfter write SetRetryAfter; property Server: string read FServer write SetServer; end; implementation { TclHttpEntityHeader } procedure TclHttpEntityHeader.Assign(Source: TPersistent); var Src: TclHttpEntityHeader; begin BeginUpdate(); try if (Source is TclHttpEntityHeader) then begin Src := (Source as TclHttpEntityHeader); Boundary := Src.Boundary; CharSet := Src.CharSet; CacheControl := Src.CacheControl; Connection := Src.Connection; ContentEncoding := Src.ContentEncoding; ContentLanguage := Src.ContentLanguage; ContentLength := Src.ContentLength; ContentType := Src.ContentType; ContentVersion := Src.ContentVersion; Date := Src.Date; Expires := Src.Expires; LastModified := Src.LastModified; ProxyConnection := Src.ProxyConnection; TransferEncoding := Src.TransferEncoding; ExtraFields := Src.ExtraFields; end else begin inherited Assign(Source); end; finally EndUpdate(); end; end; procedure TclHttpEntityHeader.AssignContentType(AFieldList: TclHeaderFieldList); begin AFieldList.AddField('Content-Type', ContentType); if (ContentType <> '') then begin AFieldList.AddFieldItem('Content-Type', 'boundary', Boundary); AFieldList.AddFieldItem('Content-Type', 'charset', CharSet); end; end; procedure TclHttpEntityHeader.AssignHeader(AHeader: TStrings); var fieldList: TclHeaderFieldList; begin fieldList := nil; AHeader.BeginUpdate(); try fieldList := TclHeaderFieldList.Create(); fieldList.Parse(0, AHeader); InternalAssignHeader(fieldList); finally fieldList.Free(); AHeader.EndUpdate(); end; end; procedure TclHttpEntityHeader.BeginUpdate; begin Inc(FUpdateCount); end; procedure TclHttpEntityHeader.Changed; begin if Assigned(OnChanged) then begin OnChanged(Self); end; end; procedure TclHttpEntityHeader.Clear; begin BeginUpdate(); try Boundary := ''; CharSet := ''; CacheControl := ''; Connection := ''; ContentEncoding := ''; ContentLanguage := ''; ContentLength := ''; ContentType := ''; ContentVersion := ''; Date := ''; Expires := ''; LastModified := ''; ProxyConnection := ''; TransferEncoding := ''; ExtraFields.Clear(); finally EndUpdate(); end; end; constructor TclHttpEntityHeader.Create; begin inherited Create(); DoCreate(); RegisterFields(); Clear(); end; destructor TclHttpEntityHeader.Destroy; begin FExtraFields.Free(); FKnownFields.Free(); inherited Destroy(); end; procedure TclHttpEntityHeader.DoCreate; begin FKnownFields := TStringList.Create(); FExtraFields := TStringList.Create(); SetListChangedEvent(FExtraFields); end; procedure TclHttpEntityHeader.DoStringListChanged(Sender: TObject); begin Update(); end; procedure TclHttpEntityHeader.EndUpdate; begin if (FUpdateCount > 0) then begin Dec(FUpdateCount); Update(); end; end; procedure TclHttpEntityHeader.InternalAssignHeader(AFieldList: TclHeaderFieldList); begin AFieldList.AddField('Content-Encoding', ContentEncoding); AFieldList.AddField('Content-Language', ContentLanguage); AFieldList.AddField('Content-Length', ContentLength); AFieldList.AddField('Content-Version', ContentVersion); AssignContentType(AFieldList); AFieldList.AddField('Date', Date); AFieldList.AddField('Expires', Expires); AFieldList.AddField('LastModified', LastModified); AFieldList.AddField('Transfer-Encoding', TransferEncoding); AFieldList.AddField('Cache-Control', CacheControl); AFieldList.AddField('Connection', Connection); AFieldList.AddField('Proxy-Connection', ProxyConnection); AFieldList.AddFields(ExtraFields); end; procedure TclHttpEntityHeader.InternalParseHeader(AFieldList: TclHeaderFieldList); begin CacheControl := AFieldList.GetFieldValue('Cache-Control'); Connection := AFieldList.GetFieldValue('Connection'); ContentEncoding := AFieldList.GetFieldValue('Content-Encoding'); ContentLanguage := AFieldList.GetFieldValue('Content-Language'); ContentLength := AFieldList.GetFieldValue('Content-Length'); ContentVersion := AFieldList.GetFieldValue('Content-Version'); Date := AFieldList.GetFieldValue('Date'); Expires := AFieldList.GetFieldValue('Expires'); LastModified := AFieldList.GetFieldValue('Last-Modified'); ProxyConnection := AFieldList.GetFieldValue('Proxy-Connection'); TransferEncoding := AFieldList.GetFieldValue('Transfer-Encoding'); ParseContentType(AFieldList); end; procedure TclHttpEntityHeader.ParseContentType(AFieldList: TclHeaderFieldList); var s: string; begin s := AFieldList.GetFieldValue('Content-Type'); ContentType := AFieldList.GetFieldValueItem(s, ''); Boundary := AFieldList.GetFieldValueItem(s, 'boundary'); CharSet := AFieldList.GetFieldValueItem(s, 'charset'); end; procedure TclHttpEntityHeader.ParseHeader(AHeader: TStrings); var i: Integer; FieldList: TclHeaderFieldList; begin FieldList := nil; BeginUpdate(); try Clear(); FieldList := TclHeaderFieldList.Create(); FieldList.Parse(0, AHeader); InternalParseHeader(FieldList); for i := 0 to FieldList.FieldList.Count - 1 do begin if (FindInStrings(FKnownFields, FieldList.FieldList[i]) < 0) then begin ExtraFields.Add(FieldList.GetFieldName(i) + ': ' + FieldList.GetFieldValue(i)); end; end; finally FieldList.Free(); EndUpdate(); end; end; procedure TclHttpEntityHeader.RegisterField(const AField: string); begin if (FindInStrings(FKnownFields, AField) < 0) then begin FKnownFields.Add(AField); end; end; procedure TclHttpEntityHeader.RegisterFields; begin RegisterField('Cache-Control'); RegisterField('Connection'); RegisterField('Content-Encoding'); RegisterField('Content-Language'); RegisterField('Content-Length'); RegisterField('Content-Type'); RegisterField('Content-Version'); RegisterField('Date'); RegisterField('Expires'); RegisterField('Last-Modified'); RegisterField('Proxy-Connection'); RegisterField('Transfer-Encoding'); end; procedure TclHttpEntityHeader.SetBoundary(const Value: string); begin if (FBoundary <> Value) then begin FBoundary := Value; Update(); FBoundary := Value; end; end; procedure TclHttpEntityHeader.SetCacheControl(const Value: string); begin if (FCacheControl <> Value) then begin FCacheControl := Value; Update(); end; end; procedure TclHttpEntityHeader.SetCharSet(const Value: string); begin if (FCharSet <> Value) then begin FCharSet := Value; Update(); end; end; procedure TclHttpEntityHeader.SetConnection(const Value: string); begin if (FConnection <> Value) then begin FConnection := Value; Update(); end; end; procedure TclHttpEntityHeader.SetContentEncoding(const Value: string); begin if (FContentEncoding <> Value) then begin FContentEncoding := Value; Update(); end; end; procedure TclHttpEntityHeader.SetContentLanguage(const Value: string); begin if (FContentLanguage <> Value) then begin FContentLanguage := Value; Update(); end; end; procedure TclHttpEntityHeader.SetContentLength(const Value: string); begin if (FContentLength <> Value) then begin FContentLength := Value; Update(); end; end; procedure TclHttpEntityHeader.SetContentType(const Value: string); begin if (FContentType <> Value) then begin FContentType := Value; Update(); end; end; procedure TclHttpEntityHeader.SetContentVersion(const Value: string); begin if (FContentVersion <> Value) then begin FContentVersion := Value; Update(); end; end; procedure TclHttpEntityHeader.SetDate(const Value: string); begin if (FDate <> Value) then begin FDate := Value; Update(); end; end; procedure TclHttpEntityHeader.SetExpires(const Value: string); begin if (FExpires <> Value) then begin FExpires := Value; Update(); end; end; procedure TclHttpEntityHeader.SetExtraFields(const Value: TStrings); begin FExtraFields.Assign(Value); end; procedure TclHttpEntityHeader.SetLastModified(const Value: string); begin if (FLastModified <> Value) then begin FLastModified := Value; Update(); end; end; procedure TclHttpEntityHeader.SetListChangedEvent(AList: TStrings); begin (AList as TStringList).OnChange := DoStringListChanged; end; procedure TclHttpEntityHeader.SetProxyConnection(const Value: string); begin if (FProxyConnection <> Value) then begin FProxyConnection := Value; Update(); end; end; procedure TclHttpEntityHeader.SetTransferEncoding(const Value: string); begin if (FTransferEncoding <> Value) then begin FTransferEncoding := Value; Update(); end; end; procedure TclHttpEntityHeader.Update; begin if (FUpdateCount = 0) then begin Changed(); end; end; { TclHttpRequestHeader } procedure TclHttpRequestHeader.Assign(Source: TPersistent); var Src: TclHttpRequestHeader; begin BeginUpdate(); try inherited Assign(Source); if (Source is TclHttpRequestHeader) then begin Src := (Source as TclHttpRequestHeader); Accept := Src.Accept; AcceptCharSet := Src.AcceptCharSet; AcceptEncoding := Src.AcceptEncoding; AcceptLanguage := Src.AcceptLanguage; Authorization := Src.Authorization; Host := Src.Host; ProxyAuthorization := Src.ProxyAuthorization; Range := Src.Range; Referer := Src.Referer; UserAgent := Src.UserAgent; end; finally EndUpdate(); end; end; procedure TclHttpRequestHeader.InternalAssignHeader(AFieldList: TclHeaderFieldList); begin AFieldList.AddField('Accept', Accept); AFieldList.AddField('Accept-Charset', AcceptCharSet); AFieldList.AddField('Accept-Encoding', AcceptEncoding); AFieldList.AddField('Accept-Language', AcceptLanguage); AFieldList.AddField('Range', Range); AFieldList.AddField('Referer', Referer); AFieldList.AddField('Host', Host); AFieldList.AddField('User-Agent', UserAgent); AFieldList.AddField('Authorization', Authorization); AFieldList.AddField('Proxy-Authorization', ProxyAuthorization); inherited InternalAssignHeader(AFieldList); end; procedure TclHttpRequestHeader.Clear; begin BeginUpdate(); try inherited Clear(); Accept := '*/*'; AcceptCharSet := ''; AcceptEncoding := ''; AcceptLanguage := ''; Authorization := ''; Host := ''; ProxyAuthorization := ''; Range := ''; Referer := ''; UserAgent := ''; finally EndUpdate(); end; end; procedure TclHttpRequestHeader.SetAccept(const Value: string); begin if (FAccept <> Value) then begin FAccept := Value; Update(); end; end; procedure TclHttpRequestHeader.SetAcceptCharSet(const Value: string); begin if (FAcceptCharSet <> Value) then begin FAcceptCharSet := Value; Update(); end; end; procedure TclHttpRequestHeader.SetAcceptEncoding(const Value: string); begin if (FAcceptEncoding <> Value) then begin FAcceptEncoding := Value; Update(); end; end; procedure TclHttpRequestHeader.SetAcceptLanguage(const Value: string); begin if (FAcceptLanguage <> Value) then begin FAcceptLanguage := Value; Update(); end; end; procedure TclHttpRequestHeader.SetAuthorization(const Value: string); begin if (FAuthorization <> Value) then begin FAuthorization := Value; Update(); end; end; procedure TclHttpRequestHeader.SetHost(const Value: string); begin if (FHost <> Value) then begin FHost := Value; Update(); end; end; procedure TclHttpRequestHeader.SetProxyAuthorization(const Value: string); begin if (FProxyAuthorization <> Value) then begin FProxyAuthorization := Value; Update(); end; end; procedure TclHttpRequestHeader.SetRange(const Value: string); begin if (FRange <> Value) then begin FRange := Value; Update(); end; end; procedure TclHttpRequestHeader.SetReferer(const Value: string); begin if (FReferer <> Value) then begin FReferer := Value; Update(); end; end; procedure TclHttpRequestHeader.SetUserAgent(const Value: string); begin if (FUserAgent <> Value) then begin FUserAgent := Value; Update(); end; end; procedure TclHttpRequestHeader.InternalParseHeader(AFieldList: TclHeaderFieldList); begin inherited InternalParseHeader(AFieldList); Accept := AFieldList.GetFieldValue('Accept'); AcceptCharSet := AFieldList.GetFieldValue('Accept-Charset'); AcceptEncoding := AFieldList.GetFieldValue('Accept-Encoding'); AcceptLanguage := AFieldList.GetFieldValue('Accept-Language'); Authorization := AFieldList.GetFieldValue('Authorization'); Host := AFieldList.GetFieldValue('Host'); ProxyAuthorization := AFieldList.GetFieldValue('Proxy-Authorization'); Range := AFieldList.GetFieldValue('Range'); Referer := AFieldList.GetFieldValue('Referer'); UserAgent := AFieldList.GetFieldValue('User-Agent'); end; procedure TclHttpRequestHeader.RegisterFields; begin inherited RegisterFields(); RegisterField('Accept'); RegisterField('Accept-Charset'); RegisterField('Accept-Encoding'); RegisterField('Accept-Language'); RegisterField('Authorization'); RegisterField('Host'); RegisterField('Proxy-Authorization'); RegisterField('Range'); RegisterField('Referer'); RegisterField('User-Agent'); end; { TclHttpResponseHeader } procedure TclHttpResponseHeader.Assign(Source: TPersistent); var Src: TclHttpResponseHeader; begin BeginUpdate(); try inherited Assign(Source); if (Source is TclHttpResponseHeader) then begin Src := (Source as TclHttpResponseHeader); AcceptRanges := Src.AcceptRanges; Age := Src.Age; Allow := Src.Allow; Authenticate := Src.Authenticate; ContentRange := Src.ContentRange; ContentDisposition := Src.ContentDisposition; ETag := Src.ETag; Location := Src.Location; ProxyAuthenticate := Src.ProxyAuthenticate; RetryAfter := Src.RetryAfter; Server := Src.Server; end; finally EndUpdate(); end; end; procedure TclHttpResponseHeader.Clear; begin BeginUpdate(); try inherited Clear(); AcceptRanges := ''; Age := ''; Allow := ''; Authenticate.Clear(); ContentRange := ''; ETag := ''; Location := ''; ContentDisposition := ''; ProxyAuthenticate.Clear(); RetryAfter := ''; Server := ''; finally EndUpdate(); end; end; destructor TclHttpResponseHeader.Destroy; begin FProxyAuthenticate.Free(); FAuthenticate.Free(); inherited Destroy(); end; procedure TclHttpResponseHeader.InternalAssignHeader(AFieldList: TclHeaderFieldList); begin AFieldList.AddField('Allow', Allow); AFieldList.AddField('Accept-Ranges', AcceptRanges); AFieldList.AddField('Age', Age); AFieldList.AddField('Content-Range', ContentRange); AFieldList.AddField('Content-Disposition', ContentDisposition); AFieldList.AddField('ETag', ETag); AFieldList.AddField('Location', Location); AFieldList.AddField('Retry-After', RetryAfter); AFieldList.AddField('Server', Server); SetAuthChallenge(AFieldList, 'WWW-Authenticate', Authenticate); SetAuthChallenge(AFieldList, 'Proxy-Authenticate', ProxyAuthenticate); inherited InternalAssignHeader(AFieldList); end; procedure TclHttpResponseHeader.GetAuthChallenge(AFieldList: TclHeaderFieldList; const AuthFieldName: string; AuthChallenge: TStrings); var i: Integer; begin AuthChallenge.Clear(); for i := 0 to AFieldList.FieldList.Count - 1 do begin if SameText(AuthFieldName, AFieldList.FieldList[i]) then begin AuthChallenge.Add(AFieldList.GetFieldValue(i)); end; end; end; procedure TclHttpResponseHeader.SetAuthChallenge(AFieldList: TclHeaderFieldList; const AuthFieldName: string; AuthChallenge: TStrings); var i: Integer; begin for i := 0 to AuthChallenge.Count - 1 do begin AFieldList.AddField(AuthFieldName, AuthChallenge[i]); end; end; procedure TclHttpResponseHeader.InternalParseHeader(AFieldList: TclHeaderFieldList); begin inherited InternalParseHeader(AFieldList); AcceptRanges := AFieldList.GetFieldValue('Accept-Ranges'); Age := AFieldList.GetFieldValue('Age'); Allow := AFieldList.GetFieldValue('Allow'); ContentRange := AFieldList.GetFieldValue('Content-Range'); ContentDisposition := AFieldList.GetFieldValue('Content-Disposition'); ETag := AFieldList.GetFieldValue('ETag'); Location := AFieldList.GetFieldValue('Location'); RetryAfter := AFieldList.GetFieldValue('Retry-After'); Server := AFieldList.GetFieldValue('Server'); GetAuthChallenge(AFieldList, 'WWW-Authenticate', Authenticate); GetAuthChallenge(AFieldList, 'Proxy-Authenticate', ProxyAuthenticate); end; procedure TclHttpResponseHeader.RegisterFields; begin inherited RegisterFields(); RegisterField('Accept-Ranges'); RegisterField('Age'); RegisterField('Allow'); RegisterField('WWW-Authenticate'); RegisterField('Content-Range'); RegisterField('Content-Disposition'); RegisterField('ETag'); RegisterField('Location'); RegisterField('Proxy-Authenticate'); RegisterField('Retry-After'); RegisterField('Server'); end; procedure TclHttpResponseHeader.SetAcceptRanges(const Value: string); begin if (FAcceptRanges <> Value) then begin FAcceptRanges := Value; Update(); end; end; procedure TclHttpResponseHeader.SetAge(const Value: string); begin if (FAge <> Value) then begin FAge := Value; Update(); end; end; procedure TclHttpResponseHeader.SetAllow(const Value: string); begin if (FAllow <> Value) then begin FAllow := Value; Update(); end; end; procedure TclHttpResponseHeader.SetAuthenticate(const Value: TStrings); begin FAuthenticate.Assign(Value); end; procedure TclHttpResponseHeader.SetContentDisposition(const Value: string); begin if (FContentDisposition <> Value) then begin FContentDisposition := Value; Update(); end; end; procedure TclHttpResponseHeader.SetContentRange(const Value: string); begin if (FContentRange <> Value) then begin FContentRange := Value; Update(); end; end; procedure TclHttpResponseHeader.SetETag(const Value: string); begin if (FETag <> Value) then begin FETag := Value; Update(); end; end; procedure TclHttpResponseHeader.SetLocation(const Value: string); begin if (FLocation <> Value) then begin FLocation := Value; Update(); end; end; procedure TclHttpResponseHeader.SetProxyAuthenticate(const Value: TStrings); begin FProxyAuthenticate.Assign(Value); end; procedure TclHttpResponseHeader.SetRetryAfter(const Value: string); begin if (FRetryAfter <> Value) then begin FRetryAfter := Value; Update(); end; end; procedure TclHttpResponseHeader.SetServer(const Value: string); begin if (FServer <> Value) then begin FServer := Value; Update(); end; end; procedure TclHttpResponseHeader.DoCreate; begin inherited DoCreate(); FAuthenticate := TStringList.Create(); FProxyAuthenticate := TStringList.Create(); SetListChangedEvent(FAuthenticate); SetListChangedEvent(FProxyAuthenticate); end; end.
unit ExtAISharedInterface; interface //uses // Classes, SysUtils; // States of the ExtAI type // Predefined data types TBoolArr = array of Boolean; // Definition of actions TGroupOrderAttackUnit = procedure(aGroupID, aUnitID: Integer) of object; TGroupOrderWalk = procedure(aGroupID, aX, aY, aDir: Integer) of object; TLog = procedure(aLog: string) of object; // Definition of states between ExtAI Client and KP Server TTerrainSize = procedure(aX, aY: Word) of object; TTerrainPassability = procedure(aPassability: TBoolArr) of object; TTerrainFertility = procedure(aFertility: TBoolArr) of object; TPlayerGroups = procedure(aHandIndex: SmallInt; aGroups: array of Integer) of object; TPlayerUnits = procedure(aHandIndex: SmallInt; aUnits: array of Integer) of object; // Definition of events TMissionStartEvent = procedure() of object; TMissionEndEvent = procedure() of object; TTickEvent = procedure(aTick: Cardinal) of object; TPlayerDefeatedEvent = procedure(aHandIndex: SmallInt) of object; TPlayerVictoryEvent = procedure(aHandIndex: SmallInt) of object; // DLL interface TDLLpConfig = record Author, Description, ExtAIName: PWideChar; AuthorLen, DescriptionLen, ExtAINameLen, Version: Cardinal; end; implementation { Actions Group GroupOrderAttackHouse GroupOrderAttackUnit GroupOrderFood GroupOrderHalt GroupOrderLink GroupOrderSplit GroupOrderStorm GroupOrderWalk GroupSetFormation House HouseAllow HouseDestroy HouseRepairEnable HouseTrainQueueAdd HouseTrainQueueRemove HouseWareInBlock HouseWeaponsOrderSet HouseWoodcutterChopOnly Plan PlanAddHouse PlanAddRoad PlanAddField PlanAddOrchard PlanRemove Message PlayerMessage PlayerMessageFormatted PlayerMessageGoto PlayerMessageGotoFormatted City Setting PlayerWareDistribution Unit UnitOrderWalk Debug Log(Text) Disp(Text, Duration) Quad(X, Y, Color, ID, Duration); LineOnTerrain(X1,Y1, X2,Y2, Width, Color, ID, Duration) Line(X1,Y1, X2,Y2, width, Color, ID, Duration) Triangle(X1,Y1, X2,Y2, X3,Y3, Color, ID, Duration) Events House OnHouseBuilt OnHouseDamaged OnHouseDestroyed OnHousePlanPlaced Game OnMissionStart OnPlayerDefeated OnPlayerVictory OnTick Unit OnUnitDied OnUnitTrained OnUnitWoundedByHouse OnUnitWoundedByUnit OnWarriorEquipped States Game GameTime PeaceTime Group GroupAt GroupColumnCount GroupDead GroupIsIdle GroupMember GroupMemberCount GroupOwner House HouseAt HouseDamage HouseDeliveryBlocked HouseDestroyed HouseHasOccupant HouseHasWorker HouseIsComplete HouseOwner HousePositionX HousePositionY HouseRepair HouseTrainQueuePeek HouseType HouseWareBlock HouseWareInside HouseWeaponsOrdered HouseWoodcutterChopOnly Fields IsFieldAt IsOrchardAt IsRoadAt Player PlayerAllianceCheck PlayerDefeated PlayerEnabled PlayerGetAllGroups PlayerGetAllHouses PlayerGetAllUnits PlayerHouseCanBuild PlayerName PlayerVictorious PlayerWareDistribution Stat StatArmyCount StatCitizenCount StatHouseTypeCount StatPlayerCount StatUnitCount StatUnitKilledCount StatUnitLostCount StatUnitTypeCount StatWaresBalance StatWaresProduced Unit UnitAt UnitCarryCount UnitCarryType UnitDead UnitDirection UnitGroup UnitHunger UnitHungerLow UnitHungerMax UnitOwner UnitPositionX UnitPositionY UnitType } end.
unit RealState.Agent.Controller; interface uses MVCFramework, MVCFramework.Commons, JsonDataObjects; type [MVCPath('/api/agents')] TAgentController = class(TMVCController) public [MVCPath('/')] [MVCHTTPMethod([httpGET])] procedure GetAgents; end; implementation uses System.StrUtils, System.SysUtils, RealState.Agent.Repository; procedure TAgentController.GetAgents; var repository: TAgentRepository; begin Writeln(Context.Request.PathInfo); repository := TAgentRepository.Create(nil); try Render(repository.GetAgents); finally repository.Free; end; end; end.
unit ChromeLikeBaseWindowCaptionButton; // Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeBaseWindowCaptionButton.pas" // Стереотип: "GuiControl" // Элемент модели: "TChromeLikeBaseWindowCaptionButton" MUID: (533D01CB01B1) interface {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3IntfUses {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , Classes , l3Interfaces , Messages ; type RChromeLikeWindowCaptionbuttonClass = class of TChromeLikeBaseWindowCaptionButton; TChromeLikeWindowCaptionButtonState = ( cbsDisabled , cbsHot , cbsNormal , cbsPushed );//TChromeLikeWindowCaptionButtonState TChromeLikeBaseWindowCaptionButton = class({$If NOT Defined(NoVCL)} TCustomControl {$IfEnd} // NOT Defined(NoVCL) ) private f_State: TChromeLikeWindowCaptionButtonState; f_Active: Boolean; f_ParentForm: TForm; f_OnClick: TNotifyEvent; private procedure CMMouseEnter(var aMessage: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var aMessage: TMessage); message CM_MOUSELEAVE; procedure WMEraseBkgnd(var aMessage: TWMEraseBkgnd); message WM_ERASEBKGND; procedure CMEnabledChanged(var aMessage: TMessage); message CM_ENABLEDCHANGED; protected function pm_GetState: TChromeLikeWindowCaptionButtonState; virtual; procedure pm_SetState(aValue: TChromeLikeWindowCaptionButtonState); virtual; function pm_GetActive: Boolean; virtual; procedure pm_SetActive(aValue: Boolean); virtual; function pm_GetParentForm: TForm; virtual; function NeedUpdateHint: Boolean; virtual; function GetHintText: Il3CString; virtual; {$If NOT Defined(NoVCL)} procedure SetParent(AParent: TWinControl); override; {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} procedure Click; override; {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; {$IfEnd} // NOT Defined(NoVCL) public procedure NotifyFormResized; constructor Create(AOwner: TComponent); override; protected property State: TChromeLikeWindowCaptionButtonState read pm_GetState write pm_SetState; property ParentForm: TForm read pm_GetParentForm; public property Active: Boolean read pm_GetActive write pm_SetActive; property OnClick: TNotifyEvent read f_OnClick write f_OnClick; end;//TChromeLikeBaseWindowCaptionButton {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3ImplUses , Windows , UxTheme , l3String {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *533D01CB01B1impl_uses* //#UC END# *533D01CB01B1impl_uses* ; {$If NOT Defined(NoVCL)} function TChromeLikeBaseWindowCaptionButton.pm_GetState: TChromeLikeWindowCaptionButtonState; //#UC START# *533D0269002B_533D01CB01B1get_var* //#UC END# *533D0269002B_533D01CB01B1get_var* begin //#UC START# *533D0269002B_533D01CB01B1get_impl* Result := f_State; //#UC END# *533D0269002B_533D01CB01B1get_impl* end;//TChromeLikeBaseWindowCaptionButton.pm_GetState procedure TChromeLikeBaseWindowCaptionButton.pm_SetState(aValue: TChromeLikeWindowCaptionButtonState); //#UC START# *533D0269002B_533D01CB01B1set_var* //#UC END# *533D0269002B_533D01CB01B1set_var* begin //#UC START# *533D0269002B_533D01CB01B1set_impl* if (aValue <> f_State) then begin f_State := aValue; Invalidate; end; //#UC END# *533D0269002B_533D01CB01B1set_impl* end;//TChromeLikeBaseWindowCaptionButton.pm_SetState function TChromeLikeBaseWindowCaptionButton.pm_GetActive: Boolean; //#UC START# *533D02A3034C_533D01CB01B1get_var* //#UC END# *533D02A3034C_533D01CB01B1get_var* begin //#UC START# *533D02A3034C_533D01CB01B1get_impl* Result := f_Active; //#UC END# *533D02A3034C_533D01CB01B1get_impl* end;//TChromeLikeBaseWindowCaptionButton.pm_GetActive procedure TChromeLikeBaseWindowCaptionButton.pm_SetActive(aValue: Boolean); //#UC START# *533D02A3034C_533D01CB01B1set_var* //#UC END# *533D02A3034C_533D01CB01B1set_var* begin //#UC START# *533D02A3034C_533D01CB01B1set_impl* if (aValue <> f_Active) then begin f_Active := aValue; Invalidate; end; //#UC END# *533D02A3034C_533D01CB01B1set_impl* end;//TChromeLikeBaseWindowCaptionButton.pm_SetActive function TChromeLikeBaseWindowCaptionButton.pm_GetParentForm: TForm; //#UC START# *533D035E03BC_533D01CB01B1get_var* //#UC END# *533D035E03BC_533D01CB01B1get_var* begin //#UC START# *533D035E03BC_533D01CB01B1get_impl* Result := f_ParentForm; //#UC END# *533D035E03BC_533D01CB01B1get_impl* end;//TChromeLikeBaseWindowCaptionButton.pm_GetParentForm procedure TChromeLikeBaseWindowCaptionButton.NotifyFormResized; //#UC START# *54744FB502AB_533D01CB01B1_var* //#UC END# *54744FB502AB_533D01CB01B1_var* begin //#UC START# *54744FB502AB_533D01CB01B1_impl* if NeedUpdateHint then Hint := l3Str(GetHintText); //#UC END# *54744FB502AB_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.NotifyFormResized function TChromeLikeBaseWindowCaptionButton.NeedUpdateHint: Boolean; //#UC START# *54744FED0113_533D01CB01B1_var* //#UC END# *54744FED0113_533D01CB01B1_var* begin //#UC START# *54744FED0113_533D01CB01B1_impl* Result := (Hint = ''); //#UC END# *54744FED0113_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.NeedUpdateHint function TChromeLikeBaseWindowCaptionButton.GetHintText: Il3CString; //#UC START# *5474500600DA_533D01CB01B1_var* //#UC END# *5474500600DA_533D01CB01B1_var* begin //#UC START# *5474500600DA_533D01CB01B1_impl* Result := nil; //#UC END# *5474500600DA_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.GetHintText procedure TChromeLikeBaseWindowCaptionButton.CMMouseEnter(var aMessage: TMessage); //#UC START# *533D037C00E9_533D01CB01B1_var* //#UC END# *533D037C00E9_533D01CB01B1_var* begin //#UC START# *533D037C00E9_533D01CB01B1_impl* if Enabled then pm_SetState(cbsHot); //#UC END# *533D037C00E9_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.CMMouseEnter procedure TChromeLikeBaseWindowCaptionButton.CMMouseLeave(var aMessage: TMessage); //#UC START# *533D03A40389_533D01CB01B1_var* //#UC END# *533D03A40389_533D01CB01B1_var* begin //#UC START# *533D03A40389_533D01CB01B1_impl* if Enabled then pm_SetState(cbsNormal); //#UC END# *533D03A40389_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.CMMouseLeave procedure TChromeLikeBaseWindowCaptionButton.WMEraseBkgnd(var aMessage: TWMEraseBkgnd); //#UC START# *533D03BE0299_533D01CB01B1_var* //#UC END# *533D03BE0299_533D01CB01B1_var* begin //#UC START# *533D03BE0299_533D01CB01B1_impl* aMessage.Result := 1; //#UC END# *533D03BE0299_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.WMEraseBkgnd procedure TChromeLikeBaseWindowCaptionButton.CMEnabledChanged(var aMessage: TMessage); //#UC START# *533D04A00242_533D01CB01B1_var* function lp_GetParentForm: TForm; var l_Control: TControl; begin Result := nil; l_Control := Parent; while (l_Control <> nil) and (not (l_Control is TCustomForm)) do begin l_Control := l_Control.Parent; end; if (l_Control is TCustomForm) then Result := TForm(l_Control); end;//lp_GetParentForm //#UC END# *533D04A00242_533D01CB01B1_var* begin //#UC START# *533D04A00242_533D01CB01B1_impl* inherited; if not Enabled then pm_SetState(cbsDisabled) else pm_SetState(cbsNormal); //#UC END# *533D04A00242_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.CMEnabledChanged constructor TChromeLikeBaseWindowCaptionButton.Create(AOwner: TComponent); //#UC START# *47D1602000C6_533D01CB01B1_var* //#UC END# *47D1602000C6_533D01CB01B1_var* begin //#UC START# *47D1602000C6_533D01CB01B1_impl* inherited; f_Active := False; f_State := cbsNormal; //#UC END# *47D1602000C6_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.Create procedure TChromeLikeBaseWindowCaptionButton.SetParent(AParent: TWinControl); //#UC START# *4A97E78202FC_533D01CB01B1_var* function lp_GetParentForm: TForm; var l_Control: TControl; begin Result := nil; l_Control := Parent; while (l_Control <> nil) and (not (l_Control is TCustomForm)) do begin l_Control := l_Control.Parent; end; if (l_Control is TCustomForm) then Result := TForm(l_Control); end;//lp_GetParentForm //#UC END# *4A97E78202FC_533D01CB01B1_var* begin //#UC START# *4A97E78202FC_533D01CB01B1_impl* inherited; if (AParent <> nil) then f_ParentForm := lp_GetParentForm; //#UC END# *4A97E78202FC_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.SetParent procedure TChromeLikeBaseWindowCaptionButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); //#UC START# *4E7896270076_533D01CB01B1_var* var l_State: TChromeLikeWindowCaptionButtonState; //#UC END# *4E7896270076_533D01CB01B1_var* begin //#UC START# *4E7896270076_533D01CB01B1_impl* if Enabled then begin if PtInRect(ClientRect, Point(X, Y)) then l_State := cbsHot else l_State := cbsNormal; pm_SetState(l_State); end; inherited; //#UC END# *4E7896270076_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.MouseUp procedure TChromeLikeBaseWindowCaptionButton.Click; //#UC START# *4F88469E0021_533D01CB01B1_var* //#UC END# *4F88469E0021_533D01CB01B1_var* begin //#UC START# *4F88469E0021_533D01CB01B1_impl* if Assigned(f_OnClick) then f_OnClick(Self); //#UC END# *4F88469E0021_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.Click procedure TChromeLikeBaseWindowCaptionButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); //#UC START# *4F88473B03CD_533D01CB01B1_var* //#UC END# *4F88473B03CD_533D01CB01B1_var* begin //#UC START# *4F88473B03CD_533D01CB01B1_impl* if Enabled then pm_SetState(cbsPushed); inherited; //#UC END# *4F88473B03CD_533D01CB01B1_impl* end;//TChromeLikeBaseWindowCaptionButton.MouseDown initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TChromeLikeBaseWindowCaptionButton); {* Регистрация TChromeLikeBaseWindowCaptionButton } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // NOT Defined(NoVCL) {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) end.
unit ReOptimizationUnit; interface uses SysUtils, BaseExampleUnit; type TReOptimization = class(TBaseExample) public procedure Execute(OptimizationProblemId: String); end; implementation uses OptimizationParametersUnit, DataObjectUnit, EnumsUnit; procedure TReOptimization.Execute(OptimizationProblemId: String); var Parameters: TOptimizationParameters; ErrorString: String; DataObject: TDataObject; begin Parameters := TOptimizationParameters.Create; try Parameters.OptimizationProblemID := OptimizationProblemId; Parameters.ReOptimize := True; DataObject := Route4MeManager.Optimization.Update(Parameters, ErrorString); WriteLn(''); try if (DataObject <> nil) then begin WriteLn('ReOptimization executed successfully'); WriteLn(Format('Optimization Problem ID: %s', [DataObject.OptimizationProblemId])); WriteLn(Format('State: %s', [TOptimizationDescription[TOptimizationState(DataObject.State)]])); end else WriteLn(Format('ReOptimization error: "%s"', [ErrorString])); finally FreeAndNil(DataObject); end; finally FreeAndNil(Parameters); end; end; end.
unit FFSUtils; interface uses System.IOUtils, FFSTypes, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, MaskUtils, Dialogs, Printers, Math, Registry, TlHelp32; const BadDate = 0; BadTime = -1; crlf = #13#10; PRIMARY_KEY = ''; FFSDEFAULTPRINTER = 'Windows Default Printer'; type EInvalidDateException = class(Exception); TFFSDate = TDateTime; TStringArray = Array of string; TDateFormat = (dtfYMD, dtfMDY, dtfYrMO, dtfMOYr, dtfVax6); TMaskFormat = (mtNone, mtZip, mtPhone, mtApr); // misc function FormatZip(z:string):string; function StrVax(NewValue,CurrentValue:string):string; procedure WaitSleep(MilliSecondsToWait: Cardinal); // Messages function MsgInformation(msg:string;Flags:integer=MB_OK):integer; function MsgConfirmation(msg:string;Flags:integer=MB_YESNO):integer; function MsgAsterisk(msg:string;Flags:integer=MB_OK):integer; function MsgProcessBusy:integer; function MsgReportBusy:integer; procedure MsgInsufficient; // New Set of Date Routines #Miller - Uses storage format, display format, & TDate - I want to try these out 11/20/2000 function DateStorToDisp(s:string):string; function DateStorToDate(s:string):TFFSDate; // Internal - Used to be component properties procedure SetglDateFmt(const Value: string); procedure SetglStorFmt(const Value: string); procedure SetglDateLongFmt(const Value: string); procedure SetglEpoch(const Value: integer); procedure SetglSystemDate(const Value: TFFSDate); procedure SetglTimeFmt(const Value: string); Function GetglDateFmt:string; Function GetglDateLongFmt:string; Function GetglEpoch:integer; Function GetglSystemDate:TFFSDate; Function GetglTimeFmt:string; function GetglSystemTime: TFFSDate; // Date Functions function SystemDateFmt(ADateFormat:TDateFormat):string; // Returns the system date as a string in the given format // Routines that use the computer clock time function DateTimeStamp:string; // Returns date and time as a string to use as a date/time stamp // System Date - Date and time are recorded at program startup - note: if the system is left on overnight, the system date & time will be old function SystemDateString:string; // Returns the system date as a string function SystemTimeString:string; // Returns the system time as a string function SystemDateStringLong:string; // Returns the system date in a long format function SystemYrMo:string; // Conversion routines from text to date/time function ConvertToDate(ADateString:string):TFFSDate; function ConvertYYMMDDToDate(s:string):TFFSDate; function ConvertToTime(ATimeStr:string):TFFSDate; function DateStrToDate(d, fmt: string): TFFSDate; function YrMoStrToDate(AYrMoString:string):TFFSDate; // conversion routines from date/time to text function DateStrConvert(ADateString:string;AFmtFrom, AFmtTo:TDateFormat):string; function AnyDateTommddyyyy(StrDate:string):string; function AnyDateToyyyymmdd(StrDate:string):string; function AnyDateToMonthDayYear(StrDate:string):string; function DateToShortString(d:TFFSDate):string; function yyyymmTommyyyy(ADateStr: string):string; function TimeTohhmmap(ATime:TFFSDate):string; function AnyTimeTohhmmap(ATimeStr:string):string; function yyyymmddToVax(ADate:string):string; function VaxToDate(s: string; ymd:boolean=false):string; // function CrunchDate(s: string): string; function ExpandDate(s: string): string; function CrunchTime(s: string): string; function ExpandTime(s: string): string; function Crunch6Time(s: string): string; function Expand6Time(s: string): string; function CrunchDateTime(s: string):string; function ExpandDateTime(s: string):string; function Y2KYrMo(AYrMo:string):string; function NextYrMo(AYrMo:string):string; function EomDate(AYrMo:string;RetFmt:string):string; function SixDigitDate(Ayyyymmdd:string):string; // Date functions Borrowed from rx function IsValidDate(ADate: TDateTime): Boolean; function y4md(mmddyy:string):string; function mdy(yymmdd:string):string; function y2k(yystr:string):integer; function yyyymmddToNormal( yyyymmdd : string ) : string; function formatYMDtostring(s:string):string; // Strings - formerly in String Functions function InStr(SubStr,S:string):boolean; // uses pos function to return a boolean result function acompress(instr:string;outsize:integer):string; // Compression routine for CPI UTL Scanning function ncompress(instr:string;outsize:integer):string; // Compression routine for CPI UTL Scanning function space(n:integer):string; // Returns a string of n spaces function RJust(s:string;l:integer):string; // Right Justifies a string to l characters in length padded with spaces function RJustC(s:string;l:integer;c:char):string; // Right Justifies a string to l characters in length padded with character c function LJust(s:string;l:integer):string; // Left Justifies a string to l characters in length padded with spaces function LJustC(s:string;l:integer;c:char):string; // Left Justifies a string to l characters in length padded with character c function empty(s:string):boolean; // Returns False if the string contains any non-blank characters function CommaString(cs:string;Item:integer):string; // Returns then sub-string of a comma delimited string list given by the Item Number function StrZero(n,len:integer;fillch:char='0'):string; // Returns an integer as right justified string padded with zeros by default function ZFill(s: string; l: integer): string; // Fills the remainder of a string with 'Z' function ReverseString(s:shortstring):shortstring; // Returns the exact mirror of the string passed function RepeatChar(c:char;len:integer):string; // Retruns len number of c chars as a string function StripChar(c:char;s:string):string; // remove the character from the string function iif(BoolValue:boolean; s1, s2:string):string; function AddMask(s:string; fmt:TMaskFormat):string; function StripMask(s:string; fmt:TMaskFormat):string; // Misc function ReadVax(NewValue, CurrentValue: string): string; // compares new value to current value function CurrToVax(NewValue, CurrentValue: Currency;len, dec:integer):string; // Returns Blank for no change, otherwise right justified to dec decimals function StrToVax(NewValue, CurrentValue: string; len:integer):string; // Returns a Tilde for Newly Blank, emptystr for no change, otherwise the given new value in a left justified string function DateToVax(NewValue, CurrentValue: string):string; // always len = 6 left just function PadNumeric(s:string;n:integer):string; // Right Justifies numeric values, left justifies non-numeric function FormatTelephoneNumber(InputPhone : string): string; // Returns a formatted telephone number function GetRandomFileName(dir,ext:string) : TFileName; // returns a unique random name in the given directory procedure FFSSound(AppSoundName:string); // plays a sound related to the given application according to registry settings function FindReplace(s, Find, Replace:string):string; // Does a Case-Sensitive find and replace within a string function StripNonNum(s:string):string; // strips formatting characters from a string representing a number function StripNonAlphaNumeric(s:string):string; // strips all non-alphanumeric characters from a string function GetFirstNumber(s:string):string; // Gets the first number from a string function Separate(s:string;delimiter:string=' '):TStringArray; // Breaks up a string into a word list function MakeCSVList(sa:array of string):string; function CsvQuote(const s:string):string; // Adds proper quotation marks around a string for CSV Rules procedure RemoveFilesInDirectory(ADir:string;OlderThanDays:integer); function ElapsedSeconds(AStartTime, AStopTime:TDateTime):integer; // boolean function BoolToYesNo(BoolValue: boolean): String; // Takes a boolean outputs "Yes" or "No" function BoolToYN(BoolValue:boolean):string; // Takes a boolean outputs "Y" or "N" function BoolToTF(BoolValue:boolean):string; // Takes a boolean outputs "T" or "F" function BoolToTrueFalse(BoolValue:boolean):string; // Takes a boolean outputs "True" or "False" function StrToBool(s:string):boolean; // Takes a string. If it starts with "T" or "Y" then the result is true // Big Numbers function Int64ToBase94(ALongValue:Int64):string; // Takes a Long Integer & converts it to a base 94 number function Base94ToInt64(ABase94:string):Int64; // Takes a Base94 Number & converts it to a Long Integer function IntToBase26(n:integer):string; // Takes a Long Integer & converts it to a base 26 number // files procedure ChangeToRW(AName:string); // changes a file's attributes to Read-write procedure FileUpdateBuildList(ADirectory:string;AFileList, AResultList:TStringList); // returns AFileList with names and ages (0 for non-existent files) in a comma text format. function FileCopy(Src,Dest:string):boolean; procedure SetFileAge(AFileName:string;AnAge:integer); // Rounding functions function Sgn(X: Extended): Integer; function RoundUp(X: Extended): Extended; function RoundDn(X: Extended): Extended; function RoundN(X: Extended): Extended; overload; function Fix(X: Extended): Extended; function RoundDnX(X: Extended): Extended; function RoundUpX(X: Extended): Extended; function RoundX(X: Extended): Extended; function RoundN(x: Extended; d: Integer): Extended; overload; function RoundNExtended(x: Extended; d: Integer): Extended; overload; function RoundNCurrency(x: Currency; d: Integer): Currency; overload; function RoundNReal(x: Real; d: Integer): Real; overload; function CommaInt(i:integer):string; function CommaCurr(c:currency):string; function NextPos(SubStr: AnsiString; Str: AnsiString; LastPos: DWORD = 0): DWORD; function WinProcessIsActive(AProcessID:int64):boolean; //Security Related procedure code; Procedure Assemble; procedure CryptText(ThisCle, Buffer: PChar; BufferLength: Integer); Procedure DecryptText(ThisCle, Buffer: PChar; BufferLength: Integer); Function RotateBits(C: Char; Bits: Integer): Char; Function EncryptionWithPasswordVer0(Str,Pwd: String; Encode: Boolean): String; function EncryptionWithPassword(Str,Pwd: String; Encode: Boolean): String; // Printer function ValidPrinter(prName: string): boolean; function DiskInDrive(const ADrive: char): DWORD; // Palette Functions function IsPaletteDevice: BOOLEAN; //Using CreateProcess to Execute Programs procedure ExecNewProcess(ProgramName : String; Wait: Boolean); function ProcessExists(exeFileName: string): Boolean; implementation uses filectrl, mask, mmsystem, dcDateEdit; const Base594Lo : char = '!'; Base594Hi : char = '~'; DateFormats : array[TDateFormat] of string[20] = ('yyyymmdd', 'mm/dd/yyyy', 'yyyymm','mm/yyyy','mmddyy'); var FglEpoch: integer; FglDateLongFmt: string; FglDateFmt: string; FglTimeFmt: string; FglStorFmt: string; FglSystemDate: TFFSDate; //Variables for encryption/decryption algorithm ax,bx,cx,dx,si,tmp,x1a2,res,i,inter,cfc,cfd,k,l : Word; x1a0 : array[0..7] of Word; cle : array[0..15] of char; cry: array[0..33000] of char; newkey : string; function CommaInt(i:integer):string; var s : string; p : integer; sgn : string; begin result := ''; s := inttostr(i); sgn := ''; if s[1] = '-' then begin sgn := s[1]; s := copy(s,2,length(s)); end; while length(s) > 3 do begin p := length(s)-2; result := ',' + copy(s,p,3) + result; s := copy(s,1,p-1); end; result := sgn + s + result; end; function CommaCurr(c:currency):string; begin result := formatcurr('#,###,###,##0.00',c); end; Function GetglDateFmt:string; begin result := FglDateFmt; end; Function GetglDateLongFmt:string; begin result := FglDateLongFmt; end; Function GetglEpoch:integer; begin result := FglEpoch; end; Function GetglSystemDate:TFFSDate; begin {$ifdef SERVER} result := Date; {$else} result := FglSystemDate; {$endif} end; Function GetglTimeFmt:string; begin result := FglTimeFmt; end; { TGlobalDates } function CrunchDate(s:string):string; var p : integer; begin p := pos('/',s); while p > 0 do begin delete(s,p,1); p := pos('/',s); end; result := s; end; function ExpandDate(s:string):string; begin result := AnyDateTommddyyyy(s); end; function AnyDateTommddyyyy(StrDate: string): string; var tempDate : TFFSDate; begin tempDate := ConvertToDate(StrDate); if tempdate <> BadDate then result := DateToShortString(tempDate) else result := StrDate; end; function DateStrConvert(ADateString:string;AFmtFrom, AFmtTo:TDateFormat):string; begin end; function AnyDateToMonthDayYear(StrDate: string): string; var TempDate : TFFSDate; begin TempDate := ConvertToDate(StrDate); if TempDate <> BadDate then result := FormatDateTime('mmmm d, yyyy', TempDate) else result := 'Bad Date'; end; function AnyDateToyyyymmdd(StrDate: string): string; var tempDate : TFFSDate; begin tempDate := ConvertToDate(StrDate); if tempdate <> BadDate then result := FormatDateTime('yyyymmdd',tempdate) else result := ''; end; function AnyTimeTohhmmap(ATimeStr: string): string; var Temp : TFFSDate; begin Temp := ConvertToTime(ATimeStr); if Temp <> BadTime then result := TimeTohhmmap(temp) else result := ''; end; function yyyymmddToVax(ADate:string):string; begin ADate := stripchar('/',ADate); try if (instr(ADate[1],'12') and (length(ADate) = 8)) then result := copy(ADate,5,2) + copy(ADate,7,2) + copy(ADate,3,2) else result := ADate except result := ADate; end; //if length(ADate) <> 8 then result := ADate //else result := copy(ADate,5,2) + copy(ADate,7,2) + copy(ADate,3,2); end; function ExtractNumber(d,fmt,part:string):integer; var p,c : integer; eq : boolean; s : string; begin part := uppercase(part); fmt := uppercase(fmt); p := pos(part, fmt); if p > 0 then begin c := p; eq := true; while (c < length(fmt)) and (eq) do begin if fmt[c+1] = part then inc(c) else eq := false; end; s := copy(d,p,c-p+1); try result := strtoint(s); except result := 0; end; end else result := 0; end; function VaxToDate(s: string; ymd:boolean=false):string; begin result := ''; if length(s) > 0 then begin case s[1] of 'C' : result := dvStrings[ndCont]; 'W' : result := dvStrings[ndWaived]; 'H' : result := dvStrings[ndHist]; 'N' : result := dvStrings[ndNA]; 'S' : result := dvStrings[ndSatisfied]; 'X' : result := dvStrings[ndNewLoan]; else begin if ymd then s := copy(s,3,2) + copy(s,5,2) + copy(s,1,2); result := anydatetoyyyymmdd(s); end; end; end; end; function DateStrToDate(d,fmt:string):TFFSDate; var syy, smm, sdd : word; begin smm := ExtractNumber(d,fmt,'M'); syy := ExtractNumber(d,fmt,'Y'); sdd := ExtractNumber(d,fmt,'D'); try result := encodedate(syy,smm,sdd); except result := badDate;; end; end; function ConvertYYMMDDToDate(s:string):TFFSDate; var d: string; begin d:= copy(s,5,2) + copy(s,7,2) + copy(s,1,4); result := ConvertToDate(d); end; function YrMoStrToDate(AYrMoString:string):TFFSDate; var s : string; begin s := AYrMoString; s := stripchar('/', s); if length(s) < 2 then begin // need at least the month result := badDate; exit; end; if length(s) = 2 then s := s + '01' else insert('01',s,3); result := ConvertToDate(s); end; function ConvertToDate(ADateString: string): TFFSDate; var yy : integer; yys : string; s : string; begin s := StripChar('/', ADateString).Trim; if length(s) < 4 then begin result := badDate; exit; end; if length(s) = 4 then s := s + formatdatetime('yyyy',now); // put the slashes in insert('/',s,3); insert('/',s,6); // make it a 4 digit year no matter what. if length(s) = 8 then begin yys := copy(s,7,2); try yy := strtoint(yys); except yy := 0; end; inc(yy,1900); if yy < FglEpoch then inc(yy,100); yys := inttostr(yy); delete(s,7,2); s := s + yys; end; if length(s) = 10 then begin try result := strtodate(s) except result := badDate; end; end else result := BadDate; end; function ConvertToTime(ATimeStr: string): TFFSDate; begin if pos(':',ATimeStr) = 0 then insert(':',ATimeStr,3); try result := StrtoTime(ATimeStr); except result := BadTime; end; end; function DateTimeStamp: string; begin result := formatdatetime(FglDateFmt + ' ' + FglTimeFmt, now); // result := CurrentDateString(glDateFmt, false) + ' ' + lowercase(CurrentTimeString(glTimeFmt, false)); end; function DateToShortString(d: TFFSDate): string; begin result := FormatDateTime(FglDateFmt, d); // result := StDateToDateString(glDateFmt,d,false); end; function yyyymmTommyyyy(ADateStr: string):string; begin if length(ADateStr)=6 then result := copy(ADateStr,5,2) + '/' + copy(ADateStr,1,4) else result := ADateStr; end; procedure SetglDateFmt(const Value: string); begin FglDateFmt := Value; end; procedure SetglStorFmt(const Value: string); begin FglStorFmt := Value; end; procedure SetglDateLongFmt(const Value: string); begin FglDateLongFmt := Value; end; procedure SetglEpoch(const Value: integer); begin FglEpoch := Value; end; function IsLeapYear(AYear: Integer): Boolean; begin Result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or (AYear mod 400 = 0)); end; function DaysPerMonth(AYear, AMonth: Integer): Integer; const DaysInMonth: array[1..12] of Integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); begin Result := DaysInMonth[AMonth]; if (AMonth = 2) and IsLeapYear(AYear) then Inc(Result); { leap-year Feb is special } end; function ValidDate(Y, M, D: Word): Boolean; begin Result := (Y >= 1) and (Y <= 9999) and (M >= 1) and (M <= 12) and (D >= 1) and (D <= DaysPerMonth(Y, M)); end; function IsValidDate(ADate: TDateTime): Boolean; var Year, Month, Day: Word; begin try DecodeDate(ADate, Year, Month, Day); Result := ValidDate(Year, Month, Day); except Result := False; end; end; function InStr(SubStr,S:string):boolean; // uses pos function to return a boolean result begin result := pos(substr, s) > 0; end; procedure SetglSystemDate(const Value: TFFSDate); begin FglSystemDate := Value; end; procedure SetglTimeFmt(const Value: string); begin FglTimeFmt := Value; end; function SystemDateString: string; begin result := FormatDateTime(FglDateFmt, FglSystemDate); end; function SystemTimeString:string; begin result := FormatDateTime(FglTimeFmt, time); end; function SystemYrMo:string; begin result := FormatDateTime('yyyymm', FglSystemDate); end; function NextYrMo(AYrMo:string):string; var yr : integer; mo : integer; yrs, mos: string; s : string; x : integer; begin result := ''; if length(AYrMo) <> 6 then exit; yr := strtointdef(copy(AYrMo,1,4),2000); mo := strtointdef(copy(AYrMo,5,2),1); inc(mo); if mo > 12 then begin mo := 1; inc(yr); end; str(yr:4,yrs); str(mo:2,mos); s := yrs + mos; for x := 1 to length(s) do if s[x] = ' ' then s[x] := '0'; result := s; end; function EomDate(AYrMo:string;RetFmt:string):string; var yr,mo,D:integer; dt : TDateTime; begin result := ''; if length(AYrMo) = 6 then begin Yr := strtointdef(copy(AYrMo,1,4),2000);; Mo := strtointdef(copy(AYrMo,5,2),1); d := DaysPerMonth(Yr,Mo); dt := encodedate(yr,mo,d); result := formatdatetime(RetFmt,dt); end; end; function SixDigitDate(Ayyyymmdd:string):string; begin if length(Ayyyymmdd) <> 8 then begin result := Ayyyymmdd; exit; end; result := copy(Ayyyymmdd,5,2) + copy(Ayyyymmdd,7,2) + copy(Ayyyymmdd,3,2); end; function Y2KYrMo(AYrMo:string):string; var s : string; begin if length(AYrMo) = 4 then begin AYrMo := copy(AYrMo,3,2) + '01' + copy(AYrMo,1,2); s := AnyDateToyyyymmdd(AYrMo); result := copy(s,1,6); end else result := AYrMo; end; function SystemDateStringLong: string; begin result := FormatDateTime(FglDateLongFmt, FglSystemDate); end; function TimeTohhmmap(ATime: TFFSDate): string; begin result := FormatDateTime(FglTimeFmt,ATime); end; function CrunchDateTime(s: string): string; var d,t:string; p : integer; begin p := pos(' ',s); if p > 0 then begin d := copy(s,1,p-1); t := copy(s,p+1,length(s)-p); end else begin d := s; t := ''; end; result := crunchDate(d) + crunchTime(t); end; function ExpandDateTime(s: string): string; var d, t : string; begin if length(s) in [6,10] then begin d := copy(s,1,6); t := copy(s,7,4); result := ExpandDate(d) + ' ' + ExpandTime(t); end else if length(s) in [8,12] then begin d := copy(s,1,8); t := copy(s,9,4); result := ExpandDate(d) + ' ' + ExpandTime(t); end; end; function CrunchTime(s: string): string; var p : integer; hr : integer; oknum : integer; begin p := pos(':',s); if p > 0 then delete(s,p,1); p := pos('a',s); if p > 0 then begin delete(s,p,1); val(copy(s,1,2),hr, oknum); if hr = 12 then begin delete(s,1,2); s := '00' + s; end; end; p := pos('p',s); if p > 0 then begin delete(s,p,1); val(copy(s,1,2),hr, oknum); hr := hr + 12; delete(s,1,2); s := inttostr(hr) + s; end; result := s; end; function ExpandTime(s: string): string; var hr : integer; oknum : integer; apm : string; hrs : string; begin apm := 'a'; if length(s)=4 then begin val(copy(s,1,2),hr, oknum); case hr of 0 : hrs := '12'; 1..11 : hrs := RJustC(inttostr(hr),2,'0'); 12 : begin hrs := inttostr(hr); apm := 'p'; end; 13..23 : begin hrs := inttostr(hr-12); apm := 'p'; end; end; if length(hrs) < 2 then hrs := ' ' + hrs; result := hrs + ':' + copy(s,3,2) + apm; end else result := s; end; function Crunch6Time(s: string): string; var p : integer; hr : integer; oknum : integer; begin repeat p := pos(':',s); if p > 0 then delete(s,p,1); until p = 0; p := pos('a',s); if p > 0 then begin delete(s,p,1); val(copy(s,1,2),hr, oknum); if hr = 12 then begin delete(s,1,2); s := '00' + s; end; end; p := pos('p',s); if p > 0 then begin delete(s,p,1); val(copy(s,1,2),hr, oknum); if not (hr = 12) then hr := hr + 12; delete(s,1,2); s := inttostr(hr) + s; end; result := s; end; function Expand6Time(s: string): string; var hr : integer; oknum : integer; apm : string; hrs : string; begin apm := 'a'; if length(s)=6 then begin val(copy(s,1,2),hr, oknum); case hr of 0 : hrs := '12'; 1..11 : hrs := RJustC(inttostr(hr),2,'0'); 12 : begin hrs := inttostr(hr); apm := 'p'; end; 13..24 : begin hrs := inttostr(hr-12); apm := 'p'; end; end; if length(hrs) < 2 then hrs := ' ' + hrs; result := hrs + ':' + copy(s,3,2) + ':' + copy(s,5,2) + apm; end else result := s; end; function GetglSystemTime: TFFSDate; begin result := Time; end; // get a random unique file name function GetRandomFileName(dir,ext:string) : TFileName; begin Randomize; result := dir+IntToStr(Random(99999999))+ext; while FileExists(result) do result := dir+IntToStr(Random(99999999))+ext; end; function StrToBool(s: string): boolean; var test : string; begin test := uppercase(s); if length(test) > 0 then result := test[1] in ['T','Y','1'] else result := false; end; function BoolToTF(BoolValue: boolean): string; begin case BoolValue of false : result := 'F'; true : result := 'T'; end; end; function BoolToTrueFalse(BoolValue: boolean): string; begin case BoolValue of false : result := 'False'; true : result := 'True'; end; end; function BoolToYesNo(BoolValue: boolean): String; begin case BoolValue of false : result := 'No'; true : result := 'Yes'; end; end; function BoolToYN(BoolValue: boolean): string; begin case BoolValue of false : result := 'N'; true : result := 'Y'; end; end; function PadNumeric(s: string; n: integer): string; var x : integer; non : boolean; r: string; begin r := trim(s); non := false; for x := 1 to length(r) do if not (r[x] in ['0'..'9']) then non := true; if non then result := r else result := RJust(r,n); end; function Separate(s: string; delimiter: string = ' '): TStringArray; var x,p : integer; sar : TStringArray; begin x := 0; SetLength(sar,x); p := pos(delimiter, s); while p > 0 do begin inc(x); setLength(sar, x); sar[x-1] := copy(s,1,p-1); delete(s,1,p); p := pos(delimiter, s); end; if length(s) > 0 then begin inc(x); setLength(sar, x); sar[x-1] := s; end; result := sar; end; function CsvQuote(const s:string):string; var quoted : boolean; x : integer; r : string; begin quoted := false; for x := 1 to length(s) do begin if ord(s[x]) <= 32 then begin quoted := true; break; end; if s[x] = ',' then begin quoted := true; break; end; end; if empty(s) then result := '" "' else begin if pos('"',s) > 0 then begin quoted := true; r := ''; for x := 1 to length(s) do if s[x] = '"' then r := r + '""' else r := r + s[x]; end else r := s; if quoted then result := '"' + r + '"' else result := r; end; r := ''; end; function IntToBase26(n:integer):string; var s : string; x,y : integer; c,r : integer; begin s := ''; for x := 6 downto 1 do begin c := 26; for y := 2 to x do c := c * 26; r := n div c; if r > 26 then raise exception.create('Base26 Overflow'); if r > 0 then begin s := s + chr(ord('A') - 1 + r); n := n mod c; end; end; s := s + chr(ord('A') - 1 + n); result := s; end; function formatYMDtostring(s:string):string; var mm,dd,yy : string; tempdate : tdatetime; begin try yy := copy(s,1,4); mm := copy(s,5,2); dd := copy(s,7,2); tempdate := strtodate(mm+'/'+dd+'/'+yy); result := datetostr(tempdate); except result := ''; end; end; Function FormatTelephoneNumber(InputPhone : string):string; begin {format the telephone number} if InputPhone = '' then FormatTelephoneNumber := '' else FormatTelephoneNumber := FormatMaskText('(000) 000-0000;0;*',InputPhone); end; function Int64ToBase94(ALongValue:Int64):string; var x,y : integer; n,r : int64; temp : int64; c : char; txt : string; begin txt := ''; temp := ALongValue; for x := 5 downto 2 do begin n := 94; for y := 2 to x - 1 do n := (n * 94); try r := temp div n; except r := 0; end; c := chr(r + ord(base594Lo)); txt := txt + c; try temp := temp mod n; except end; end; c := chr(temp + ord(base594Lo)); txt := txt + c; result := txt; end; function Base94ToInt64(ABase94:string):Int64; var c : char; x : integer; y : int64; n : int64; begin result := 0; // make sure the value is correct length if length(ABase94) > 5 then exit; while length(ABase94) < 5 do ABase94 := Base594Lo + ABase94; n := 0; for x := 5 downto 1 do begin c := ABase94[x]; y := ord(c) - ord(base594Lo); case x of 5 : n := y; 4 : n := n + (y * 94); 3 : n := n + (y * 94 * 94); 2 : n := n + (y * 94 * 94 * 94); 1 : n := n + (y * 94 * 94 * 94 * 94); end; end; result := n; end; function MsgAsterisk(msg: string; Flags: integer): integer; begin result := MessageBox(0, pchar(msg),'Error', Flags+MB_ICONASTERISK+MB_TASKMODAL); end; function MsgConfirmation(msg: string; Flags: integer): integer; begin if flags = MB_YESNO then flags := flags + MB_DEFBUTTON2; // FreeLocalizer. result := MessageBox(0, pchar(msg),'Please Confirm',Flags+MB_ICONQUESTION+MB_TASKMODAL); end; function MsgInformation(msg: string; Flags: integer): integer; begin result := MessageBox(0, pchar(msg),'Information',Flags+MB_ICONINFORMATION+MB_TASKMODAL); end; procedure MsgInsufficient; begin MsgInformation('You have insufficient rights for this task.'); end; function MsgProcessBusy:integer; begin result := MsgInformation('Another process is currently running. Please try your request later.'); end; function MsgReportBusy:integer; begin result := MsgInformation('Too many reports are currently running. Please try your request later.'); end; function ReadVax(NewValue,CurrentValue:string):string; var test : string; begin test := TrimRight(NewValue); if test = '' then result := CurrentValue // there was no change else if test = '~' then result := '' // was set to blank else result := test; // there was an actual change end; function CurrToVax(NewValue, CurrentValue: Currency;len, dec:integer):string; // Returns Blank for no change, otherwise right justified to dec decimals var fs : string; over : integer; begin if newvalue = currentvalue then result := repeatchar(' ',len) else begin str(newvalue:len:dec,fs); over := length(fs) - len; if over > 0 then fs := copy(fs,over+1,length(fs)-over); result := fs; end; end; function StrToVax(NewValue, CurrentValue: string; len:integer):string; var tnew, told: string; begin tnew := TrimRight(newvalue); told := TrimRight(CurrentValue); if tnew = told then result := repeatchar(' ',len) else if tnew = '' then result := '~' + repeatchar(' ',len-1) else result := ljust(tnew,len); end; function DateToVax(NewValue, CurrentValue: string):string; // always len = 6 left just var s : string; begin s := StrToVax(NewValue, CurrentValue,8); result := ljust(yyyymmddToVax(s),6); // if the result is a date then it will be compressed to 6 chars end; procedure FFSSound(AppSoundName:string); var opts : word; begin opts := SND_APPLICATION+SND_NOWAIT+SND_ASYNC+SND_NODEFAULT; PlaySound(pchar(AppSoundName), 0, opts); end; procedure ChangeToRW(AName:string); var attrs : integer; begin if not fileExists(AName) then exit; attrs := FileGetAttr(AName); if (Attrs and faReadOnly) <> 0 then FileSetAttr(AName, Attrs - faReadOnly); end; function FindReplace(s, Find, Replace:string):string; var p : integer; begin result := s; if find = replace then exit; p := pos(find, s); while p > 0 do begin delete(s,p,length(find)); insert(replace, s, p); p := pos(find, s); end; result := s; end; procedure FileUpdateBuildList(ADirectory:string;AFileList, AResultList:TStringList); // returns AFileList with names and ages (0 for non-existent files) in a comma text format. var x : integer; fname : string; age : integer; APath : string; begin APath := IncludeTrailingBackslash(ADirectory); AResultList.clear; if not DirectoryExists(APath) then raise exception.Create('Directory Missing'); for x := 0 to AFileList.Count - 1 do begin fname := APath + AFileList[x]; age := 0; if fileexists(fname) then age := FileAge(fname) else age := 0; AResultList.Add(CsvQuote(AFileList[x]) + ',' + csvquote(inttostr(age))); end; end; function FileCopy(Src,Dest:string):boolean; var fsrc, fdest : file; buf : array[1..65536] of char; bytesread, byteswrite : integer; begin Result := false; if not FileExists(Src) then exit; TFile.Copy(Src, Dest, true); TFile.SetLastWriteTime(Dest, TFile.GetLastWriteTime(Src)); Result := true; end; procedure SetFileAge(AFileName:string;AnAge:integer); var fhandle : integer; begin fhandle := fileOpen(AFileName, fmOpenWrite); if fhandle > 0 then begin fileSetDate(fhandle, AnAge); fileclose(fhandle); end; end; function StripNonNum(s:string):string; var x : integer; begin result := ''; for x := 1 to length(s) do if s[x] in ['0'..'9','-','.'] then result := result + s[x]; end; function StripNonAlphaNumeric(s:string):string; var x : integer; begin result := ''; for x := 1 to length(s) do if s[x] in ['0'..'9','A'..'Z','a'..'z'] then result := result + s[x]; end; function GetFirstNumber(s:string):string; var r: string; x: integer; begin r := trim(s); result := ''; if (r[1] in ['0'..'9']) then begin for x := 1 to length(r) do begin if not (r[x] in ['0'..'9']) then break; end; if (x+1 <= length(r)) then result := copy(r,0,x) else result := copy(r,0,x-1); end; end; function RepeatChar(c:char;len:integer):string; var x : integer; s : string; begin s := EmptyStr; for x := 1 to len do s := s + c; result := s; s := emptystr; end; function empty(s:string):boolean; begin result := trim(s) = emptystr; end; function CommaString(cs:string;Item:integer):string; var sl : TStringList; begin sl := TStringList.create; sl.CommaText := cs; if Item < sl.count then result := sl[Item] else result := ''; sl.free; end; function StrZero(n,len:integer;fillch:char='0'):string; var x : integer; s : string; begin s := inttostr(n); for x := (length(s) + 1) to len do s := fillch + s; result := s; end; function ZFill(s:string;l:integer):string; begin result := s + RepeatChar('Z', l - length(s)); end; function acompress(instr:string;outsize:integer):string; // 09/17/97 - blank compress - for cpi utl stuff var ss : integer; outstr : string; c : string; si : integer; got_number : boolean; begin instr := trim(instr); ss := length(instr); if ss < 1 then begin result := space(outsize); exit; end; c := uppercase(copy(instr,1,1)); if pos(c, 'PR') > 0 then outstr := c // PO box or RR/Rural Route - 10/03/97 else if (ss >= 4) and (uppercase(copy(instr,1,4)) = 'STAR') then outstr := 'R' // star "R"ural route else outstr := ''; si := 1; got_number := false; while (si <= ss) and (length(outstr) < outsize) and (not got_number) do begin c := copy(instr,si,1); if (c >= '0') and (c <= '9') then got_number := true // find position of first number else inc(si); end; if (not got_number) then begin outstr := ''; // drop any "P" or "R" prefixing si := 1; // and just grab from the string end; while (si <= ss) and (length(outstr) < outsize) do begin c := uppercase(copy(instr,si,1)); if ((c >= '0') and (c <= '9')) or ((c >= 'A') and (c <= 'Z')) then outstr := outstr + c; inc(si); end; outstr := LJust(outstr,outsize); result := outstr; end; // 10/03/97 - name compress for cpi function ncompress(instr:string;outsize:integer):string; // 09/17/97 - blank compress - for cpi utl stuff var ss, si : integer; outstr, c : string; begin instr := trim(instr); ss := length(instr); if ss < 1 then begin result := space(outsize); exit; end; outstr := ''; si := 1; while (si <= ss) and (length(outstr) < outsize) do begin c := uppercase(copy(instr,si,1)); if ((c >= '0') and (c <= '9')) or ((c >= 'A') and (c <= 'Z')) then outstr := outstr + c; inc(si); end; outstr := LJust(outstr,outsize); result := outstr; end; function space(n:integer):string; begin result := repeatchar(' ',n); end; function y2k(yystr:string):integer; var yy : integer; oknum : integer; begin val(yystr,yy,oknum); if yy > 70 {fmDatamod.tblSysEpoch.value} then yy := yy + 1900{fmdatamod.tblSysCentury.value} else yy := yy + 1900{fmdatamod.tblSysCentury.value} + 100; result := yy; end; function rjust(s:string;l:integer):string; begin result := RJustC(s,l,' '); end; function RJustC(s:string;l:integer;c:char):string; begin if length(s) > l then result := copy(s,1,l) else result := RepeatChar(c,l-length(trim(s))) + trim(s); end; function ljust(s:string;l:integer):string; begin result := LJustC(s,l,' '); end; function LJustC(s:string;l:integer;c:char):string; begin if length(s) > l then result := copy(s,1,l) else result := s + RepeatChar(c,l-length(s)); end; function y4md(mmddyy:string):string; var yy : integer; begin yy := strtoint(copy(mmddyy,5,2)); if yy > 70 then result := '19'+ copy(mmddyy,5,2) + copy(mmddyy,1,4); end; function mdy(yymmdd:string):string; begin result := copy(yymmdd,3,4) + copy(yymmdd,1,2); end; // changed to handle 'WAIVED', 'W', 'CONT.', and '' function yyyymmddToNormal( yyyymmdd : string ) : string; var test : string; begin // #Miller - need to finish test := copy(yyyymmdd,1,1); if not empty(test) then begin case test[1] of 'W' : begin end; end; end; if (yyyymmdd='NEW LOAN') or (yyyymmdd='WAIVED') or (yyyymmdd='W') or (yyyymmdd='') or (yyyymmdd='CONT.') then begin result := yyyymmdd; exit; end; if Length(yyyymmdd)<>8 then begin result := yyyymmdd; exit; end; result := Copy(yyyymmdd,5,2)+'/'+Copy(yyyymmdd,7,2)+'/'+Copy(yyyymmdd,1,4); end; function MakeCSVList(sa:array of string):string; var i : integer; begin result := ''; // be safe in case the array is empty for i:=0 to High(sa) do result := result + CsvQuote(sa[i]) + ','; if result > '' then Delete(result,Length(result),1); end; function ReverseString(s:shortstring):shortstring; var x : integer; begin result := ''; for x := length(s) downto 1 do result := result + s[x]; end; function SystemDateFmt(ADateFormat:TDateFormat):string; begin result := FormatDateTime(DateFormats[ADateFormat], FglSystemDate); end; function DateStorToDisp(s:string):string; var wd : TFFSDate; begin wd := DateStorToDate(s); if wd = BadDate then result := s else result := DateToShortString(wd); end; function DateDispToStor(s:string):string; begin end; function DateStorToDate(s:string):TFFSDate; var yd : integer; mm, dd, yy : string; mmp, ddp, yyp : integer; begin mm := ''; yy := ''; dd := ''; yd := 4; // year digits mmp := pos('mm',FglStorFmt); yyp := pos('yyyy',FglStorFmt); if yyp = 0 then begin yyp := pos('yy',FglStorFmt); yd := 2; end; ddp := pos('dd',FglstorFmt); if mmp > 0 then mm := copy(s,mmp,2); if yyp > 0 then yy := copy(s,yyp,yd); if ddp > 0 then dd := copy(s,ddp,2); // #Miller - make it so waived, etc work too. result := ConvertToDate(mm+'/'+dd+'/'+yy); end; function StripChar(c:char;s:string):string; begin while Pos(c,s)<>0 do Delete(s,Pos(c,s),1); result := s; end; function iif(BoolValue:boolean; s1, s2:string):string; begin if BoolValue then result := s1 else result := s2; end; function Sgn(X: Extended): Integer; // Returns -1, 0 or 1 according to the // sign of the argument begin if X < 0 then Result := -1 else if X = 0 then Result := 0 else Result := 1; end; function RoundUp(X: Extended): Extended; // Returns the first integer greater than or // equal to a given number in absolute value // (sign is preserved). // RoundUp(3.3) = 4 RoundUp(-3.3) = -4 begin Result := Int(X) + Sgn(Frac(X)); end; function RoundDn(X: Extended): Extended; // Returns the first integer less than or // equal to a given number in absolute // value (sign is preserved). // RoundDn(3.7) = 3 RoundDn(-3.7) = -3 begin Result := Int(X); end; function RoundN(X: Extended): Extended; // Rounds a number "normally": if the fractional // part is >= 0.5 the number is rounded up (see RoundUp) // Otherwise, if the fractional part is < 0.5, the // number is rounded down (see RoundDn). // RoundN(3.5) = 4 RoundN(-3.5) = -4 // RoundN(3.1) = 3 RoundN(-3.1) = -3 begin (* if Abs(Frac(X)) >= 0.5 then Result := RoundUp(X) else Result := RoundDn(X); *) Result := Int(X) + Int(Frac(X) * 2); end; function Fix(X: Extended): Extended; // Returns the first integer less than or // equal to a given number. // Int(3.7) = 3 Int(-3.7) = -3 // Fix(3.7) = 3 Fix(-3.1) = -4 begin if (X >= 0) or (Frac(X) = 0) then Result := Int(X) else Result := Int(X) - 1; end; function RoundDnX(X: Extended): Extended; // Returns the first integer less than or // equal to a given number. // RoundDnX(3.7) = 3 RoundDnX(-3.7) = -3 // RoundDnX(3.7) = 3 RoundDnX(-3.1) = -4 begin Result := Fix(X); end; function RoundUpX(X: Extended): Extended; // Returns the first integer greater than or // equal to a given number. // RoundUpX(3.1) = 4 RoundUpX(-3.7) = -3 begin Result := Fix(X) + Abs(Sgn(Frac(X))) end; function RoundX(X: Extended): Extended; // Rounds a number "normally", but taking the sign into // account: if the fractional part is >= 0.5 the number // is rounded up (see RoundUpX) // Otherwise, if the fractional part is < 0.5, the // number is rounded down (see RoundDnX). // RoundX(3.5) = 4 RoundX(-3.5) = -3 begin Result := Fix(X + 0.5); end; function RoundN(x: Extended; d: Integer): Extended; begin result := RoundNExtended(x,d); end; function RoundNExtended(x: Extended; d: Integer): Extended; // RoundN(123.456, 0) = 123.00 // RoundN(123.456, 2) = 123.46 // RoundN(123456, -3) = 123000 const t: array [0..12] of int64 = (1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000); begin if Abs(d) > 12 then raise ERangeError.Create('RoundN: Value must be in -12..12'); if d = 0 then Result := Int(x) + Int(Frac(x) * 2) else if d > 0 then begin x := x * t[d]; Result := (Int(x) + Int(Frac(x) * 2)) / t[d]; end else begin // d < 0 x := x / t[-d]; Result := (Int(x) + Int(Frac(x) * 2)) * t[-d]; end; end; function RoundNCurrency(x: Currency; d: Integer): Currency; const t: array [0..12] of int64 = (1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000, 100000000000, 1000000000000); begin // f := 1; // for i := 1 to d do f := f*10; // result := Int(x * f + 0.5) / f; if Abs(d) > 4 then raise ERangeError.Create('RoundN: Value must be in -12..3'); if d = 0 then Result := Int(x) + Int(Frac(x) * 2) else if d > 0 then begin x := x * t[d]; Result := (Int(x) + Int(Frac(x) * 2)) / t[d]; end else begin // d < 0 x := x / t[-d]; Result := (Int(x) + Int(Frac(x) * 2)) * t[-d]; end; end; function RoundNReal(x: real; d: Integer): real; var i,f : integer; begin if Abs(d) > 12 then raise ERangeError.Create('RoundN: Value must be in -12..12'); // f := 1; // for i := 1 to d do f := f*10; // result := Int(x * f + 0.5) / f; result := Int(x * Power(10,d) + 0.5) / Power(10,d); end; function StripMask(s:string; fmt:TMaskFormat):string; var x,l,p : integer; m : string; begin result := ''; case fmt of mtNone : begin result := s; exit; end; mtZip : m := ' - '; mtPhone : m := '( ) - '; mtApr : m := ' . '; end; if fmt in [mtZip, mtPhone] then begin // standard conversion l := length(s); if length(m) < l then l := length(m); for x := 1 to l do begin if m[x] = ' ' then result := result + s[x]; end; end; if fmt in [mtApr] then begin p := pos('.',s); if p > 0 then delete(s,p,1); result := s; end; end; function AddMask(s:string; fmt:TMaskFormat):string; var x,l,p : integer; m : string; begin result := ''; s := TrimRight(s); case fmt of mtNone : begin result := s; exit; end; mtZip : m := ' - '; mtPhone : m := '( ) - '; mtApr : m := ' . '; end; if fmt in [mtZip, mtPhone] then begin // standard conversion l := length(m); p := 0; for x := 1 to l do begin if m[x] = ' ' then begin inc(p); if length(s) >= p then result := result + s[p]; end else begin if length(s) > p then result := result + m[x]; // only add more mask chars if there are more s chars end; end; end; if fmt = mtApr then begin if pos(copy(s,1,1),'0123456789') > 0 then begin // numeric value p := pos('.',s); if p > 0 then begin // check the position of the decimal while length(s) - p < 2 do s := s + '0'; // always 2 decimal places while length(s) - p > 2 do s := copy(s,1,length(s)-1); // truncate extra decimals // now delete the decimal so we can apply the mask delete(s,p,1); end; l := length(m); p := length(s) + 1; for x := l downto 1 do begin if m[x] = ' ' then begin dec(p); if p > 0 then result := s[p] + result; end else result := m[x] + result; end; if copy(result,1,1) = '.' then result := '0' + result; // add a preceeding zero end else begin if copy(s,1,1) = 'V' then result := 'VARI'; end; end; end; function NextPos(SubStr: AnsiString; Str: AnsiString; LastPos: DWORD = 0): DWORD; type StrRec = packed record allocSiz: Longint; refCnt: Longint; length: Longint; end; const skew = sizeof(StrRec); asm TEST EAX,EAX // Search-String passed? JE @@noWork TEST EDX,EDX // Sub-String passed? JE @@stringEmpty PUSH ECX // Save registers affected PUSH EBX PUSH ESI PUSH EDI MOV ESI,EAX // Load Sub-String pointer MOV EDI,EDX // Load Search-String pointer MOV EBX,ECX // Save Last Position in EBX MOV ECX,[EDI-skew].StrRec.length // Get Search-String Length SUB ECX,EBX // subtract Start Position PUSH EDI // Save Start Position of Search String to return ADD EDI,EBX // Adjust Start Position of Search String MOV EDX,[ESI-skew].StrRec.length // Get Sub-String Length DEC EDX // Adjust JS @@fail // Failed if Sub-String Length was zero MOV AL,[ESI] // Pull first character of Sub-String for SCASB function INC ESI // Point to second character for CMPSB function SUB ECX,EDX // Load character count to be scanned JLE @@fail // Failed if Sub-String was equal or longer than Search-String @@loop: REPNE SCASB // Scan for first matching character JNE @@fail // Failed, if none are matching MOV EBX,ECX // Save counter PUSH ESI PUSH EDI MOV ECX,EDX // load Sub-String length REPE CMPSB // compare all bytes until one is not equal POP EDI // restore counter POP ESI JE @@found // all byte were equal, search is completed MOV ECX,EBX // restore counter JMP @@loop // continue search @@fail: // saved pointer is not needed POP EDX XOR EAX,EAX JMP @@exit @@stringEmpty: // return zero - no match XOR EAX,EAX JMP @@noWork @@found: // restore pointer to start position of Search-String POP EDX // load position of match MOV EAX,EDI // difference between position and start in memory is // position of Sub SUB EAX,EDX @@exit: // restore registers POP EDI POP ESI POP EBX POP ECX @@noWork: end; function WinProcessIsActive(AProcessID:int64):boolean; var h : THandle; l, d : DWORD; begin l := AProcessID; h := OpenProcess(PROCESS_QUERY_INFORMATION, false, l); GetExitCodeProcess(h, d); result := d = STILL_ACTIVE; end; procedure RemoveFilesInDirectory(ADir:string;OlderThanDays:integer); var srec : TSearchRec; rslt : integer; pth : string; age1 : integer; age2 : TDateTime; compd : TDateTime; fname : string; begin compd := now - OlderThanDays; if compd < 2 then exit; // this doesn't delete anything less than a 2 days old pth := ADir + '*.*'; rslt := findfirst(pchar(pth), faAnyFile, srec); while rslt = 0 do begin fname := ADir + srec.Name; age1 := FileAge(fname); if age1 > -1 then begin Age2 := FileDateToDateTime(age1); if Age2 < compd then begin try ChangeToRW(fname); deletefile(fname); except end; end; end; rslt := findnext(srec); end; FindClose(srec); end; function ValidPrinter(prName: string): boolean; var rp: integer; begin printer.Refresh; rp := printer.Printers.IndexOf(prName); result := (rp <> -1) or (prName = FFSDEFAULTPRINTER); end; function DiskInDrive(const ADrive: char): DWORD; var bytesPerSector: DWORD; errorMode: UINT; numFreeClusters: DWORD; retCode: BOOL; rootPath: string; secsPerCluster: DWORD; totalClusters: DWORD; begin Result := 0; if not (ADrive in ['A'..'Z', 'a'..'z']) then begin Result := $FFFFFFFF; Exit; end; rootPath := ADrive + ':'; errorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try retCode := GetDiskFreeSpace(PChar(rootPath), secsPerCluster, bytesPerSector, numFreeClusters, totalClusters); finally SetErrorMode(errorMode); end; if not retCode then Result := GetLastError; end; function ElapsedSeconds(AStartTime, AStopTime:TDateTime):integer; var TotalTime : TDateTime; Hour, Minute, Second, MSec : word; begin TotalTime := AStopTime - AStartTime; decodeTime(TotalTime, hour, minute, second, msec); result := (hour * 60 * 60) + (minute * 60) + second; end; function IsPaletteDevice: BOOLEAN; var DeviceContext: hDC; begin DeviceContext := GetDC(hWnd_DeskTop); try RESULT := GetDeviceCaps(DeviceContext, RASTERCAPS) AND RC_PALETTE = RC_PALETTE; finally // Give back the screen DC ReleaseDC(0, DeviceContext); end; END {IsPaletteDevice}; function FormatZip(z:string):string; var s : string; p : integer; begin s := z; if length(s) > 5 then begin if length(s) = 6 then s := copy(s,1,5) else begin p := pos('-',s); if (p > 0) and (p <> 6) then delete(s,p,1); p := pos('-',s); if p = 0 then insert('-',s,6); end; end; result := s; end; function StrVax(NewValue,CurrentValue:string):string; var test : string; begin test := TrimRight(NewValue); if test = '' then result := CurrentValue else if test = '~' then result := '' else result := test; end; procedure code; begin dx:= x1a2+i; ax:= x1a0[i]; cx:= $015a; bx:= $4e35; tmp:= ax; ax:= si; si:= tmp; tmp:= ax; ax:= dx; dx:= tmp; if (ax <> 0) then ax:= ax*bx; tmp:= ax; ax:= cx; cx:= tmp; if (ax <> 0) then begin ax:= ax*si; cx:= ax+cx; end; tmp:= ax; ax:= si; si:= tmp; ax:= ax*bx; dx:= cx+dx; ax:= ax+1; x1a2:= dx; x1a0[i]:= ax; res:= ax xor dx; i:= i+1; end; Procedure Assemble; begin x1a0[0]:= ( ord(cle[0])*256 ) + ord(cle[1]); code; inter:= res; x1a0[1]:= x1a0[0] xor ( (ord(cle[2])*256) + ord(cle[3]) ); code; inter:= inter xor res; x1a0[2]:= x1a0[1] xor ( (ord(cle[4])*256) + ord(cle[5]) ); code; inter:= inter xor res; x1a0[3]:= x1a0[2] xor ( (ord(cle[6])*256) + ord(cle[7]) ); code; inter:= inter xor res; x1a0[4]:= x1a0[3] xor ( (ord(cle[8])*256) + ord(cle[9]) ); code; inter:= inter xor res; x1a0[5]:= x1a0[4] xor ( (ord(cle[10])*256) + ord(cle[11]) ); code; inter:= inter xor res; x1a0[6]:= x1a0[5] xor ( (ord(cle[12])*256) + ord(cle[13]) ); code; inter:= inter xor res; x1a0[7]:= x1a0[6] xor ( (ord(cle[14])*256) + ord(cle[15]) ); code; inter:= inter xor res; i:= 0; end; procedure CryptText(ThisCle, Buffer: PChar; BufferLength: Integer); // The buffer contains the message to encrypt. No need to be null-termindated, // since its length is explicitly specified. // ThisCle contains the password, 16 characters at max. var Rep: Char; c, d, e: Byte; compte, j: word; begin // Some initializations ZeroMemory(@Cry, SizeOf(Cry)); ZeroMemory(@Cle, SizeOf(Cle)); StrCopy(Cle, ThisCle); si:=0; x1a2:=0; i:=0; for j:=0 to BufferLength-1 do begin c:= ord(Buffer[j]); { c = first byte to crypt} Assemble; cfc:= inter shr 8; cfd:= inter and 255; for compte:= 0 to 15 do cle[compte]:= chr(ord(cle[compte]) xor c); c:= c xor (cfc xor cfd); d:= c shr 4; e:= c and 15; Case d of 0 : rep:= 'a'; 1 : rep:= 'b'; 2 : rep:= 'c'; 3 : rep:= 'd'; 4 : rep:= 'e'; 5 : rep:= 'f'; 6 : rep:= 'g'; 7 : rep:= 'h'; 8 : rep:= 'i'; 9 : rep:= 'j'; 10: rep:= 'k'; 11: rep:= 'l'; 12: rep:= 'm'; 13: rep:= 'n'; 14: rep:= 'o'; 15: rep:= 'p'; else rep := 'a'; end; cry[j*2]:=rep; // contains the first letter // shorter: cry[j*2]:=Char($61+d); // "case" and "rep" no longer needed Case e of 0 : rep:= 'a'; 1 : rep:= 'b'; 2 : rep:= 'c'; 3 : rep:= 'd'; 4 : rep:= 'e'; 5 : rep:= 'f'; 6 : rep:= 'g'; 7 : rep:= 'h'; 8 : rep:= 'i'; 9 : rep:= 'j'; 10: rep:= 'k'; 11: rep:= 'l'; 12: rep:= 'm'; 13: rep:= 'n'; 14: rep:= 'o'; 15: rep:= 'p'; else rep := 'a'; end; cry[j*2+1]:=rep; // contains here the second letter // shorter: cry[j*2+1]:=Char($61+e); // "case" and "rep" no longer needed end; end; Procedure DecryptText(ThisCle, Buffer: PChar; BufferLength: Integer); var Rep: Char; c, d, e: Byte; compte, j: Word; begin // Some initializations ZeroMemory(@Cry, SizeOf(Cry)); ZeroMemory(@Cle, SizeOf(Cle)); StrCopy(Cle, ThisCle); si:=0; x1a2:=0; i:=0; j:=0; l:=0; while j<BufferLength-1 do begin //(j:=0 to BufferLength-1 do begin rep:= Buffer[j]; case rep of 'a' : d:= 0; 'b' : d:= 1; 'c' : d:= 2; 'd' : d:= 3; 'e' : d:= 4; 'f' : d:= 5; 'g' : d:= 6; 'h' : d:= 7; 'i' : d:= 8; 'j' : d:= 9; 'k' : d:= 10; 'l' : d:= 11; 'm' : d:= 12; 'n' : d:= 13; 'o' : d:= 14; 'p' : d:= 15; else d := 0; end; d:= d shl 4; j:=j+1; rep:= Buffer[j]; { rep = second letter } Case rep of 'a' : e:= 0; 'b' : e:= 1; 'c' : e:= 2; 'd' : e:= 3; 'e' : e:= 4; 'f' : e:= 5; 'g' : e:= 6; 'h' : e:= 7; 'i' : e:= 8; 'j' : e:= 9; 'k' : e:= 10; 'l' : e:= 11; 'm' : e:= 12; 'n' : e:= 13; 'o' : e:= 14; 'p' : e:= 15; else e := 0; end; c:= d + e; Assemble; cfc:= inter shr 8; cfd:= inter and 255; c:= c xor (cfc xor cfd); for compte:= 0 to 15 do cle[compte]:= chr(ord(cle[compte]) xor c); // Note : c contains the decrypted byte cry[l]:=chr(c); j:=j+1; l:=l+1; end; end; Function EncryptionWithPassword(Str,Pwd: String; Encode: Boolean): String; var Buf : PChar; Bufkey : Pchar; keysize : Integer; Size : Integer; begin //Encryption algorithm Ver 1 (Latest Version) Size := length(str); if (Size = 0) then exit; keysize := length(Pwd); if (keysize = 0) then exit; GetMem(buf, Size+1); buf := pchar(str); GetMem(Bufkey,keysize+1); BufKey := pchar(Pwd); if (keysize>16) Then begin showmessage('Key must be <=16 characters'); //FreeMem(Buf); //FreeMem(Bufkey); end else begin if Encode then begin //encrypt cryptText(Bufkey, buf, Size); //FreeMem(buf); //FreeMem(Bufkey); result := String(Cry); end else begin //decrypt decryptText(Bufkey, buf, Size); //FreeMem(buf); //FreeMem(Bufkey); result := String(Cry); end; end; end; Function RotateBits(C: Char; Bits: Integer): Char; var SI : Word; begin Bits := Bits mod 8; // Are we shifting left? if Bits < 0 then begin // Put the data on the right half of a Word (2 bytes) SI := MakeWord(Byte(C),0); // Now shift it left the appropriate number of bits SI := SI shl Abs(Bits); end else begin // Put the data on the left half of a Word (2 bytes) SI := MakeWord(0,Byte(C)); // Now shift it right the appropriate number of bits SI := SI shr Abs(Bits); end; // Finally, Swap the bytes SI := Swap(SI); // And OR the two halves together SI := Lo(SI) or Hi(SI); Result := Chr(SI); end; Function EncryptionWithPasswordVer0(Str,Pwd: String; Encode: Boolean): String; var a,PwdChk,Direction,ShiftVal,PasswordDigit : Integer; begin //Encryption algorithm Ver 0 (Earlier version) PasswordDigit := 1; PwdChk := 0; for a := 1 to Length(Pwd) do Inc(PwdChk,Ord(Pwd[a])); Result := Str; if Encode then Direction := -1 else Direction := 1; for a := 1 to Length(Result) do begin if Length(Pwd)=0 then ShiftVal := a else ShiftVal := Ord(Pwd[PasswordDigit]); if Odd(A) then Result[A] := RotateBits(Result[A],-Direction*(ShiftVal+PwdChk)) else Result[A] := RotateBits(Result[A],Direction*(ShiftVal+PwdChk)); inc(PasswordDigit); if PasswordDigit > Length(Pwd) then PasswordDigit := 1; end; end; procedure WaitSleep(MilliSecondsToWait: Cardinal); var StartTime: Cardinal; begin StartTime := GetTickCount; while (GetTickCount >= StartTime) and (GetTickCount < (StartTime + MilliSecondsToWait)) do Application.ProcessMessages end; procedure ExecNewProcess(ProgramName : String; Wait: Boolean); var StartInfo : TStartupInfo; ProcInfo : TProcessInformation; CreateOK : Boolean; begin { fill with known state } FillChar(StartInfo,SizeOf(TStartupInfo),#0); FillChar(ProcInfo,SizeOf(TProcessInformation),#0); StartInfo.cb := SizeOf(TStartupInfo); CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil,False, CREATE_NEW_PROCESS_GROUP+NORMAL_PRIORITY_CLASS, nil, nil, StartInfo, ProcInfo); { check to see if successful } if CreateOK then begin //may or may not be needed. Usually wait for child processes if Wait then WaitForSingleObject(ProcInfo.hProcess, INFINITE); end else begin ShowMessage('Unable to run '+ProgramName); end; CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; function ProcessExists(exeFileName: string): Boolean; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32; begin FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := SizeOf(FProcessEntry32); ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32); Result := False; while Integer(ContinueLoop) <> 0 do begin if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(exeFileName)) or (UpperCase(FProcessEntry32.szExeFile) = UpperCase(exeFileName))) then Result := True; ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; {function SetPrinter(prName: string): boolean; var rp: integer; begin if prName = FFSDEFAULTPRINTER then printer.PrinterIndex := -1 else begin printer.Refresh; rp := printer.Printers.IndexOf(prName); printer.PrinterIndex := rp; or (prName = FFSDEFAULTPRINTER); end; } (* Unused Items // compare str1 and str2 up to a max of Length(str2) function PartialCompare(str1, str2 : string) : boolean; begin result := CompareText(Copy(str1,0,Length(str2)),str2)=0; end; function posx(substr, s:string;n:integer;caseSensitive:boolean = true):integer; var subs : string; p : integer; begin subs := copy(s,n,length(s)); if not casesensitive then begin subs := uppercase(subs); substr := uppercase(subs); end; p := pos(substr, subs); if p > 0 then p := p + n - 1; result := p; end; function YesNoToBool(s: string): boolean; var temp : string; begin temp := uppercase(trim(s)); if temp = 'YES' then result := true else result := false; end; function YNToBool(s: string): boolean; var temp : string; begin temp := uppercase(trim(s)); if temp = 'Y' then result := true else result := false; end; function TFToBool(s: string): boolean; var temp : string; begin temp := uppercase(trim(s)); if temp = 'T' then result := true else result := false; end; function TrueFalseToBool(s: string): boolean; var temp : string; begin temp := uppercase(trim(s)); if temp = 'TRUE' then result := true else result := false; end; function repchar(c:string;l:integer):string; var x : integer; s : string; begin c := copy(c,1,1); for x := 1 to l do s := s + c; result := s; end; *) initialization SetglEpoch(1970); SetglDateFmt('mm/dd/yyyy'); SetglStorFmt('yyyymmdd'); SetglDateLongFmt('mmmm d, yyyy'); SetglTimeFmt('hh:mma/p'); SetglSystemDate(Date); end.
{ Subroutine SST_W_C_INIT * * Set up the back end call table to install the routines for writing C. } module sst_w_c_INIT; define sst_w_c_init; %include 'sst_w_c.ins.pas'; procedure sst_w_c_init; {init back end state for writing C} var i: sys_int_machine_t; {loop counter} ent_p: string_chain_ent_p_t; {points to current reserved name chain entry} name_p: string_var_p_t; {unused subroutine return argument} sym_pp: sst_symbol_pp_t; {unused subroutine return argument} stat: sys_err_t; { ************************************* * * Local subroutine INSTALL_DTYPE_NAME (DTYPE) * * Install the name of the data type DTYPE in the output symbol table. It is * not an error if the name is already in the symbol table. It is assumed that * the data type descriptor is properly filled in, and that it points to * a symbol descriptor. } procedure install_dtype_name ( in dtype: sst_dtype_t); {descriptor for data type to add to sym table} var pos: string_hash_pos_t; {position handle into a hash table} sym_pp: sst_symbol_pp_t; {pointer to data area in hash table entry} name_p: string_var_p_t; {unused subroutine return argument} found: boolean; {TRUE if name found in hash table} begin string_hash_pos_lookup ( {get position for this name in hash table} sst_scope_p^.hash_out_h, {handle to base output symbol table} dtype.symbol_p^.name_out_p^, {name to find hash table position for} pos, {returned hash table position handle} found); {TRUE if name already in hash table} if not found then begin {name not already in symbol table ?} string_hash_ent_add (pos, name_p, sym_pp); {add name to symbol table} sym_pp^ := dtype.symbol_p; {point hash entry to name descriptor} end; end; { ************************************* * * Start of main routine. } begin sst_w.doit := addr(sst_w_c_doit); {install routine to "run" the back end} { * Put the basic machine data types into the output symbol table. These * data types were declared in the config file, and were all set up by the * routine SST_CONFIG_OUT. Each data type has a data type descriptor and * a symbol descriptor, although the symbol has not been entered in any * symbol table. } for i := 1 to sst_config.n_size_int do begin {once for each base integer type} with sst_config.size_int[i]: csize do begin {CSIZE is this SIZE_INT entry} install_dtype_name (csize.dtype_p^); {install data type in symbol table} end; {done with CSIZE abbreviation} end; {back for next integer size} for i := 1 to sst_config.n_size_float do begin {once for each base float type} with sst_config.size_float[i]: csize do begin {CSIZE is this SIZE_FLOAT entry} install_dtype_name (csize.dtype_p^); {install data type in symbol table} end; {done with CSIZE abbreviation} end; {back for next floating point size} install_dtype_name (sst_dtype_uptr_p^); install_dtype_name (sst_dtype_bool_p^); install_dtype_name (sst_dtype_char_p^); { * Put the reserved symbols into the symbol table. No symbol descriptor * will be connected, so these only serve to prevent other symbols names * from being reserved names. * * It is not an error if the reserved name is already in the output symbol table. * This allows listing all the reserved names without having to delete the ones * explicitly given as data type names, etc. } ent_p := sst_config.reserve_p; {init current chain entry to first} while ent_p <> nil do begin {once for each entry in reserved names chain} sst_name_new_out ( {add just the name to the symbol table} ent_p^.s, {symbol name} name_p, {pnt to name in hash entry, UNUSED} sym_pp, {pnt to hash entry data area, UNUSED} stat); ent_p := ent_p^.next_p; {advance to next name in chain} end; {back and process this new chain entry} { * Set the default SET sizes if none were explicitly given. The C language * has no native SET data type, so set the SIZE_SET list to all the available * integer data types, and set SIZE_SET_MULTIPLE to the preferred machine * integer. } if sst_config.n_size_set = 0 then begin {not SIZE_SET commands were used ?} for i := 1 to sst_config.n_size_int do begin {once for each integer size} sst_config.size_set[i].size := {copy data from this integer size} sst_config.size_int[i].size; sst_config.size_set[i].dtype_p := sst_config.size_int[i].dtype_p; end; {back for next integer size} sst_config.n_size_set := sst_config.n_size_int; {set number of SET sizes} end; {done with defaults for SIZE_SET commands} if sst_config.size_set_multiple.size = 0 then begin {no SIZE_SET_MULTIPLE cmd ?} sst_config.size_set_multiple.size := {copy data from preferred machine integer} sst_config.int_machine_p^.size_used; sst_config.size_set_multiple.dtype_p := sst_config.int_machine_p; end; {done with default for SIZE_SET_MULTIPLE} { * Set the length of output lines before wrapping is required. } sst_out.wrap_len := 80; {max allowed output line size} string_vstring (sst_out.comm_start, '/* '(0), -1); string_vstring (sst_out.comm_end, ' */'(0), -1); sst_out.comm_pos := 40; {default column for end of line comment start} { * Initialize other state. } decl_done := []; {no explicit declarations written yet} addr_cnt_ar := -1; {init how array identifiers are interpreted} array_mode := array_pnt_first_k; no_ibm_str_kluge := false; {init to use IBM string constant kluge} end;
unit MarkAddressAsDepartedUnit; interface uses SysUtils, BaseExampleUnit; type TMarkAddressAsDeparted = class(TBaseExample) public procedure Execute(RouteId: String; AddressId, MemberId: integer; IsDeparted: boolean); end; implementation procedure TMarkAddressAsDeparted.Execute(RouteId: String; AddressId, MemberId: integer; IsDeparted: boolean); var ErrorString: String; begin Route4MeManager.Address.MarkAsDeparted( RouteId, AddressId, MemberId, IsDeparted, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then WriteLn('MarkAddressAsDeparted executed successfully') else WriteLn(Format('MarkAddressAsDeparted error: "%s"', [ErrorString])); end; end.
unit pubby.tests; {$mode delphi}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, pubby; type IIntSubscriber = ISubscriber<Integer>; IIntPublisher = IPublisher<Integer>; TIntSubscriberImpl = TSubscriberImpl<Integer>; { TTestIntSub } TTestIntSub = class(TIntSubscriberImpl) private FShouldFail: Boolean; strict protected public property ShouldFail : Boolean read FShouldFail write FShouldFail; end; {$M+} TPubbyTest= class(TTestCase) protected FSubscriber : IIntSubscriber; FPublisher : IIntPublisher; procedure SetUp; override; procedure TearDown; override; published procedure TestHookUp; end; implementation { TTestIntSub } procedure TPubbyTest.TestHookUp; begin Fail('Write your own test'); end; procedure TPubbyTest.SetUp; begin FSubscriber:=TTestIntSub.Create; FPublisher:=TPublisherImpl<Integer>.Create; end; procedure TPubbyTest.TearDown; begin FSubscriber:=nil; FPublisher:=nil; end; initialization RegisterTest(TPubbyTest); end.
{ Date Created: 5/22/00 11:17:32 AM } unit InfoCHECKACCOUNTSTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoCHECKACCOUNTSRecord = record PAccountName: String[32]; PAccountNumber: String[20]; PNextCheckNumber: Integer; End; TInfoCHECKACCOUNTSBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoCHECKACCOUNTSRecord end; TEIInfoCHECKACCOUNTS = (InfoCHECKACCOUNTSPrimaryKey); TInfoCHECKACCOUNTSTable = class( TDBISAMTableAU ) private FDFAccountName: TStringField; FDFAccountNumber: TStringField; FDFNextCheckNumber: TIntegerField; FDFTemplate: TBlobField; procedure SetPAccountName(const Value: String); function GetPAccountName:String; procedure SetPAccountNumber(const Value: String); function GetPAccountNumber:String; procedure SetPNextCheckNumber(const Value: Integer); function GetPNextCheckNumber:Integer; procedure SetEnumIndex(Value: TEIInfoCHECKACCOUNTS); function GetEnumIndex: TEIInfoCHECKACCOUNTS; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoCHECKACCOUNTSRecord; procedure StoreDataBuffer(ABuffer:TInfoCHECKACCOUNTSRecord); property DFAccountName: TStringField read FDFAccountName; property DFAccountNumber: TStringField read FDFAccountNumber; property DFNextCheckNumber: TIntegerField read FDFNextCheckNumber; property DFTemplate: TBlobField read FDFTemplate; property PAccountName: String read GetPAccountName write SetPAccountName; property PAccountNumber: String read GetPAccountNumber write SetPAccountNumber; property PNextCheckNumber: Integer read GetPNextCheckNumber write SetPNextCheckNumber; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoCHECKACCOUNTS read GetEnumIndex write SetEnumIndex; end; { TInfoCHECKACCOUNTSTable } procedure Register; implementation procedure TInfoCHECKACCOUNTSTable.CreateFields; begin FDFAccountName := CreateField( 'AccountName' ) as TStringField; FDFAccountNumber := CreateField( 'AccountNumber' ) as TStringField; FDFNextCheckNumber := CreateField( 'NextCheckNumber' ) as TIntegerField; FDFTemplate := CreateField( 'Template' ) as TBlobField; end; { TInfoCHECKACCOUNTSTable.CreateFields } procedure TInfoCHECKACCOUNTSTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCHECKACCOUNTSTable.SetActive } procedure TInfoCHECKACCOUNTSTable.Validate; begin { Enter Validation Code Here } end; { TInfoCHECKACCOUNTSTable.Validate } procedure TInfoCHECKACCOUNTSTable.SetPAccountName(const Value: String); begin DFAccountName.Value := Value; end; function TInfoCHECKACCOUNTSTable.GetPAccountName:String; begin result := DFAccountName.Value; end; procedure TInfoCHECKACCOUNTSTable.SetPAccountNumber(const Value: String); begin DFAccountNumber.Value := Value; end; function TInfoCHECKACCOUNTSTable.GetPAccountNumber:String; begin result := DFAccountNumber.Value; end; procedure TInfoCHECKACCOUNTSTable.SetPNextCheckNumber(const Value: Integer); begin DFNextCheckNumber.Value := Value; end; function TInfoCHECKACCOUNTSTable.GetPNextCheckNumber:Integer; begin result := DFNextCheckNumber.Value; end; procedure TInfoCHECKACCOUNTSTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('AccountName, String, 32, N'); Add('AccountNumber, String, 20, N'); Add('NextCheckNumber, Integer, 0, N'); Add('Template, Memo, 0, N'); end; end; procedure TInfoCHECKACCOUNTSTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AccountName, Y, Y, N, N'); end; end; procedure TInfoCHECKACCOUNTSTable.SetEnumIndex(Value: TEIInfoCHECKACCOUNTS); begin case Value of InfoCHECKACCOUNTSPrimaryKey : IndexName := ''; end; end; function TInfoCHECKACCOUNTSTable.GetDataBuffer:TInfoCHECKACCOUNTSRecord; var buf: TInfoCHECKACCOUNTSRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAccountName := DFAccountName.Value; buf.PAccountNumber := DFAccountNumber.Value; buf.PNextCheckNumber := DFNextCheckNumber.Value; result := buf; end; procedure TInfoCHECKACCOUNTSTable.StoreDataBuffer(ABuffer:TInfoCHECKACCOUNTSRecord); begin DFAccountName.Value := ABuffer.PAccountName; DFAccountNumber.Value := ABuffer.PAccountNumber; DFNextCheckNumber.Value := ABuffer.PNextCheckNumber; end; function TInfoCHECKACCOUNTSTable.GetEnumIndex: TEIInfoCHECKACCOUNTS; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoCHECKACCOUNTSPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoCHECKACCOUNTSTable, TInfoCHECKACCOUNTSBuffer ] ); end; { Register } function TInfoCHECKACCOUNTSBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAccountName; 2 : result := @Data.PAccountNumber; 3 : result := @Data.PNextCheckNumber; end; end; end. { InfoCHECKACCOUNTSTable }
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, ComCtrls; type TForm1 = class(TForm) ProgressBar1: TProgressBar; BtnStart: TBitBtn; BtnStop: TBitBtn; Timer1: TTimer; EdtTimeout: TEdit; Label1: TLabel; BtnFireNow: TBitBtn; EdtRestzeit: TEdit; Label2: TLabel; Label3: TLabel; procedure BtnStartClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure BtnStopClick(Sender: TObject); procedure BtnFireNowClick(Sender: TObject); private { Private-Deklarationen } FStartTime : TDateTime; FNextAction : TDateTime; procedure CheckButtons; procedure UpdateProgressBar; procedure CalcNextAction; function ElapsedTime:Double; // abgelaufene Zeit function Restzeit:Double; function RestzeitMinuten:Double; function RestzeitSekunden:Double; public { Public-Deklarationen } procedure DoAktion;virtual; end; var Form1: TForm1; implementation {$R *.DFM} uses mmsystem; Const OneMinute = 1.0/(24.0*60.0); procedure TForm1.BtnStartClick(Sender: TObject); begin CalcNextAction; Timer1.Enabled := True; CheckButtons; UpdateProgressBar; end; procedure TForm1.CheckButtons; begin BtnStart.Enabled := not Timer1.Enabled; BtnStop.Enabled := Timer1.Enabled; end; procedure TForm1.DoAktion; var i : Integer; b : Boolean; begin MessageBeep(MB_OK); FlashWindow(Handle, True); // Wecker klingelt :-) PlaySound('RingIn', 0, SND_ALIAS); FlashWindow(Handle, False); end; procedure TForm1.Timer1Timer(Sender: TObject); begin if Now >= FNextAction then begin DoAktion; CalcNextAction; end; UpdateProgressBar; end; procedure TForm1.BtnStopClick(Sender: TObject); begin Timer1.Enabled := False; CheckButtons; ProgressBar1.Position := ProgressBar1.Min; end; procedure TForm1.UpdateProgressBar; begin ProgressBar1.Position := Trunc(ElapsedTime/(FNextAction-FStartTime)*ProgressBar1.Max); EdtRestzeit.Text:= TimeToStr(Restzeit); end; procedure TForm1.CalcNextAction; begin FStartTime := Now; FNextAction := FStartTime+ StrToFloat(EdtTimeout.Text)*OneMinute; end; procedure TForm1.BtnFireNowClick(Sender: TObject); begin DoAktion; end; function TForm1.Restzeit: Double; begin Result := FNextAction-Now; end; function TForm1.ElapsedTime: Double; begin Result := Now-FStartTime; end; function TForm1.RestzeitMinuten: Double; begin Result := Restzeit * 24.0 * 60.0; end; function TForm1.RestzeitSekunden: Double; begin Result := Restzeit * 24.0 * 60.0* 60.0; end; end.
unit MessageList; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, Placemnt; type TMessageListForm = class(TForm) MainMenu: TMainMenu; FileMI: TMenuItem; SaveMI: TMenuItem; ClearMI: TMenuItem; MessageListSaveDialog: TSaveDialog; MessageListMemo: TMemo; FormPlacement: TFormPlacement; procedure ClearMIClick(Sender: TObject); procedure SaveMIClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure Save; procedure Clear; public { Public declarations } end; var MessageListForm: TMessageListForm; implementation {$R *.dfm} procedure TMessageListForm.ClearMIClick(Sender: TObject); begin Clear; end; procedure TMessageListForm.SaveMIClick(Sender: TObject); begin Save; end; procedure TMessageListForm.FormShow(Sender: TObject); begin SendMessage(MessageListMemo.Handle, EM_LINESCROLL, 0, MessageListMemo.Lines.Count - 1); end; procedure TMessageListForm.Clear; begin MessageListMemo.Lines.Clear; end; procedure TMessageListForm.Save; begin if MessageListSaveDialog.Execute then begin MessageListMemo.Lines.SaveToFile(MessageListSaveDialog.FileName); end; end; end.
unit MultiStateButton; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls; type { TMultiStateButton } TMultiStateButton = class(TImage) private fastate:integer; fstates:integer; fpath, fimage, fext:string; Procedure setpath(value:string); Procedure Setstate(value:integer); protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; Procedure Click; override; published Property Path:string read fpath write setpath; Property ImageFile:string read fimage write fimage; Property Extension:string read fext write fext; Property StatesCount:integer read fstates write fstates default 2; Property State:integer read fastate write setstate; end; procedure Register; implementation procedure Register; begin RegisterComponents('Touch',[TMultiStateButton]); end; { TMultiStateButton } procedure TMultiStateButton.setpath(value: string); begin fpath:=IncludeTrailingPathDelimiter(value); end; procedure TMultiStateButton.Setstate(value: integer); begin if (fpath='') or (fext='') or (fimage='') then exit; if (value>=1) and (value<=fstates) then fastate:=value else fastate:=1; picture.LoadFromFile(fpath+fimage+'_'+inttostr(fastate)+fext); end; constructor TMultiStateButton.Create(AOwner: TComponent); begin inherited Create(AOwner); fstates:=2; fastate:=1; fpath:=''; fimage:=''; fext:='.png'; end; destructor TMultiStateButton.Destroy; begin inherited Destroy; end; procedure TMultiStateButton.Click; begin if (fpath='') or (fext='') or (fimage='') then exit; fastate:=fastate+1; if fastate>fstates then fastate:=1; picture.LoadFromFile(fpath+fimage+'_'+inttostr(fastate)+fext); inherited Click; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMC; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$ELSE} System.Classes, {$ENDIF} clMailMessage, clTcpCommandClient, clEncoder; type TclCustomMail = class(TclTcpCommandClient) private FMailMessage: TclMailMessage; FUseSasl: Boolean; FSaslOnly: Boolean; procedure SetUseSasl(const Value: Boolean); procedure SetMailMessage(const Value: TclMailMessage); procedure SetSaslOnly(const Value: Boolean); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetOAuthChallenge: string; procedure SetAuthorization(const Value: string); override; public constructor Create(AOwner: TComponent); override; published property UseSasl: Boolean read FUseSasl write SetUseSasl default False; property SaslOnly: Boolean read FSaslOnly write SetSaslOnly default False; property MailMessage: TclMailMessage read FMailMessage write SetMailMessage; end; resourcestring AuthMethodInvalid = 'Unable to logon to the server using Secure Password Authentication'; const AuthMethodInvalidCode = -400; implementation { TclCustomMail } constructor TclCustomMail.Create(AOwner: TComponent); begin inherited Create(AOwner); FUseSasl := False; FSaslOnly := False; end; function TclCustomMail.GetOAuthChallenge: string; begin Result := 'user=' + UserName + #1 + 'auth=' + Authorization + #1#1; Result := TclEncoder.EncodeToString(Result, cmBase64); end; procedure TclCustomMail.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FMailMessage) and (Operation = opRemove) then begin FMailMessage := nil; end; end; procedure TclCustomMail.SetAuthorization(const Value: string); begin if (Authorization <> Value) then begin if not (csLoading in ComponentState) then begin if (Value <> '') then begin UseSasl := True; end; end; inherited SetAuthorization(Value); end; end; procedure TclCustomMail.SetMailMessage(const Value: TclMailMessage); begin if (FMailMessage <> Value) then begin if (FMailMessage <> nil) then begin FMailMessage.RemoveFreeNotification(Self); end; FMailMessage := Value; if (FMailMessage <> nil) then begin FMailMessage.FreeNotification(Self); end; end; end; procedure TclCustomMail.SetSaslOnly(const Value: Boolean); begin if (FSaslOnly <> Value) then begin FSaslOnly := Value; Changed(); end; end; procedure TclCustomMail.SetUseSasl(const Value: Boolean); begin if (FUseSasl <> Value) then begin FUseSasl := Value; Changed(); end; end; end.
unit udmMDFe; interface uses Windows, Forms, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS, DBClient, ufrmStatus, uMatVars, ACBrMDFeDAMDFeClass, pcnConversao, pmdfeConversaoMDFe, ACBrMDFe, ACBrMDFeDAMDFEFR, ACBrBase, ACBrDFe, frxClass, ACBrDFeSSL ; type TdmMDFe = class(TdmPadrao) qryManutencaoFIL_ORIG: TStringField; qryManutencaoNR_MANIF: TStringField; qryManutencaoNR_MDFE: TFloatField; qryManutencaoCHMDFE: TStringField; qryManutencaoPROTOCOLO: TStringField; qryManutencaoARQUIVO_MDFE: TBlobField; qryManutencaoXML_CANC: TBlobField; qryManutencaoOPERADOR: TStringField; qryLocalizacaoFIL_ORIG: TStringField; qryLocalizacaoNR_MANIF: TStringField; qryLocalizacaoNR_MDFE: TFloatField; qryLocalizacaoCHMDFE: TStringField; qryLocalizacaoPROTOCOLO: TStringField; qryLocalizacaoARQUIVO_MDFE: TBlobField; qryLocalizacaoXML_CANC: TBlobField; qryLocalizacaoOPERADOR: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryManutencaoSTATUS: TStringField; qryLocalizacaoSTATUS: TStringField; qryManutencaoSERIE: TIntegerField; qryLocalizacaoSERIE: TIntegerField; qryManutencaoNRO_RECIBO: TStringField; qryLocalizacaoNRO_RECIBO: TStringField; qryManutencaoSEQEVENTO: TIntegerField; qryLocalizacaoSEQEVENTO: TIntegerField; ACBrMDFe1: TACBrMDFe; ACBrMDFeDAMDFEFR1: TACBrMDFeDAMDFEFR; procedure ACBrMDFe1StatusChange(Sender: TObject); procedure DataModuleCreate(Sender: TObject); private smtp_host: string; smtp_porta: string; smtp_usuario: string; smtp_email: string; smtp_senha: string; smtp_UtilizaSSL: Boolean; smtp_EnviarPDF: Boolean; smtp_PedirConfirmacao: Boolean; smtp_AguardarEnvio: Boolean; smtp_UtilizaTLS: Boolean; smtp_Nome: string; EnviarEmail: Boolean; FMDFe: real; FNro_Manifesto: string; FChave: string; FEmissora: string; FSerie: string; public procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; function LocalizaMDFE(DataSet: TDataSet = nil): Boolean; function LocalizaPorChave(DataSet: TDataSet = nil): Boolean; procedure LerConfiguracao(AUFFilial: string = ''); property Emissora: string read FEmissora write FEmissora; property Nro_Manifesto: string read FNro_Manifesto write FNro_Manifesto; property MDFe: real read FMDFe write FMDFe; property Serie: string read FSerie write FSerie; property Chave: string read FChave write FChave; procedure LiberarFormStatus; end; const SQL_DEFAULT = 'SELECT ' + ' MDFE.FIL_ORIG, ' + ' MDFE.SERIE, ' + ' MDFE.NR_MANIF, ' + ' MDFE.NR_MDFE, ' + ' MDFE.CHMDFE, ' + ' MDFE.PROTOCOLO, ' + ' MDFE.ARQUIVO_MDFE, ' + ' MDFE.XML_CANC, ' + ' MDFE.DT_ALTERACAO, ' + ' MDFE.OPERADOR, ' + ' MDFE.STATUS, ' + ' MDFE.NRO_RECIBO, ' + ' MDFE.SEQEVENTO ' + 'FROM STWOPETMDFE MDFE '; const PASTA_ARQUIVO = 'mmyyyy'; var dmMDFe: TdmMDFe; implementation {$R *.dfm} { TdmCfopItem } uses udmCliente, udmVariaveis, udmProduto, LibGeral, udmConfigSMTP; procedure TdmMDFe.ACBrMDFe1StatusChange(Sender: TObject); begin inherited; case ACBrMDFe1.Status of stMDFeIdle: begin if (frmStatus <> nil) then frmStatus.Hide; end; stMDFeStatusServico: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Verificando Status do servico...'; frmStatus.Show; frmStatus.BringToFront; end; stMDFeRecepcao: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Enviando dados do MDFe...'; frmStatus.Show; frmStatus.BringToFront; end; stMDFeRetRecepcao: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Recebendo dados do MDFe...'; frmStatus.Show; frmStatus.BringToFront; end; stMDFeConsulta: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Consultando CTe...'; frmStatus.Show; frmStatus.BringToFront; end; stMDFeEvento: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Enviando evento de MDFe...'; frmStatus.Show; frmStatus.BringToFront; end; stMDFeRecibo: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Consultando Recibo de Lote...'; frmStatus.Show; frmStatus.BringToFront; end; stMDFeEmail: begin if (frmStatus = nil) then frmStatus := TfrmStatus.Create(Application); frmStatus.lblStatus.Caption := 'Enviando Email...'; frmStatus.Show; frmStatus.BringToFront; end; end; Application.ProcessMessages; end; procedure TdmMDFe.DataModuleCreate(Sender: TObject); var str: TMemoryStream; begin inherited; if not Assigned(frmStatus) then frmStatus := TfrmStatus.Create(Application); str := TMemoryStream.Create; RecuperarFR3('MDFE_EVENTOS_V3.fr3', str); str.SaveToFile(ExtractFileDir(Application.ExeName)+'\Report\MDFE_EVENTOS_V3.fr3'); str.Free; str := nil; str := TMemoryStream.Create; RecuperarFR3('DAMDFe_Retrato_V3.fr3', str); str.SaveToFile(ExtractFileDir(Application.ExeName)+'\Report\DAMDFe_Retrato_V3.fr3'); str.Free; str := nil; end; procedure TdmMDFe.LerConfiguracao(AUFFilial: string); begin if TemValor(AUFFilial) then ACBrMDFe1.Configuracoes.WebServices.UF := AUFFilial else ACBrMDFe1.Configuracoes.WebServices.UF := dmVariaveis.qryManutencaoESTADO.AsString; ACBrMDFe1.Configuracoes.Geral.FormaEmissao := teNormal; ACBrMDFe1.Configuracoes.Geral.VersaoDF := ve300; ACBrMDFe1.Configuracoes.Geral.Salvar := True; if not Assigned(dmConfigSMTP) then dmConfigSMTP := TdmConfigSMTP.Create(Application); with dmConfigSMTP do begin Codigo := 'MDFE'; if Localizar then begin smtp_host := qryLocalizacaoHOST.AsString; smtp_porta := qryLocalizacaoPORTA.AsString; smtp_usuario := qryLocalizacaoUSUARIO.AsString; smtp_email := qryLocalizacaoEMAIL.AsString; smtp_senha := qryLocalizacaoSENHA.AsString; smtp_UtilizaSSL := qryLocalizacaoSSL.AsString = 'T'; smtp_EnviarPDF := qryLocalizacaoENVIARPDF.AsString = 'T'; smtp_PedirConfirmacao := qryLocalizacaoCONFIRMACAO.AsString = 'T'; smtp_AguardarEnvio := qryLocalizacaoAGUARDAR.AsString = 'T'; smtp_UtilizaTLS := qryLocalizacaoTLS.AsString = 'T'; smtp_Nome := qryLocalizacaoNOME.AsString; end; end; EnviarEmail := (Length(Trim(smtp_host)) > 0) and (Length(Trim(smtp_porta)) > 0) and (Length(Trim(smtp_usuario)) > 0) and (Length(Trim(smtp_senha)) > 0) and (Length(Trim(smtp_email)) > 0); try //PASTA QUE SALVA O ARQUIVO XML DO NFE ForceDirectories(sPath_MDFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now)); ACBrMDFe1.Configuracoes.Arquivos.PathSalvar := sPath_MDFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); except ACBrMDFe1.Configuracoes.Arquivos.PathSalvar := sPath_MDFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); end; ACBrMDFe1.DAMDFe := ACBrMDFeDAMDFEFR1; ACBrMDFeDAMDFEFR1.FastFile := PathWithDelim(ExtractFilePath(Application.ExeName)) + 'Report\DAMDFe_Retrato_V3.fr3'; ACBrMDFeDAMDFEFR1.FastFileEvento := PathWithDelim(ExtractFilePath(Application.ExeName)) + 'Report\MDFE_EVENTOS_V3.fr3'; if ACBrMDFe1.DAMDFe <> nil then begin ACBrMDFe1.DAMDFe.TipoDAMDFe := tiRetrato; ACBrMDFe1.DAMDFe.Logo := sCaminhoLogo_MDFe; ACBrMDFe1.DAMDFe.MostrarPreview := lVisualizarMDFE; ACBrMDFe1.DAMDFe.NumCopias := iNumCopiasNFe; ACBrMDFe1.DAMDFe.Usuario := sSnh_NmUsuario; ACBrMDFe1.DAMDFe.Sistema := 'Processado por www.americasoft.com.br'; try //PASTA QUE SALVA O PDF DO NFE ForceDirectories(sPathPDF_MDFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now)); ACBrMDFe1.DAMDFE.PathPDF := sPathPDF_MDFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); except ACBrMDFe1.DAMDFE.PathPDF := sPathPDF_MDFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); end; end; if TemValor(sCertDigitalNumeroSerie) then begin if sCertDigitalCaminhoPFX <> '' then begin ACBrMDFe1.Configuracoes.Geral.SSLLib := libWinCrypt; ACBrMDFe1.Configuracoes.Certificados.ArquivoPFX := sCertDigitalCaminhoPFX; end; ACBrMDFe1.Configuracoes.Certificados.NumeroSerie := sCertDigitalNumeroSerie; ACBrMDFe1.Configuracoes.Certificados.Senha := sCertDigitalSenha; end else ACBrMDFe1.Configuracoes.Certificados.NumeroSerie := ACBrMDFe1.SSL.SelecionarCertificado; ACBrMDFe1.Configuracoes.WebServices.Visualizar := False; if gProxyAuthentication <> taNoAuthentication then begin ACBrMDFe1.Configuracoes.WebServices.ProxyHost := sProxyServer; ACBrMDFe1.Configuracoes.WebServices.ProxyPort := IntToStr(iProxyPort); ACBrMDFe1.Configuracoes.WebServices.ProxyUser := sProxyUsername; ACBrMDFe1.Configuracoes.WebServices.ProxyPass := sProxyPassword; end; ACBrMDFe1.Configuracoes.Arquivos.PathSchemas := sPathSchemas_MDFe; if lMDFeAmbienteTestes then ACBrMDFe1.Configuracoes.WebServices.Ambiente := taHomologacao else ACBrMDFe1.Configuracoes.WebServices.Ambiente := taProducao; end; function TdmMDFe.LocalizaMDFE(DataSet: TDataSet): Boolean; begin inherited; if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE (MDFE.FIL_ORIG = :FIL_ORIG) AND'); SQL.Add('(MDFE.SERIE = :SERIE) AND '); //SQL.Add(' (MDFE.NR_MANIF = :NR_MANIF) AND'); SQL.Add('(MDFE.NR_MDFE = :NR_MDFE) '); SQL.Add('ORDER BY MDFE.NR_MANIF'); Params[0].AsString := FEmissora; Params[1].AsString := FSerie; Params[2].AsFloat := FMDFe; end; DataSet.Open; end; function TdmMDFe.LocalizaPorChave(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE MDFE.CHMDFE=:CHAVE'); Params[0].AsString := FChave; end; DataSet.Open; end; procedure TdmMDFe.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE MDFE.NR_MANIF = :NR_MANIF'); SQL.Add('ORDER BY MDFE.NR_MANIF'); Params[0].AsString := FNro_Manifesto; end; end; procedure TdmMDFe.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY MDFE.NR_MANIF'); end; end; procedure TdmMDFe.LiberarFormStatus; begin if Assigned(frmStatus) then begin frmStatus.Free; frmStatus := nil; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.9 2/23/2005 6:34:26 PM JPMugaas New property for displaying permissions ina GUI column. Note that this should not be used like a CHMOD because permissions are different on different platforms - you have been warned. Rev 1.8 10/26/2004 9:51:14 PM JPMugaas Updated refs. Rev 1.7 4/20/2004 4:01:30 PM JPMugaas Fix for nasty typecasting error. The wrong create was being called. Rev 1.6 4/19/2004 5:05:24 PM JPMugaas Class rework Kudzu wanted. Rev 1.5 2004.02.03 5:45:20 PM czhower Name changes Rev 1.4 1/22/2004 4:59:16 PM SPerry fixed set problems Rev 1.3 1/22/2004 7:20:44 AM JPMugaas System.Delete changed to IdDelete so the code can work in NET. Rev 1.2 10/19/2003 3:36:06 PM DSiders Added localization comments. Rev 1.1 4/7/2003 04:04:08 PM JPMugaas User can now descover what output a parser may give. Rev 1.0 2/19/2003 02:02:08 AM JPMugaas Individual parsing objects for the new framework. } unit IdFTPListParseNovellNetware; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; { This parser should work with Netware 3 and 4. It will probably work on later versions of Novell Netware as well. } type TIdNovellNetwareFTPListItem = class(TIdNovellBaseFTPListItem); TIdFTPLPNovellNetware = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; class function ParseListing(AListing : TStrings; ADir : TIdFTPListItems) : Boolean; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseNovellNetware"'*) implementation uses IdException, IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPNovellNetware } class function TIdFTPLPNovellNetware.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; function IsNetwareLine(const AData : String) : Boolean; var LPerms : String; begin Result := AData <> ''; if Result then begin //The space in the set might be necessary for a test case I had captured //from a website. I don't know if that is an real FTP list or not but it's //better to be safe then sorry. At least I did tighten up the Novell Permissions //check. Result := CharIsInSet(AData, 1, 'dD- '); {Do not localize} if Result then begin // we need to test HellSoft separately from this even though they will be handled by //the same parser. if Result then begin LPerms := ExtractNovellPerms(AData); Result := IsValidNovellPermissionStr(LPerms) and (Length(LPerms) = 8) and (not IsNovelPSPattern(AData)); end; end; end; end; begin Result := False; if AListing.Count > 0 then begin if IsTotalLine(AListing[0]) then begin Result := (AListing.Count > 1) and IsNetwareLine(AListing[1]); end else begin Result := IsNetwareLine(AListing[0]); end; end; end; class function TIdFTPLPNovellNetware.GetIdent: String; begin Result := 'Novell Netware'; {do not localize} end; class function TIdFTPLPNovellNetware.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdNovellNetwareFTPListItem.Create(AOwner); end; class function TIdFTPLPNovellNetware.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var strs : TStrings; wYear, LCurrentMonth, wMonth, wDay: Word; wHour, wMin, wSec, wMSec: Word; ADate: TDateTime; LBuf : String; NameStartPos : Integer; NameStartIdx : Integer; LName : String; LI : TIdNovellNetwareFTPListItem; begin { - [RWCEAFMS] 0 1576 Feb 08 2000 00README - [RWCEAFMS] 0 742 Jan 03 2001 00INDEX - [RWCEAFMS] tjhamalainen 1020928 Sep 25 2001 winntnw.exe d [RWCEAFMS] Okkola 512 Aug 17 03:42 WINDOWS -[R----F-] 1 raj 857 Feb 23 2000 !info! d[R----F-] 1 raj 512 Nov 30 2001 incoming d [R----F--] supervisor 512 Jan 16 18:53 login - [R----F--] rhesus 214059 Oct 20 15:27 cx.exe } LI := AItem as TIdNovellNetwareFTPListItem; NameStartIdx := 5; // Get defaults for modified date/time ADate := Now; DecodeDate(ADate, wYear, wMonth, wDay); DecodeTime(ADate, wHour, wMin, wSec, wMSec); LCurrentMonth := wMonth; if TextStartsWith(LI.Data, 'D') then begin {do not localize} LI.ItemType := ditDirectory; end else begin LI.ItemType := ditFile; end; //Most FTP Clients don't support permissions on a Novel Netware server. LBuf := AItem.Data; LI.NovellPermissions := ExtractNovellPerms(LBuf); LI.PermissionDisplay := '[' + LI.NovellPermissions + ']'; {do not localize} Fetch(LBuf, '] '); {do not localize} if LBuf <> '' then begin //One Novell Server I found at nf.wsp.krakow.pl //uses an old version of Novell Netware (3.12 or so). That differs slightly if LBuf[1] = ' ' then {do not localize} begin IdDelete(LBuf, 1, 1); // LBuf := TrimLeft(LBuf); Fetch(LBuf); end; strs := TStringList.Create; try SplitColumns(LBuf, strs); { 0 - owner 1 - size 2 - month 3 - day of month 4 - time or year 5 - start of file name or time 6 - start of file name if 5 was time } if strs.Count > 4 then begin LI.OwnerName := strs[0]; LI.Size := IndyStrToInt64(strs[1], 0); wMonth := StrToMonth(strs[2]); if wMonth < 1 then begin wMonth := LCurrentMonth; end; wDay := IndyStrToInt(strs[3], wDay); if IndyPos(':', Strs[4]) = 0 then {do not localize} begin wYear := IndyStrToInt(strs[4], wYear); wYear := Y2Year(wYear); wHour := 0; wMin := 0; if (Strs.Count > 5) and (IndyPos(':', Strs[5]) > 0) then {do not localize} begin LBuf := Strs[5]; wHour := IndyStrToInt(Fetch(LBuf, ':'), wHour); {do not localize} wMin := IndyStrToInt(Fetch(LBuf, ':'), wMin); {do not localize} NameStartIdx := 6; end; end else begin wYear := AddMissingYear(wDay, wMonth); LBuf := Strs[4]; wHour := IndyStrToInt(Fetch(LBuf, ':'), wHour); {do not localize} wMin := IndyStrToInt(Fetch(LBuf, ':'), wMin); {do not localize} end; LI.ModifiedDate := EncodeDate(wYear, wMonth, wDay); LI.ModifiedDate := LI.ModifiedDate + EncodeTime(wHour, wMin, 0, 0); //Note that I doubt a file name can start with a space in Novel/ //Netware. Some code I've seen strips those off. for NameStartPos := NameStartIdx to Strs.Count -1 do begin LName := LName + ' ' + Strs[NameStartPos]; {do not localize} end; IdDelete(LName, 1, 1); LI.FileName := LName; //Novell Netware is case sensitive I think. LI.LocalFileName := LName; end; finally FreeAndNil(strs); end; end; Result := True; end; class function TIdFTPLPNovellNetware.ParseListing(AListing: TStrings; ADir: TIdFTPListItems): Boolean; var LStartLine, i : Integer; LItem : TIdFTPListItem; begin if AListing.Count = 0 then begin Result := True; Exit; end; If IsTotalLine(AListing[0]) then begin LStartLine := 1; end else begin LStartLine := 0; end; for i := LStartLine to AListing.Count -1 do begin LItem := MakeNewItem(ADir); LItem.Data := AListing[i]; ParseLine(LItem); end; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPNovellNetware); finalization UnRegisterFTPListParser(TIdFTPLPNovellNetware); end.
unit uSHFingerRegistDevice; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, DB, ADODB; type TfmSHFingerRegistDevice = class(TForm) Panel1: TPanel; lb_Message: TLabel; Panel2: TPanel; btn_GetFPData: TSpeedButton; btn_Save: TSpeedButton; btn_Cancel: TSpeedButton; TempADOQuery: TADOQuery; procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure btn_SaveClick(Sender: TObject); procedure btn_CancelClick(Sender: TObject); procedure btn_GetFPDataClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private L_stDeviceMessage : string; L_stFingerData : string; FSave: Boolean; FFingerCardNo: string; FFingerUserID: string; FFPDeviceID: integer; FFPDeviceVer: integer; { Private declarations } public { Public declarations } property FingerUserID : string read FFingerUserID write FFingerUserID; property FingerCardNo : string read FFingerCardNo write FFingerCardNo; property FPDeviceID : integer read FFPDeviceID write FFPDeviceID; property FPDeviceVer : integer read FFPDeviceVer write FFPDeviceVer; //0:2.0이하 1:2.4이상 property Save : Boolean read FSave write FSave; end; var fmSHFingerRegistDevice: TfmSHFingerRegistDevice; implementation uses uDataModule1, uSHComModule, udmAdoQuery, uLomosUtil, uDBFunction; {$R *.dfm} procedure TfmSHFingerRegistDevice.FormCreate(Sender: TObject); begin L_stDeviceMessage := '$DeviceIP 에서 $UserID 번지에 지문 등록후 가져오기 버튼을 클릭 하여 주세요.'; FPDeviceID := 1; end; procedure TfmSHFingerRegistDevice.FormActivate(Sender: TObject); var stMessage : string; begin stMessage := StringReplace(L_stDeviceMessage,'$DeviceIP',G_stFingerReaderIP,[rfReplaceAll]); stMessage := StringReplace(stMessage,'$UserID',FillZeroStrNum(FingerUserID,G_nFPUserIDLength),[rfReplaceAll]); lb_Message.Caption := stMessage; end; procedure TfmSHFingerRegistDevice.btn_SaveClick(Sender: TObject); begin Save := True; if FingerCardNo = '' then FingerCardNo := dmDBFunction.GetFdmsCardNo; if DataModule1.DupCheckTB_CARDFINGER(FingerUserID) then begin dmAdoQuery.UpdateTB_CARDFINGER(FingerUserID,FingerCARDNO,L_stFingerData,'1','Y'); end else begin dmAdoQuery.InsertIntoTB_CARDFINGER(FingerUserID,FingerCARDNO,L_stFingerData,'1','Y'); end; Close; end; procedure TfmSHFingerRegistDevice.btn_CancelClick(Sender: TObject); begin Save := False; Close; end; procedure TfmSHFingerRegistDevice.btn_GetFPDataClick(Sender: TObject); var oFPNode : TFPNode; Tick: DWORD; NowTick: DWORD; begin Try btn_GetFPData.Enabled := False; btn_Save.Enabled := False; oFPNode := TFPNode.Create(nil); oFPNode.ReaderType := 0; //등록기 타입으로 동작하자. oFPNode.FPNodeNo := 1; oFPNode.FPNodeIP := G_stFingerReaderIP; oFPNode.FPNodePort := 7005; oFPNode.FPDeviceID := FPDeviceID; oFPNode.FPNodeName := '등록기'; oFPNode.FPDeviceType := FPDeviceVer; if oFPNode.Open then oFPNode.Open := False; oFPNode.Open := True; Tick := GetTickCount + DWORD(3000); //3초 동안 접속 하지 못하면 접속 실패이다. While oFPNode.SocketConnected <> Connected do begin NowTick := GetTickCount; if Tick < NowTick then break; Application.ProcessMessages; end; if oFPNode.SocketConnected <> Connected then begin showmessage('지문리더 접속에 실패 하였습니다.'); Exit; end; L_stFingerData := oFPNode.GetFPData(FingerUserID); if L_stFingerData = '' then begin showmessage('해당 번지의 지문을 가져오지 못했습니다..'); Exit; end; btn_Save.Enabled := True; oFPNode.Open := False; Finally oFPNode.Destroy; btn_GetFPData.Enabled := True; End; end; procedure TfmSHFingerRegistDevice.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (L_stFingerData <> '') and (Not Save) then begin if Application.MessageBox(PChar('지문데이터를 저장 하지 않았습니다.종료 하시겠습니까?'),'경고',MB_OKCANCEL) = ID_CANCEL then begin CanClose := False; end; end; end; end.
unit CompPreprocInt; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Compiler preprocessor interface $jrsoftware: issrc/Projects/CompPreprocInt.pas,v 1.4 2010/12/10 05:14:33 jr Exp $ } interface const ispeSuccess = 0; ispeInvalidParam = 1; ispePreprocessError = 2; ispeSilentAbort = 3; type TPreprocCompilerData = type Pointer; TPreprocFileHandle = type Integer; TPreprocLoadFileProc = function(CompilerData: TPreprocCompilerData; Filename: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer): TPreprocFileHandle; stdcall; TPreprocLineInProc = function(CompilerData: TPreprocCompilerData; FileHandle: TPreprocFileHandle; LineIndex: Integer): PChar; stdcall; TPreprocLineOutProc = procedure(CompilerData: TPreprocCompilerData; LineFilename: PChar; LineNumber: Integer; LineText: PChar); stdcall; TPreprocErrorProc = procedure(CompilerData: TPreprocCompilerData; ErrorMsg: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer); stdcall; TPreprocStatusProc = procedure(CompilerData: TPreprocCompilerData; StatusMsg: PChar); stdcall; TPreprocPrependDirNameProc = function(CompilerData: TPreprocCompilerData; Filename: PChar; Dir: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer): PChar; stdcall; TPreprocCleanupProc = function(CleanupProcData: Pointer): Integer; stdcall; PPreprocessScriptParams = ^TPreprocessScriptParams; TPreprocessScriptParams = record Size: Cardinal; { [in] Set to SizeOf(TPreprocessScriptParams). Preprocessor must return ispeInvalidParam if value is not recognized. } InterfaceVersion: Cardinal; { [in] Currently set to 1. Preprocessor must return ispeInvalidParam if value is not recognized. } CompilerBinVersion: Cardinal; { [in] Compiler version as an integer } Filename: PChar; { [in] The full name of the file being preprocessed, or an empty string if preprocessing the main script. } SourcePath: PChar; { [in] The default source directory, and directory to look in for #include files. Normally, this is the directory containing the script file. } CompilerPath: PChar; { [in] The "compiler:" directory. This is the directory which contains the *.e32 files. } Options: PChar; { [in] The 'ISPP:'-prefixed options that were passed to the compiler in TCompileScriptParamsEx.Options. } CompilerData: TPreprocCompilerData; { [in] Opaque value supplied by the compiler that the preprocessor must pass unchanged when calling the *Proc callback functions. } LoadFileProc: TPreprocLoadFileProc; { [in] Call to load a new file. Returns a "handle" to the file which can be passed to LineInProc. On failure, returns -1 and internally calls ErrorProc with a description of the error. } LineInProc: TPreprocLineInProc; { [in] Call to read a line from the specified file. LineIndex is zero-based. The returned pointer is valid only until the next LineInProc call is made (or the preprocess function returns). NULL is returned if EOF is reached. } LineOutProc: TPreprocLineOutProc; { [in] Call to send preprocessed line back to the compiler. } StatusProc: TPreprocStatusProc; { [in] Call to log a message. } ErrorProc: TPreprocErrorProc; { [in] Call to report an error. } PrependDirNameProc: TPreprocPrependDirNameProc; { [in] If the specified filename is relative, prepends the specified directory name (must include trailing path separator). If the specified filename begins with a prefix, such as "compiler:", expands the prefix. The returned pointer is valid only until the next PrependDirNameProc call is made (or the preprocess function returns). On failure, returns NULL and internally calls ErrorProc with a description of the error.} PreprocCleanupProc: TPreprocCleanupProc; { [out] Preprocessor-defined function that, if set, is called after compilation completes or is aborted. Note: This function will still be called if the preprocess function returns a non-ispeSuccess value. } PreprocCleanupProcData: Pointer; { [out] Preprocessor-defined value passed to PreprocCleanupProc. } end; TPreprocessScriptProc = function(var Params: TPreprocessScriptParams): Integer; stdcall; implementation end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.9 2/23/2005 6:34:28 PM JPMugaas New property for displaying permissions ina GUI column. Note that this should not be used like a CHMOD because permissions are different on different platforms - you have been warned. Rev 1.8 10/26/2004 9:51:14 PM JPMugaas Updated refs. Rev 1.7 4/19/2004 5:05:58 PM JPMugaas Class rework Kudzu wanted. Rev 1.6 2004.02.03 5:45:34 PM czhower Name changes Rev 1.5 1/22/2004 4:58:24 PM SPerry fixed set problems Rev 1.4 1/22/2004 7:20:46 AM JPMugaas System.Delete changed to IdDelete so the code can work in NET. Rev 1.3 10/19/2003 3:36:10 PM DSiders Added localization comments. Rev 1.2 6/27/2003 02:07:40 PM JPMugaas Should now compile now that IsNumeric was moved to IdCoreGlobal. Rev 1.1 4/7/2003 04:04:12 PM JPMugaas User can now descover what output a parser may give. Rev 1.0 2/19/2003 10:13:42 PM JPMugaas Moved parsers to their own classes. } unit IdFTPListParseNovellNetwarePSU; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdNovellPSU_DOSFTPListItem = class(TIdNovellBaseFTPListItem); TIdFTPLPNetwarePSUDos = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; TIdNovellPSU_NFSFTPListItem = class(TIdUnixBaseFTPListItem); TIdFTPLPNetwarePSUNFS = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; const NOVELLNETWAREPSU = 'Novell Netware Print Services for Unix: '; {do not localize} // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseNovellNetwarePSU"'*) implementation uses IdException, IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils; { TIdFTPLPNetwarePSUDos } class function TIdFTPLPNetwarePSUDos.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var LPerms : String; LData : String; begin Result := True; if AListing.Count >0 then begin LData := AListing[0]; Result := LData <> ''; if Result then begin Result := CharIsInSet(LData, 1, 'dD-'); {do not localize} if Result then begin //we have to be careful to distinguish between Hellsoft and //NetWare Print Services for UNIX, FTP File Transfer Service LPerms := ExtractNovellPerms(Copy(LData, 1, 12)); Result := (Length(LPerms) = 8) and IsValidNovellPermissionStr(LPerms) and IsNovelPSPattern(LData); end; end; end; end; class function TIdFTPLPNetwarePSUDos.GetIdent: String; begin Result := NOVELLNETWAREPSU + 'DOS Namespace'; {do not localize} end; class function TIdFTPLPNetwarePSUDos.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdNovellPSU_DOSFTPListItem.Create(AOwner); end; class function TIdFTPLPNetwarePSUDos.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf : String; LModifiedDate : String; LModifiedTime : String; LI : TIdNovellPSU_DOSFTPListItem; begin //-[RWCEAFMS] server1 3166 Sept 14, 99 2:30 pm vol$log.err LI := AItem as TIdNovellPSU_DOSFTPListItem; LBuf := LI.Data; //item type if TextStartsWith(LBuf, 'D') then begin {do not localize} LI.ItemType := ditDirectory; end else begin LI.ItemType := ditFile; end; IdDelete(LBuf, 1, 1); LBuf := TrimLeft(LBuf); //Permissions LI.NovellPermissions := ExtractNovellPerms(Fetch(LBuf)); LI.PermissionDisplay := '[' + LI.NovellPermissions + ']'; {do not localize} LBuf := TrimLeft(LBuf); //Owner LI.OwnerName := Fetch(LBuf); LBuf := TrimLeft(LBuf); //size LI.Size := IndyStrToInt64(Fetch(LBuf), 0); LBuf := TrimLeft(LBuf); //month //we have to make sure that the month is 3 chars. The list might return Sept instead of Sep LModifiedDate := Copy(Fetch(LBuf), 1, 3); LBuf := TrimLeft(LBuf); //day LModifiedDate := LModifiedDate + ' ' + Fetch(LBuf); {do not localize} LModifiedDate := Fetch(LModifiedDate, ','); {do not localize} LBuf := TrimLeft(LBuf); //year LModifiedDate := LModifiedDate + ' ' + Fetch(LBuf); {do not localize} LBuf := TrimLeft(LBuf); LI.ModifiedDate := DateStrMonthDDYY(LModifiedDate, ' '); {do not localize} //time LModifiedTime := Fetch(LBuf); LBuf := TrimLeft(LBuf); //am/pm LModifiedTime := LModifiedTime + Fetch(LBuf); LI.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LModifiedTime); //name LI.FileName := LBuf; Result := True; end; { TIdFTPLPNetwarePSUNFS } class function TIdFTPLPNetwarePSUNFS.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var s : TStrings; LBuf : string; begin Result := False; { 1234567890 -rw------ - 2 root wheel 512 Oct 14, 99 8:45 pm deleted.sav -rw------ - 1 bill support 1285 Oct 14, 99 9:55 pm 123456789.123456 or -rw------ 1 root wheel 512 Oct 14 99 8:45 pm deleted.sav -rw------ 1 bill support 1285 Oct 14 99 9:55 pm 123456789.123456 } if AListing.Count > 0 then begin LBuf := AListing[0]; //remove the extra space that sometimes appears in older versions to "flatten" //out the listing if (Length(LBuf) > 9) and (LBuf[10] = ' ') then {do not localize} begin IdDelete(LBuf, 10, 1); end; Result := IsValidUnixPerms(LBuf, True); if Result then begin s := TStringList.Create; try SplitColumns(LBuf, s); Result := (s.Count > 9) and (PosInStrArray(s[9], ['AM', 'PM'], False) <> -1); {do not localize} if Result then begin LBuf := s[6]; LBuf := Fetch(LBuf, ','); {do not localize} Result := IsNumeric(LBuf) and IsNumeric(s[7]) and CharEquals(s[8], 3, ':'); if Result then begin Result := StrToMonth(s[5]) > 0; end; end; finally FreeAndNil(s); end; end; end; end; class function TIdFTPLPNetwarePSUNFS.GetIdent: String; begin Result := NOVELLNETWAREPSU + 'NFS Namespace'; {do not localize} end; class function TIdFTPLPNetwarePSUNFS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdNovellPSU_NFSFTPListItem.Create(AOwner); end; class function TIdFTPLPNetwarePSUNFS.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf, LBuf2 : String; LI : TIdNovellPSU_NFSFTPListItem; begin { -rw------ - 2 root wheel 512 Oct 14, 99 8:45 pm deleted.sav -rw------ - 1 bill support 1285 Oct 14, 99 9:55 pm 123456789.123456 or -rw------- 1 root wheel 512 Oct 14, 99 8:45 pm deleted.sav -rw------- 1 root wheel 3166 Oct 14, 99 8:45 pm vol$log.err -rw------- 1 bill support 1285 Oct 14, 99 9:55 pm 123456789.123456 drw------- 2 mary support 512 Oct 14, 99 7:33 pm locktst drwxr-xr-x 1 root wheel 512 Oct 14, 99 4:33 pm brief Based on: http://www.novell.com/documentation/lg/nw42/unixpenu/data/tut0i3h5.html#cnovdocsdocenglishnw42unixpenudatahpyvrshhhtml http://www.novell.com/documentation/lg/nw5/usprint/unixpenu/data/tut0i3h5.html#dnovdocsdocenglishnw5usprintunixpenudatahpyvrshhhtm http://www.novell.com/documentation/lg/nfs24/docui/index.html#../nfs24enu/data/hpyvrshh.html } { 0 - type of item and Permissions 1 - # of links 2 - Owner 3 - Group 4 - size 5 - month 6 - day 7 - year 8 - time 9 - am/pm 10 - name } LI := AItem as TIdNovellPSU_NFSFTPListItem; LBuf := LI.Data; LBuf2 := Fetch(LBuf); if not IsNumeric(Fetch(LBuf, ' ', False)) then begin {do not localize} LBuf2 := LBuf2 + Fetch(LBuf); end; if TextStartsWith(LBuf2, '-') then begin {do not localize} LI.ItemType := ditFile; end else begin LI.ItemType := ditDirectory; end; LI.UnixOwnerPermissions := Copy(LBuf2, 2, 3); LI.UnixGroupPermissions := Copy(LBuf2, 5, 3); LI.UnixOtherPermissions := Copy(LBuf2, 8, 3); LI.PermissionDisplay := LBuf2; //number of links LI.LinkCount := IndyStrToInt(Fetch(LBuf), 0); //Owner LBuf := TrimLeft(LBuf); LI.OwnerName := Fetch(LBuf); //Group LBuf := TrimLeft(LBuf); LI.GroupName := Fetch(LBuf); //Size LBuf := TrimLeft(LBuf); AItem.Size := IndyStrToInt64(Fetch(LBuf), 0); //Date - month LBuf := TrimLeft(LBuf); LBuf2 := UpperCase(Fetch(LBuf)) + ' '; {do not localize} //Date - day LBuf := TrimLeft(LBuf); LBuf2 := TrimRight(LBuf2) + ' ' + Fetch(LBuf); {do not localize} LBuf2 := Fetch(LBuf2, ','); {do not localize} //Year - year LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf) + ' ' + LBuf2; {do not localize} //Process Day LI.ModifiedDate := DateYYStrMonthDD(LBuf2, ' '); {do not localize} //time LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); //make sure AM/pm are processed LBuf2 := LBuf2 + Fetch(LBuf); LI.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LBuf2); // File name if IndyPos(UNIX_LINKTO_SYM,LBuf) > 0 then begin LI.FileName := Fetch(LBuf, UNIX_LINKTO_SYM); LI.LinkedItemName := LBuf; end else if IndyPos(UNIX_LINKTO_SYM, LBuf) > 0 then begin LI.FileName := Fetch(LBuf, UNIX_LINKTO_SYM); LI.LinkedItemName := LBuf; end else begin LI.FileName := LBuf; end; //Novell Netware is case sensitive I think. LI.LocalFileName := AItem.FileName; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPNetwarePSUDos); RegisterFTPListParser(TIdFTPLPNetwarePSUNFS); finalization UnRegisterFTPListParser(TIdFTPLPNetwarePSUDos); UnRegisterFTPListParser(TIdFTPLPNetwarePSUNFS); end.
unit Rutinas; interface uses Controls, Dialogs; resourcestring rsConfElimina = 'Confirma Eliminación de dato ?'; rsConfGrabar = 'Confirma Grabación de dato ?'; rsConfOpera = 'Confirma Operacion ?'; type DlgTipo = ( dialElim, dialGrabar, dialOpera ); function Confirma( Tipo: DlgTipo ):boolean; implementation function Confirma( Tipo: DlgTipo ):boolean; var FConf: string; begin case Tipo of dialElim: FConf := rsConfElimina; dialGrabar: FConf := rsConfGrabar; dialOpera: FConf := rsConfOpera; end; Result := MessageDlg( FConf, mtConfirmation, [ mbYes, mbNo ], 0 ) = mrYes; end; end.
unit enet_packet; (** @file packet.c @brief ENet packet management functions freepascal 1.3.14 *) interface uses enet_consts, enet_callbacks, enet_socket; function enet_crc32 (buffers : pENetBuffer; bufferCount : enet_size_t):enet_uint32; function enet_packet_create (data : pointer; dataLength : enet_size_t; flags : enet_uint32):pENetPacket; procedure enet_packet_destroy (packet : pENetPacket); function enet_packet_resize (packet : pENetPacket; dataLength : enet_size_t):integer; implementation (** @defgroup Packet ENet packet functions @{ *) (** Creates a packet that may be sent to a peer. @param data initial contents of the packet's data; the packet's data will remain uninitialized if dataContents is NULL. @param dataLength size of the data allocated for this packet @param flags flags for this packet as described for the ENetPacket structure. @returns the packet on success, NULL on failure *) function enet_packet_create (data : pointer; dataLength : enet_size_t; flags : enet_uint32):pENetPacket; begin Result := pENetPacket (enet_malloc (sizeof (ENetPacket))); if Result=nil then exit; if (flags and ENET_PACKET_FLAG_NO_ALLOCATE)<>0 then Result ^. data := penet_uint8 (data) else if (dataLength <= 0) then Result ^.data:=nil else begin Result ^. data := penet_uint8 (enet_malloc (dataLength)); if (Result ^. data = nil) then begin enet_free (Result); Result := nil; exit; end; if (data <> nil) then system.Move(data^, Result ^. data^, dataLength); end; Result ^. referenceCount := 0; Result ^. flags := flags; Result ^. dataLength := dataLength; Result ^. freeCallback := nil; Result ^. userData := nil; end; (** Destroys the packet and deallocates its data. @param packet packet to be destroyed *) procedure enet_packet_destroy (packet : pENetPacket); begin if packet=nil then exit; if (packet ^. freeCallback <> nil) then packet ^. freeCallback(packet); if (packet ^. flags and ENET_PACKET_FLAG_NO_ALLOCATE=0) and (packet ^. data <> nil) then enet_free (packet ^. data); enet_free (packet); end; (** Attempts to resize the data in the packet to length specified in the dataLength parameter @param packet packet to resize @param dataLength new size for the packet data @returns 0 on success, < 0 on failure *) function enet_packet_resize (packet : pENetPacket; dataLength : enet_size_t):integer; var newData : penet_uint8; begin if (dataLength <= packet ^. dataLength) or ((packet ^. flags and ENET_PACKET_FLAG_NO_ALLOCATE)<>0) then begin packet ^. dataLength := dataLength; result := 0; exit; end; newData := penet_uint8 (enet_malloc (dataLength)); if (newData = nil) then begin result := -1; exit; end; system.Move(packet ^. data^, newData^, packet ^. dataLength); enet_free (packet ^. data); packet ^. data := newData; packet ^. dataLength := dataLength; result := 0; end; var initializedCRC32 : integer = 0; crcTable : array[0..255] of enet_uint32; {$push} {$R-} function reflect_crc (val, bits :integer):enet_uint32; var bit : integer; begin Result := 0; for bit:=0 to bits-1 do begin if (val and 1)<>0 then Result := Result or enet_uint32(1 shl (bits - 1 - bit)); val := val shr 1; end; end; procedure initialize_crc32; var ibyte : integer; crc : enet_uint32; offset : integer; begin for ibyte := 0 to 255 do begin crc := reflect_crc (ibyte, 8) shl 24; for offset := 0 to 7 do begin if (crc and $80000000)<>0 then crc := (crc shl 1) xor $04c11db7 else crc := crc shl 1; end; crcTable [ibyte] := reflect_crc (crc, 32); end; initializedCRC32 := 1; end; function enet_crc32 (buffers : pENetBuffer; bufferCount : enet_size_t):enet_uint32; var crc : enet_uint32; data, dataEnd : penet_uint8; begin crc := longword($FFFFFFFF); if not longbool(initializedCRC32) then initialize_crc32; while (bufferCount > 0) do begin data := penet_uint8 (buffers ^. data); dataEnd := penet_uint8 (PChar(data)+ buffers ^. dataLength); while PChar(data)<PChar(dataEnd) do begin crc := (crc shr 8) xor crcTable [(crc and $FF) xor data^]; inc(data); end; inc(buffers); dec(bufferCount); end; result := ENET_HOST_TO_NET_32 (not crc); end; {$pop} (** @} *) end.
namespace Sugar.IO; interface uses {$IF WINDOWS_PHONE OR NETFX_CORE} Windows.Storage, System.IO, {$ENDIF} Sugar; type FileUtils = public static class {$IF WINDOWS_PHONE OR NETFX_CORE} private method GetFolder(FileName: String): StorageFolder; method GetFile(FileName: String): StorageFile; public method Exists(aFile: File): Boolean; {$ENDIF} public method &Copy(SourceFileName: String; DestFileName: String); method &Create(FileName: String); method Delete(FileName: String); method Exists(FileName: String): Boolean; method Move(SourceFileName: String; DestFileName: String); method AppendText(FileName: String; Content: String); method AppendBytes(FileName: String; Content: array of Byte); method AppendBinary(FileName: String; Content: Binary); method ReadText(FileName: String; Encoding: Encoding := nil): String; method ReadBytes(FileName: String): array of Byte; method ReadBinary(FileName: String): Binary; method WriteBytes(FileName: String; Content: array of Byte); method WriteText(FileName: String; Content: String); method WriteBinary(FileName: String; Content: Binary); end; implementation {$IF WINDOWS_PHONE OR NETFX_CORE} class method FileUtils.GetFolder(FileName: String): StorageFolder; begin exit StorageFolder.GetFolderFromPathAsync(Path.GetParentDirectory(FileName)).Await; end; class method FileUtils.GetFile(FileName: String): StorageFile; begin exit StorageFile.GetFileFromPathAsync(FileName).Await; end; class method FileUtils.Exists(aFile: File): Boolean; begin try StorageFile(aFile).OpenReadAsync.Await.Dispose; exit true; except exit false; end; end; {$ENDIF} class method FileUtils.Copy(SourceFileName: String; DestFileName: String); begin if not Exists(SourceFileName) then raise new SugarFileNotFoundException(SourceFileName); if Exists(DestFileName) then raise new SugarIOException(ErrorMessage.FILE_EXISTS, DestFileName); {$IF COOPER} using Origin := new java.io.File(SourceFileName) do begin using NewFile := new java.io.File(DestFileName) do begin NewFile.createNewFile; var source := new java.io.FileInputStream(Origin).Channel; var dest := new java.io.FileOutputStream(NewFile).Channel; dest.transferFrom(source, 0, source.size); source.close; dest.close; end; end; {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} var Origin: StorageFile := GetFile(SourceFileName); Origin.CopyAsync(GetFolder(DestFileName), Path.GetFileName(DestFileName), NameCollisionOption.FailIfExists).Await; {$ELSEIF ECHOES} System.IO.File.Copy(SourceFileName, DestFileName); {$ELSEIF TOFFEE} var lError: Foundation.NSError := nil; if not NSFileManager.defaultManager.copyItemAtPath(SourceFileName) toPath(DestFileName) error(var lError) then raise new SugarNSErrorException(lError); {$ENDIF} end; class method FileUtils.Create(FileName: String); begin if Exists(FileName) then raise new SugarIOException(ErrorMessage.FILE_EXISTS, FileName); {$IF COOPER} new java.io.File(FileName).createNewFile; {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} GetFolder(FileName).CreateFileAsync(Path.GetFileName(FileName), CreationCollisionOption.FailIfExists).Await; {$ELSEIF ECHOES} using fs := System.IO.File.Create(FileName) do fs.Close; {$ELSEIF TOFFEE} NSFileManager.defaultManager.createFileAtPath(FileName) contents(nil) attributes(nil); {$ENDIF} end; class method FileUtils.Delete(FileName: String); begin if not Exists(FileName) then raise new SugarFileNotFoundException(FileName); {$IF COOPER} new java.io.File(FileName).delete; {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} GetFile(FileName).DeleteAsync.AsTask.Wait; {$ELSEIF ECHOES} System.IO.File.Delete(FileName); {$ELSEIF TOFFEE} var lError: NSError := nil; if not NSFileManager.defaultManager.removeItemAtPath(FileName) error(var lError) then raise new SugarNSErrorException(lError); {$ENDIF} end; class method FileUtils.Exists(FileName: String): Boolean; begin SugarArgumentNullException.RaiseIfNil(FileName, "FileName"); {$IF COOPER} exit new java.io.File(FileName).exists; {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} try exit GetFile(FileName) <> nil; except exit false; end; {$ELSEIF ECHOES} exit System.IO.File.Exists(FileName); {$ELSEIF TOFFEE} exit NSFileManager.defaultManager.fileExistsAtPath(FileName); {$ENDIF} end; class method FileUtils.Move(SourceFileName: String; DestFileName: String); begin if not Exists(SourceFileName) then raise new SugarFileNotFoundException(SourceFileName); if Exists(DestFileName) then raise new SugarIOException(ErrorMessage.FILE_EXISTS, DestFileName); {$IF COOPER} &Copy(SourceFileName, DestFileName); Delete(SourceFileName); {$ELSEIF WINDOWS_PHONE OR NETFX_CORE} &Copy(SourceFileName, DestFileName); Delete(SourceFileName); {$ELSEIF ECHOES} System.IO.File.Move(SourceFileName, DestFileName); {$ELSEIF TOFFEE} var lError: Foundation.NSError := nil; if not NSFileManager.defaultManager.moveItemAtPath(SourceFileName) toPath(DestFileName) error(var lError) then raise new SugarNSErrorException(lError); {$ENDIF} end; class method FileUtils.AppendText(FileName: String; Content: String); begin AppendBytes(FileName, Content.ToByteArray); end; class method FileUtils.AppendBytes(FileName: String; Content: array of Byte); begin var Handle := new FileHandle(FileName, FileOpenMode.ReadWrite); try Handle.Seek(0, SeekOrigin.End); Handle.Write(Content); finally Handle.Close; end; end; class method FileUtils.AppendBinary(FileName: String; Content: Binary); begin var Handle := new FileHandle(FileName, FileOpenMode.ReadWrite); try Handle.Seek(0, SeekOrigin.End); Handle.Write(Content); finally Handle.Close; end; end; class method FileUtils.ReadText(FileName: String; Encoding: Encoding := nil): String; begin exit new String(ReadBytes(FileName), Encoding); end; class method FileUtils.ReadBytes(FileName: String): array of Byte; begin exit ReadBinary(FileName).ToArray; end; class method FileUtils.ReadBinary(FileName: String): Binary; begin var Handle := new FileHandle(FileName, FileOpenMode.ReadOnly); try Handle.Seek(0, SeekOrigin.Begin); exit Handle.Read(Handle.Length); finally Handle.Close; end; end; class method FileUtils.WriteBytes(FileName: String; Content: array of Byte); begin var Handle := new FileHandle(FileName, FileOpenMode.Create); try Handle.Length := 0; Handle.Write(Content); finally Handle.Close; end; end; class method FileUtils.WriteText(FileName: String; Content: String); begin WriteBytes(FileName, Content.ToByteArray); end; class method FileUtils.WriteBinary(FileName: String; Content: Binary); begin var Handle := new FileHandle(FileName, FileOpenMode.Create); try Handle.Length := 0; Handle.Write(Content); finally Handle.Close; end; end; end.
unit Loading; interface uses System.SysUtils, System.UITypes, FMX.Types, FMX.Controls, FMX.StdCtrls, FMX.Objects, FMX.Effects, FMX.Layouts, FMX.Forms, FMX.Graphics, FMX.Ani, FMX.VirtualKeyboard, FMX.Platform; type TLoading = class private class var Layout : TLayout; class var Background : TRectangle; class var MessageLoad : TLabel; class var Animation : TFloatAnimation; class var ColorAnimation : TColorAnimation; class var Circle : TCircle; class var LabelX : TLabel; public class procedure Show(const AForm : TForm; const AMessage : string); class procedure Hide; end; implementation { TLoading } class procedure TLoading.Hide; begin if Assigned(Layout) then begin try if Assigned(MessageLoad) then MessageLoad.DisposeOf; if Assigned(Animation) then Animation.DisposeOf; if Assigned(ColorAnimation) then ColorAnimation.DisposeOf; if Assigned(Circle) then Circle.DisposeOf; if Assigned(LabelX) then LabelX.DisposeOf; if Assigned(Background) then Background.DisposeOf; if Assigned(Layout) then Layout.DisposeOf; except end; end; MessageLoad := nil; Animation := nil; Circle := nil; LabelX := nil; Layout := nil; Background := nil; end; class procedure TLoading.Show(const AForm : TForm; const AMessage: string); var FService: IFMXVirtualKeyboardService; begin //BackGround Background := TRectangle.Create(AForm); Background.Opacity := 0.6; Background.Parent := AForm; Background.Visible := true; Background.Align := TAlignLayout.Contents; Background.Fill.Color := TAlphaColorRec.Black; Background.Fill.Kind := TBrushKind.Solid; Background.Stroke.Kind := TBrushKind.None; Background.Visible := True; //Layout Text Layout := TLayout.Create(AForm); Layout.Opacity := 0; Layout.Parent := AForm; Layout.Visible := True; Layout.Align := TAlignLayout.Center; Layout.Width := 110; Layout.Height := 45; Layout.Visible := True; Circle := TCircle.Create(Layout); Circle.Parent := Layout; Circle.Width := 15; Circle.Height := 15; Circle.Visible := True; Circle.Fill.Kind := TBrushKind.Solid; Circle.Fill.Color := $FF23FFE8; Circle.Stroke.Kind := TBrushKind.None; Circle.Position.X := 0; Circle.Position.Y := 0; LabelX := TLabel.Create(Layout); LabelX.Parent := Layout; LabelX.Align := TAlignLayout.Bottom; LabelX.TextSettings.Font.Size := 10; LabelX.TextSettings.FontColor := TAlphaColorRec.White; LabelX.StyledSettings := LabelX.StyledSettings - [TStyledSetting.Size, TStyledSetting.FontColor]; LabelX.Text := 'Aguarde'; LabelX.TextSettings.HorzAlign := TTextAlign.Center; LabelX.TextSettings.VertAlign := TTextAlign.Center; //Animation Animation := TFloatAnimation.Create(Circle); Animation.Parent := Circle; Animation.StartValue := 0; Animation.StopValue := 110; Animation.Duration := 2; Animation.Loop := True; Animation.PropertyName := 'Position.X'; Animation.AutoReverse := True; Animation.AnimationType := TAnimationType.InOut; Animation.Interpolation := TInterpolationType.Elastic; Animation.Loop := True; Animation.Start; ColorAnimation := TColorAnimation.Create(Circle); ColorAnimation.Parent := Circle; ColorAnimation.Loop := True; ColorAnimation.AutoReverse := True; ColorAnimation.StartValue := $FF23FFE8; ColorAnimation.StopValue := $FF0A03C4; ColorAnimation.Duration := 2; ColorAnimation.AnimationType := TAnimationType.&In; ColorAnimation.Interpolation := TInterpolationType.Linear; ColorAnimation.PropertyName := 'Fill.Color'; ColorAnimation.Start; //Show Controls Background.AnimateFloat('Opacity', 0.6); Layout.AnimateFloat('Opacity', 1); Layout.BringToFront; //Hide KeyBoard TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(FService)); if (FService <> nil) then FService.HideVirtualKeyboard; FService := nil; end; end.
unit TextEditForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SynEditHighlighter, SynHighlighterGeneral, SynEdit, OkCancel_frame, StdCtrls, PrjConst, PropFilerEh, PropStorageEh, Vcl.Buttons, Vcl.ExtCtrls; type TTextEditForm = class(TForm) Text: TSynEdit; syngnrlsyn1: TSynGeneralSyn; lblHint: TLabel; FormStorage: TPropStorageEh; pnl1: TPanel; btnOk: TBitBtn; btnCancel: TBitBtn; procedure TextChange(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; function EditText(txt: TStrings; const title: string=''; const notice : string=''):Boolean; overload; function EditText(var txt: String; const title: string=''; const notice : string=''):Boolean; overload; function ShowText(var txt: String; const title: string=''; const notice : string=''):Boolean; implementation uses MAIN, DM; {$R *.dfm} function EditText(txt: TStrings; const title: string=''; const notice : string=''):Boolean; begin Result := False; with TTextEditForm.Create(Application) do try if title = '' then Caption := rsTextEditor else Caption := title; lblHint.Visible := (notice <> ''); lblHint.Caption := notice; Text.Lines.Clear; Text.Lines.AddStrings(txt); btnOk.Visible := False; if showmodal = mrOk then begin txt.Clear; txt.Text := Text.Lines.Text; Result := True; end; finally Free; end; end; function ShowText(var txt: String; const title: string=''; const notice : string=''):Boolean; begin Result := False; with TTextEditForm.Create(Application) do try if title = '' then Caption := rsTextEditor else Caption := title; lblHint.Visible := (notice <> ''); lblHint.Caption := notice; Text.Lines.Clear; Text.Lines.Text := txt; Text.WordWrap := True; btnOk.Enabled := False; if showmodal = mrOk then begin txt := Text.Lines.Text; Result := True; end; finally Free; end; end; function EditText(var txt: String; const title: string=''; const notice : string=''):Boolean; begin Result := False; with TTextEditForm.Create(Application) do try if title = '' then Caption := rsTextEditor else Caption := title; lblHint.Visible := (notice <> ''); lblHint.Caption := notice; Text.Lines.Clear; Text.Lines.Text := txt; btnOk.Enabled := False; ActiveControl := Text; if showmodal = mrOk then begin txt := Text.Lines.Text; Result := True; end; finally Free; end; end; procedure TTextEditForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) and (btnOk.Enabled) then ModalResult := mrOk else begin if (Ord(Key) = VK_ESCAPE) then ModalResult := mrCancel; end; end; procedure TTextEditForm.TextChange(Sender: TObject); begin btnOk.Enabled := True; end; end.
unit lipsum; //---------------------- COMMON INTERFACE -------------------------------------- {$i '../inc/header.inc'} //---------------------- IMPLEMENTATION ---------------------------------------- procedure writeGr8(x, y: byte; text: string); var bi1 : byte absolute $e0; bi2 : byte absolute $e1; tmp1 : word absolute $e2; tmp2 : word absolute $e4; textChar : word absolute $e6; begin tmp2 := (lms + y * 320) + x - 1; for bi2 := length(text) downto 1 do begin textChar := charset + ord(text[bi2]) * 8; tmp1 := tmp2 + bi2; for bi1 := 7 downto 0 do Poke(tmp1 + 40 * bi1, Peek(textChar + bi1)); end; end; procedure benchmark; var iter : byte absolute $e8; begin mode8; for iter := 23 downto 0 do writeGr8(0, iter, 'Lorem ipsum dolor sit amet orci aliquam.'~); end; //---------------------- COMMON PROCEDURE -------------------------------------- {$i '../inc/run.inc'} //---------------------- INITIALIZATION ---------------------------------------- initialization name := #$5d'Lorem Ipsum GR8'~; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.34 03/16/05 10:29:40 AM JSouthwell Added a default thread name to ease debugging of IdThreads. Rev 1.33 1/15/05 1:52:36 PM RLebeau Extra cleanup handling for the FYarn member Rev 1.32 1/6/2005 10:02:58 PM JPMugaas This should compile. Rev 1.31 1/6/05 2:33:04 PM RLebeau one more try...finally block, for Before/AfterExecute() Rev 1.29 1/5/05 5:31:08 PM RLebeau Added extra try..finally block to Execute() to free the FYarn member. Rev 1.28 6/9/2004 10:38:46 PM DSiders Fixed case for TIdNotifyThreadEvent. Rev 1.27 3/12/2004 7:11:02 PM BGooijen Changed order of commands for dotnet Rev 1.26 2004.03.01 5:12:44 PM czhower -Bug fix for shutdown of servers when connections still existed (AV) -Implicit HELP support in CMDserver -Several command handler bugs -Additional command handler functionality. Rev 1.25 2004.02.03 4:17:00 PM czhower For unit name changes. Rev 1.24 2004.01.22 5:59:12 PM czhower IdCriticalSection Rev 1.23 2003.12.28 2:33:16 PM czhower .Net finalization fix. Rev 1.22 2003.12.28 1:27:46 PM czhower .Net compatibility Rev 1.21 2003.10.24 12:59:20 PM czhower Name change Rev 1.20 2003.10.21 12:19:04 AM czhower TIdTask support and fiber bug fixes. Rev 1.19 10/15/2003 8:40:48 PM DSiders Added locaization comments. Rev 1.18 10/5/2003 3:19:58 PM BGooijen disabled some stuff for DotNet Rev 1.17 2003.09.19 10:11:22 PM czhower Next stage of fiber support in servers. Rev 1.14 2003.09.19 11:54:36 AM czhower -Completed more features necessary for servers -Fixed some bugs Rev 1.13 2003.09.18 4:43:18 PM czhower -Removed IdBaseThread -Threads now have default names Rev 1.12 12.9.2003 ã. 16:42:08 DBondzhev Fixed AV when exception is raised in BeforeRun and thread is terminated before Start is compleated Rev 1.11 2003.07.08 2:41:52 PM czhower Avoid calling SetThreadName if we do not need to Rev 1.10 08.07.2003 13:16:18 ARybin tiny opt fix Rev 1.9 7/1/2003 7:11:30 PM BGooijen Added comment Rev 1.8 2003.07.01 4:14:58 PM czhower Consolidation. Added Name, Loop Rev 1.7 04.06.2003 14:06:20 ARybin bug fix & limited waiting Rev 1.6 28.05.2003 14:16:16 ARybin WaitAllThreadsTerminated class method Rev 1.5 08.05.2003 12:45:10 ARybin "be sure" fix Rev 1.4 4/30/2003 4:53:26 PM BGooijen Fixed bug in Kylix where GThreadCount was not decremented Rev 1.3 4/22/2003 4:44:06 PM BGooijen changed Handle to ThreadID Rev 1.2 3/22/2003 12:53:26 PM BGooijen - Exceptions in the constructor are now handled better. - GThreadCount can't become negative anymore Rev 1.1 06.03.2003 11:54:24 ARybin TIdThreadOptions: is thread Data owner, smart Cleanup Rev 1.0 11/13/2002 09:01:14 AM JPMugaas 2002-03-12 -Andrew P.Rybin -TerminatingExceptionClass, etc. 2002-06-20 -Andrew P.Rybin -"Terminated Start" bug fix (FLock.Leave AV) -Wait All threads termination in FINALIZATION (prevent AV in WinSock) -HandleRunException 2003-01-27 -Andrew P.Rybin -TIdThreadOptions } unit IdThread; { 2002-03-12 -Andrew P.Rybin -TerminatingExceptionClass, etc. 2002-06-20 -Andrew P.Rybin -"Terminated Start" bug fix (FLock.Leave AV) -Wait All threads termination in FINALIZATION (prevent AV in WinSock) -HandleRunException 2003-01-27 -Andrew P.Rybin -TIdThreadOptions } interface {$I IdCompilerDefines.inc} uses Classes, IdGlobal, IdException, IdYarn, IdTask, IdThreadSafe, SysUtils; const IdWaitAllThreadsTerminatedCount = 1 * 60 * 1000; IdWaitAllThreadsTerminatedStep = 250; type EIdThreadException = class(EIdException); EIdThreadTerminateAndWaitFor = class(EIdThreadException); TIdThreadStopMode = (smTerminate, smSuspend); TIdThread = class; TIdExceptionThreadEvent = procedure(AThread: TIdThread; AException: Exception) of object; TIdNotifyThreadEvent = procedure(AThread: TIdThread) of object; TIdSynchronizeThreadEvent = procedure(AThread: TIdThread; AData: Pointer) of object; TIdThreadOptions = set of (itoStopped, itoReqCleanup, itoDataOwner, itoTag); TIdThread = class(TThread) protected FData: TObject; FLock: TIdCriticalSection; FLoop: Boolean; FName: string; FStopMode: TIdThreadStopMode; FOptions: TIdThreadOptions; FTerminatingException: String; FTerminatingExceptionClass: TClass; FYarn: TIdYarn; // FOnException: TIdExceptionThreadEvent; FOnStopped: TIdNotifyThreadEvent; // procedure AfterRun; virtual; //3* not abstract - otherwise it is required procedure AfterExecute; virtual;//5 not abstract - otherwise it is required procedure BeforeExecute; virtual;//1 not abstract - otherwise it is required procedure BeforeRun; virtual; //2* not abstract - otherwise it is required procedure Cleanup; virtual;//4* procedure DoException(AException: Exception); virtual; procedure DoStopped; virtual; procedure Execute; override; function GetStopped: Boolean; function HandleRunException(AException: Exception): Boolean; virtual; procedure Run; virtual; abstract; class procedure WaitAllThreadsTerminated( AMSec: Integer = IdWaitAllThreadsTerminatedCount); public constructor Create(ACreateSuspended: Boolean = True; ALoop: Boolean = True; const AName: string = ''); virtual; destructor Destroy; override; procedure Start; {$IFDEF DEPRECATED_TThread_SuspendResume}reintroduce;{$ENDIF} virtual; procedure Stop; virtual; procedure Synchronize(Method: TThreadMethod); overload; //BGO:TODO procedure Synchronize(Method: TMethod); overload; // Here to make virtual procedure Terminate; virtual; procedure TerminateAndWaitFor; virtual; // property Data: TObject read FData write FData; property Loop: Boolean read FLoop write FLoop; property Name: string read FName write FName; property ReturnValue; property StopMode: TIdThreadStopMode read FStopMode write FStopMode; property Stopped: Boolean read GetStopped; property Terminated; // TODO: Change this to be like TIdFiber. D6 implementation is not as good // as what is done in TIdFiber. property TerminatingException: string read FTerminatingException; property TerminatingExceptionClass: TClass read FTerminatingExceptionClass; //Represents the thread or fiber for the scheduler of the thread. property Yarn: TIdYarn read FYarn write FYarn; // property OnException: TIdExceptionThreadEvent read FOnException write FOnException; property OnStopped: TIdNotifyThreadEvent read FOnStopped write FOnStopped; end; TIdThreadWithTask = class(TIdThread) protected FTask: TIdTask; // procedure AfterRun; override; procedure BeforeRun; override; procedure Run; override; procedure DoException(AException: Exception); override; procedure SetTask(AValue: TIdTask); public // Defaults because // Must always create suspended so task can be set // And a bit crazy to create a non looped task constructor Create( ATask: TIdTask = nil; const AName: string = '' ); reintroduce; virtual; destructor Destroy; override; // // Must be writeable because tasks are often created after thread or // thread is pooled property Task: TIdTask read FTask write SetTask; end; TIdThreadClass = class of TIdThread; TIdThreadWithTaskClass = class of TIdThreadWithTask; var // GThreadCount shoudl be in implementation as it is not needed outside of // this unit. However with D8, GThreadCount will be deallocated before the // finalization can run and thus when the finalizaiton accesses GThreadCount // in TerminateAll an error occurs. Moving this declaration to the interface // "fixes" it. GThreadCount: TIdThreadSafeInteger = nil; implementation uses //facilitate inlining only. {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.Threading, {$ENDIF} {$ENDIF} {$IFDEF USE_VCL_POSIX} Posix.SysSelect, Posix.SysTime, {$ENDIF} {$IFDEF VCL_XE3_OR_ABOVE} System.SyncObjs, {$ENDIF} IdResourceStringsCore; class procedure TIdThread.WaitAllThreadsTerminated(AMSec: Integer = IdWaitAllThreadsTerminatedCount); begin while AMSec > 0 do begin if GThreadCount.Value = 0 then begin Break; end; IndySleep(IdWaitAllThreadsTerminatedStep); AMSec := AMSec - IdWaitAllThreadsTerminatedStep; end; end; procedure TIdThread.TerminateAndWaitFor; begin if FreeOnTerminate then begin raise EIdThreadTerminateAndWaitFor.Create(RSThreadTerminateAndWaitFor); end; Terminate; Start; //resume WaitFor; end; procedure TIdThread.BeforeRun; begin end; procedure TIdThread.AfterRun; begin end; procedure TIdThread.BeforeExecute; begin end; procedure TIdThread.AfterExecute; begin end; procedure TIdThread.Execute; begin // Must make this call from INSIDE the thread. The call in Create // was naming the thread that was creating this thread. :( // // RLebeau - no need to put this inside the try blocks below as it // already uses its own try..except block internally if Name = '' then begin Name := 'IdThread (unknown)'; end; SetThreadName(Name); try BeforeExecute; try while not Terminated do begin if Stopped then begin DoStopped; // It is possible that either in the DoStopped or from another thread, // the thread is restarted, in which case we dont want to restop it. if Stopped then begin // DONE: if terminated? if Terminated then begin Break; end; // Thread manager will revive us {$IFDEF DEPRECATED_TThread_SuspendResume} Suspended := True; {$ELSE} Suspend; {$ENDIF} if Terminated then begin Break; end; end; end; Include(FOptions, itoReqCleanup); try try try BeforeRun; if Loop then begin while not Stopped do begin try Run; except on E: Exception do begin if not HandleRunException(E) then begin Terminate; raise; end; end; end; end; end else begin try Run; except on E: Exception do begin if not HandleRunException(E) then begin Terminate; raise; end; end; end; end; finally AfterRun; end; except Terminate; raise; end; finally Cleanup; end; end; finally AfterExecute; end; except on E: Exception do begin FTerminatingExceptionClass := E.ClassType; FTerminatingException := E.Message; DoException(E); Terminate; end; end; end; constructor TIdThread.Create(ACreateSuspended: Boolean; ALoop: Boolean; const AName: string); begin {$IFDEF DOTNET} inherited Create(True); {$ENDIF} FOptions := [itoDataOwner]; if ACreateSuspended then begin Include(FOptions, itoStopped); end; FLock := TIdCriticalSection.Create; Loop := ALoop; Name := AName; // {$IFDEF DOTNET} if not ACreateSuspended then begin {$IFDEF DEPRECATED_TThread_SuspendResume} Suspended := False; {$ELSE} Resume; {$ENDIF} end; {$ELSE} // // Most things BEFORE inherited - inherited creates the actual thread and if // not suspended will start before we initialize inherited Create(ACreateSuspended); {$IFNDEF VCL_6_OR_ABOVE} // Delphi 6 and above raise an exception when an error occures while // creating a thread (eg. not enough address space to allocate a stack) // Delphi 5 and below don't do that, which results in a TIdThread // instance with an invalid handle in it, therefore we raise the // exceptions manually on D5 and below if (ThreadID = 0) then begin IndyRaiseLastError; end; {$ENDIF} {$ENDIF} // Last, so we only do this if successful GThreadCount.Increment; end; destructor TIdThread.Destroy; begin FreeOnTerminate := False; //prevent destroy between Terminate & WaitFor Terminate; try if itoReqCleanup in FOptions then begin Cleanup; end; finally // RLebeau- clean up the Yarn one more time, in case the thread was // terminated after the Yarn was assigned but the thread was not // re-started, so the Yarn would not be freed in Cleanup() try FreeAndNil(FYarn); finally // Protect FLock if thread was resumed by Start Method and we are still there. // This usually happens if Exception was raised in BeforeRun for some reason // And thread was terminated there before Start method is completed. FLock.Enter; try finally FLock.Leave; end; FreeAndNil(FLock); GThreadCount.Decrement; end; end; inherited Destroy; //+WaitFor! end; procedure TIdThread.Start; begin FLock.Enter; try if Stopped then begin // Resume is also called for smTerminate as .Start can be used to initially start a // thread that is created suspended if Terminated then begin Include(FOptions,itoStopped); end else begin Exclude(FOptions,itoStopped); end; {$IFDEF DEPRECATED_TThread_SuspendResume} Suspended := False; {$ELSE} Resume; {$ENDIF} {APR: [in past] thread can be destroyed here! now Destroy wait FLock} end; finally FLock.Leave; end; end; procedure TIdThread.Stop; begin FLock.Enter; try if not Stopped then begin case FStopMode of smTerminate: Terminate; smSuspend: {DO not suspend here. Suspend is immediate. See Execute for implementation}; end; Include(FOptions, itoStopped); end; finally FLock.Leave; end; end; function TIdThread.GetStopped: Boolean; begin if Assigned(FLock) then begin FLock.Enter; try // Suspended may be True if checking stopped from another thread Result := Terminated or (itoStopped in FOptions) or Suspended; finally FLock.Leave; end; end else begin Result := True; //user call Destroy end; end; procedure TIdThread.DoStopped; begin if Assigned(OnStopped) then begin OnStopped(Self); end; end; procedure TIdThread.DoException(AException: Exception); begin if Assigned(FOnException) then begin FOnException(Self, AException); end; end; procedure TIdThread.Terminate; begin //this assert can only raise if terminate is called on an already-destroyed thread Assert(FLock<>nil); FLock.Enter; try Include(FOptions, itoStopped); inherited Terminate; finally FLock.Leave; end; end; procedure TIdThread.Cleanup; begin Exclude(FOptions, itoReqCleanup); FreeAndNil(FYarn); if itoDataOwner in FOptions then begin FreeAndNil(FData); end; end; function TIdThread.HandleRunException(AException: Exception): Boolean; begin // Default behavior: Exception is death sentence Result := False; end; procedure TIdThread.Synchronize(Method: TThreadMethod); begin inherited Synchronize(Method); end; //BGO:TODO //procedure TIdThread.Synchronize(Method: TMethod); //begin // inherited Synchronize(TThreadMethod(Method)); //end; { TIdThreadWithTask } procedure TIdThreadWithTask.AfterRun; begin FTask.DoAfterRun; inherited AfterRun; end; procedure TIdThreadWithTask.BeforeRun; begin inherited BeforeRun; FTask.DoBeforeRun; end; procedure TIdThreadWithTask.DoException(AException: Exception); begin inherited DoException(AException); FTask.DoException(AException); end; constructor TIdThreadWithTask.Create(ATask: TIdTask; const AName: string); begin inherited Create(True, True, AName); FTask := ATask; end; destructor TIdThreadWithTask.Destroy; begin FreeAndNil(FTask); inherited Destroy; end; procedure TIdThreadWithTask.Run; begin if not FTask.DoRun then begin Stop; end; end; procedure TIdThreadWithTask.SetTask(AValue: TIdTask); begin if FTask <> AValue then begin FreeAndNil(FTask); FTask := AValue; end; end; {$IFDEF REGISTER_EXPECTED_MEMORY_LEAK} type TIdThreadSafeIntegerAccess = class(TIdThreadSafeInteger); {$ENDIF} initialization // RLebeau 7/19/09: According to RAID #271221: // // "Indy always names the main thread. It should not name the main thread, // it should only name threads that it creates. This basically means that // any app that uses Indy will end up with the main thread named "Main". // // The IDE currently names it's main thread, but because Indy is used by // the dcldbx140.bpl package which gets loaded by the IDE, the name used // for the main thread always ends up being overwritten with the name // Indy gives it." // // So, DO NOT uncomment the following line... // SetThreadName('Main'); {do not localize} GThreadCount := TIdThreadSafeInteger.Create; {$IFNDEF FREE_ON_FINAL} {$IFDEF REGISTER_EXPECTED_MEMORY_LEAK} IndyRegisterExpectedMemoryLeak(GThreadCount); IndyRegisterExpectedMemoryLeak(TIdThreadSafeIntegerAccess(GThreadCount).FCriticalSection); {$ENDIF} {$ENDIF} finalization // This call hangs if not all threads have been properly destroyed. // But without this, bad threads can often have worse results. Catch 22. // TIdThread.WaitAllThreadsTerminated; {$IFDEF FREE_ON_FINAL} //only enable this if you know your code exits thread-clean FreeAndNil(GThreadCount); {$ENDIF} end.
unit clBaixas; interface uses clEntrega, clConexao; type TBaixa = Class(TEntrega) private protected _conexao: TConexao; public constructor Create; destructor Destroy; function JaExiste(): Boolean; function Baixar(): Boolean; function UltimaBaixa(): String; end; const TABLENAME = 'TBENTREGAS'; implementation uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, uGlobais; constructor TBaixa.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TBaixa.Destroy; begin _conexao.Free; end; function TBaixa.JaExiste(): Boolean; begin try Result := False; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add(' WHERE NUM_NOSSONUMERO = :NOSSONUMERO'); ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; dm.ZConn.PingServer; Open; if not(IsEmpty) then Result := True; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TBaixa.Baixar(): Boolean; begin try Result := False; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DAT_PREV_DISTRIBUICAO = :PREVDISTRIBUICAO, ' + 'DAT_BAIXA = :BAIXA, ' + 'DOM_BAIXADO = :BAIXADO, ' + 'DAT_ENTREGA = :ENTREGA, ' + 'COD_AGENTE = :AGENTE, ' + 'COD_ENTREGADOR = :ENTREGADOR, ' + 'DAT_ATRIBUICAO = :ATRIBUICAO, ' + 'VAL_VERBA_ENTREGADOR = :VERBA, ' + 'QTD_DIAS_ATRASO = :DIASATRASO, ' + 'QTD_VOLUMES_EXTRA = :VOLUMESEXTRA, ' + 'VAL_VOLUMES_EXTRA = :VALOREXTRA, ' + 'QTD_PESO_COBRADO = :PESOCOBRADO, ' + 'DES_TIPO_PESO = :TIPOPESO, ' + 'DES_RASTREIO = :RASTREIO, ' + 'NUM_CTRC := :CTRC ' + 'WHERE ' + 'NUM_NOSSONUMERO = :NOSSONUMERO AND DOM_PAGO <> ' + QuotedStr('S'); Self.Rastreio := Self.Rastreio + #13 + 'Importação de Baixa da Entrega feita em ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' por ' + uGlobais.sNomeUsuario; ParamByName('NOSSONUMERO').AsString := Self.NossoNumero; ParamByName('PREVDISTRIBUICAO').AsDate := Self.PrevDistribuicao; ParamByName('BAIXA').AsDateTime := Self.DataBaixa; ParamByName('BAIXADO').AsString := Self.Baixado; ParamByName('ENTREGA').AsDate := Self.Entrega; ParamByName('ATRIBUICAO').AsDateTime := Self.Atribuicao; ParamByName('VERBA').AsFloat := Self.VerbaEntregador; ParamByName('AGENTE').AsInteger := Self.Agente; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('DIASATRASO').AsInteger := Self.DiasAtraso; ParamByName('VOLUMESEXTRA').AsFloat := Self.VolumesExtra; ParamByName('VALOREXTRA').AsFloat := Self.ValorExtra; ParamByName('PESOCOBRADO').AsFloat := Self.PesoCobrado; ParamByName('TIPOPESO').AsString := Self.TipoPeso; ParamByName('RASTREIO').AsString := Self.Rastreio; if Self.DiasAtraso > 0 then begin ParamByName('CTRC').AsInteger := 1; end else begin ParamByName('CTRC').AsInteger := 0; end; dm.ZConn.PingServer; ExecSQL; Self.Rastreio := ''; end; dm.qryCRUD.Close; dm.qryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TBaixa.UltimaBaixa(): String; begin try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT MAX(DAT_BAIXA) DATA FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not(IsEmpty) then Result := dm.QryGetObject.FieldByName('DATA').AsString; end; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; end.
{$M-} {This is the source for the QUASAR interface. See QUASAR.PAS for documentation} program qsr; const ntries=10; {jsys definitions} msend=510B; mrecv=511B; mutil=512B; erstr=11B; disms=167B; {parameters} priou=101B; ipciw=1B; muqry=20B; mursp=25B; spqsr=2; mucre=6; ipcf16=601035B; type {packetdescriptor describes the IPCF packet descriptor, which is what you give to MSEND, MRECV, etc. See Monitor calls for details. The case Boolean is because "page mode" IPCF needs a page number, which we handle as an integer, but normal mode needs an address, which we handle as a pointer.} packetdescriptor=packed record ipcfl:integer; ipcfs:integer; ipcfr:integer; case Boolean of true: (ipcfpl:0..777777B;ipcfpn:0..777777B; ipcfd:integer); false: (ipcxx:0..777777B;ipcfpt:^sendmessage) end; messtypes=(type0); {sendmessage is used messages we send to Quasar. For simplicity, we always send in page mode. Here is an explanation of the general structure of messages to QUASAR: length of whole message,,message type code flags - bit 0 is always a flag asking for an acknowlegement typically the acknowlegement is the text saying "5 jobs killed", that the EXEC prints with [] around it. acknowlegement code - we could supply a code so we can tell the acknowlegements apart from each other message-specific flags count of arguments. The rest of the message consists of "arguments", each of which has the following form. This is the number of them. length of argument including this word,,argument type code data for argument} sendmessage=record case messtypes of type0: (qsrmsg:array[0..511]of integer) end; smesspt = ^sendmessage; {message is used for received messages. The fields described below are the standard QUASAR message fields. We typically ignore the header, which contains a count and message type. The next word contains some flags, of which we are only interested in MORE. This indicates when a message is too long, and is continued into another one. NUMARGS indicates the number of fields in this message. The rest of it then contains the messages in the usual QUASAR form of COUNT,,MSGTYPE followed by data. We let you access halfwords in order to read these headers, and characters in order to get at the data, which is text for the messages we are interested in. Note that some messages we receive are in page mode and some in normal mode. However we always use the same area, so no one needs to know about this except that routine that does the MRECV.} message=packed record header:array[0..2]of integer; dumflg:Boolean; more:Boolean; numargs:integer; case Boolean of true: (halfs:packed array[0..1013]of 0..777777B); false: (chars:packed array[0..2534]of char) end; messpt=^message; {The following types are used to define parameters to various switches. QUEUE is sort of interesting. There are two different representations used when talking to QUASAR to tell it what kind of object you are talking about. The most common one is an integer. But in the LIST command there is a word of bits, with one bit for each object type. This lets you ask to see any combination of queues you want. The QUEUE type is defined so that QUEUESET gives you the right bits. To get the integer version for use in the other commands, you have to translate using the table QUEUETRAN. We prefer to always use the same representation for queues. We chose the one used for LIST because the other one has gaps in the assignments, as you will see if you look at QUEUETRAN.} queue=(batch,printer,cardpunch,papertape,plotter,dumqueue,mount,retrieve); queueset = set of queue; brevity=(notverbose,verbose,brief); {Fstring is used to define arguments which are going to be passed as STRING. When the caller specifies STRING, the callee see two variables: the data and a length code. Normally the data is defined as a packed array of char, but for this program we chose to define it as words. Note that Pascal will not make sure they are ASCIZ. Thus the routines that take string arguments use the length code to figure out how many words to copy, and then clear the rest of the last word.} fstring=array[0..100]of integer; ptpform=(tapedum,ptpascii,ptpimage,ptpimagebinary,ptpbinary); outputlog=(outlogdum,lognever,logalways,logerror); notification=(notifdum,notifytty,notifymail,notifyjob); batchlog=(batlogdum,logappend,logsupercede,logspool); sstring=packed array[1..12]of char; var packet:packetdescriptor; mess:smesspt; {the place we put messages we are sending} smesspage:integer; {page number of mess^} memdone: Boolean; {indicates we have done memory allocation} m:messpt; {the place we receive messages} messpage:integer; {page number of m^} {nextindex is used by the command to create queue entries. This builds a message incrementally, and nextindex keeps track of the place where the next option should go in the block we are building. MYPID is the pid for this process, which is assigned once at the beginning. QSRPID is Quasar's pid. We get it each time we want to do a command, in case Quasar happens to have crashed and restarted.} nextindex,mypid,qsrpid:integer; ret:integer; userlen,i,j:integer; conv:packed record case Boolean of true:(word:integer); false:(queues:queueset) end; {Queuetran is used to convert from our normal representation of queue types to one often used by Quasar. See the definition of QUEUE above for details} queuetran:array[queue]of integer; {TEST is probably not used at the moment. It is useful for testing when we need to build an FSTRING} test:record case Boolean of true:(words:fstring); false:(chars:packed array[1..300]of char) end; {TESTS is also used for testing} tests:sstring; {Here is the conversion table from the bit numbers used in LIST to the integers used in the other request types.} initprocedure; begin queuetran[batch] := 4b; queuetran[printer] := 3b; queuetran[cardpunch] := 5b; queuetran[papertape] := 6b; queuetran[plotter] := 7b; queuetran[mount] := 14b; queuetran[retrieve] := 17B; end; procedure getpages(num:integer;var page:integer;var loc:messpt); extern; procedure getpagex(num:integer;var page:integer;var loc:smesspt); extern; procedure quit; extern; function to6(x:alfa):integer; extern; procedure fatal; {Print most recent error and quit} begin jsys(erstr,3;priou,400000B:-1,0); quit end; function getqsr:integer; {Returns Quasar's PID} var argblk:array[0..2]of integer; begin argblk[0] := mursp; {get a cataloged PID} argblk[1] := spqsr; {Quasar} jsys(mutil,2,ret;3,argblk); {Now ask for the pid} if ret <> 2 then fatal; getqsr := argblk[2] end; function getme:integer; {Gets and returns a PID for me} var argblk:array[0..2]of integer; begin argblk[0] := mucre; {create a pid} argblk[1] := 400000B; {for me} jsys(mutil,2,ret;3,argblk); {Now ask for the pid} if ret <> 2 then fatal; getme := argblk[2] end; procedure getmem; {Allocate memory} begin getpagex(1,smesspage,mess); getpages(1,messpage,m); {a page for page mode, since it must be on a page boundary} end; procedure reqlist(howmuch:brevity;which:queueset;user:integer); {Request a listing of queues} begin with mess^ do {create a quasar message asking for a listing of the queues} begin qsrmsg[0] := 7000010B; {length,,message type code} qsrmsg[1] := 400000000000B; {ask for acknowlege message} qsrmsg[2] := 0; {no ack code} case howmuch of {flags - we use only the verbosity flag} notverbose: qsrmsg[3] := 0; verbose: qsrmsg[3] := 100000000000B; brief: qsrmsg[3] := 200000000000B end; qsrmsg[4] := 1; {number of args} qsrmsg[5] := 2000000B; {2 words,,arg type=tell us about these queues} conv.queues := which; qsrmsg[6] := conv.word; {bits, one per queue} if user <> 0 {if he specifies a user name} then begin qsrmsg[0] := 11000010B; {the block is longer} qsrmsg[4] := 2; {it has 2 args} qsrmsg[7] := 2000001B; {here is the extra arg: 2 words,,user spec} qsrmsg[10B] := user {and the data: user number} end end; with packet do begin ipcfl := 0; ipcfs := mypid; ipcfr := qsrpid; ipcfpl := 9; ipcfpt := mess; end; jsys(msend,2,ret;4,packet); {Now send the message} if ret <> 2 then fatal; end; procedure getack(dobrackets:Boolean); {GETACK is a general routine used to wait for Quasar to send a response. For this program, we will always get back a response that has some text in it that should be printed on the terminal. We don't bother to analyze the messages. If they have anything in them at all, the last argument will be text. So we just get the last argument. Note that sometimes the text will be too long for one message, in which case the MORE bit will be set. There is a slight complexity in that we don't know in advance whether the messge will be send in page mode or normal mode. Quasar looks at the length, and uses page mode for big ones and normal for small ones. We first try page mode, and if that doesn't work, try normal mode. DOBRACKETS indicates we want to print [] around it. We do that in this routine instead of outside for reasons of timing. If you tried WRITE('['); GETACK; WRITE(']'), the result would be [<long pause><message>]. The long pause is unesthetic, so we delay doing the [ until we have the response to print. That requires it to be done in this routine.} var i,j,pos:integer; pagemode:Boolean; begin repeat {keep going as long as last message has MORE set, as it indicates continuations} repeat {keep going until we get something from QUASAR, in case someone else sends us junk mail. Also throw away trivial messages from QUASAR. Not sure why they happen} with packet do {first try page mode} begin ipcfl := 200000B; {Page mode} ipcfs := 0; ipcfr := mypid; ipcfpl := 512; ipcfpn := messpage end; jsys(mrecv,2,ret;4,packet;i); {wait until there is something} if ret <> 2 {Failed} then if i = ipcf16 {We get this if they sent normal mode} then begin {since we tried to read it in page mode} with packet do {Try again in normal mode} begin ipcfl := 0; {normal mode} ipcfs := 0; ipcfr := mypid; ipcfpl := 512; ipcfpn := messpage * 1000B end; jsys(mrecv,2,ret;4,packet); {get ack} if ret <> 2 {If this fails, too, real error} then fatal end else fatal; {some other failure cause - real error} until (packet.ipcfs = qsrpid) and (m^.numargs > 0); {keep going until we get something from QUASAR and it is non-trivial} {The following delightful code finds the last "argument" in the message. POS is the position of the header of the argument we are currently looking at. The only way to find the Nth argument is to skip the previous N-1} pos := 0; {POS is kept in half-words} for i := 2 to m^.numargs do {skip arguments til the last} pos := pos + 2*m^.halfs[pos]; j := ((pos div 2) + 1) * 5; {now convert offset to this arg to char's} if dobrackets then write(tty,'['); for i := j to j + 5*m^.halfs[pos] - 1 do {write out the chars. 5*m^.half[pos] is the number of chars. m^.half[pos] is simply the left half of the header for the last arg} if m^.chars[i] = chr(0) {it is ASCIZ, so stop on nul} then goto 1 else write(tty,m^.chars[i]); 1: if dobrackets then writeln(tty,']'); until not m^.more end; procedure dolist(howmuch:brevity;which:queueset;user:integer); {INFO OUTPUT - main routine} begin qsrpid := getqsr; reqlist(howmuch,which,user); getack(false) end; procedure startqueue(what:queue;jobname:alfa;var fname:fstring;flen:integer); {PRINT, SUBMIT, etc. These have to be done in three pieces because of the presence of multiple switches. It is not practical to have that many arguments to the procedure. So we have this procedure, which sets up the part of the message containing required arguments. Then the user calls a routine for each switch he wants. Each of these just appends an argument specifying the data needed for that switch. Finally, DOQUEUE puts in a final count and sends off the message, waiting for ack if the user wants to.} var conv:record case Boolean of true:(word:integer); false:(chars:packed array[0..4]of char) end; i:integer; begin qsrpid := getqsr; with mess^ do begin qsrmsg[0] := 37B; {message type - count will come at the end} qsrmsg[1] := 0; {no switches} qsrmsg[2] := 0; {no ack code} qsrmsg[3] := 0; {no message-specific switches} qsrmsg[4] := 3; {3 required arguments} qsrmsg[5] := 2000024B; {count,,type of queue} qsrmsg[6] := queuetran[what]; {here is the queue type} qsrmsg[7] := 2000032B; {count,,job name} qsrmsg[8] := to6(jobname); {here is the job name (sixbit)} qsrmsg[9] := (flen div 5 + 2) * 1000000B + 10B; {count,,file name} for i := 0 to flen div 5 do {copies the file name} qsrmsg[10+i] := fname[i]; conv.word := fname[flen div 5]; {make asciz by setting unused char's} for i := flen mod 5 to 4 do {in last word to 0} conv.chars[i] := chr(0); qsrmsg[10 + flen div 5] := conv.word; nextindex := 11 + flen div 5; {set up NEXTINDEX so switch routines know where to put their data} end; end; procedure queueswitch(index:integer;value:integer); {general routine to add a switch. INDEX is the argument type code for the particular switch. VALUE is the value of the switch} begin mess^.qsrmsg[4] := mess^.qsrmsg[4] + 1; {say we have one more arg} mess^.qsrmsg[nextindex] := index+ 2000000B; {count,,switch type code} mess^.qsrmsg[nextindex+1] := value; {value} nextindex := nextindex+2; {advance so next switch goes after this} end; procedure qtextswitch(index:integer;var name:fstring;len:integer); {This is for switches whose value is text. If you understand the last two routines, you should understand this.} var conv:record case Boolean of true:(word:integer); false:(chars:packed array[0..4]of char) end; begin with mess^ do begin qsrmsg[4] := qsrmsg[4] + 1; qsrmsg[nextindex] := (len div 5 + 2) * 1000000B + index; qsrmsg[nextindex + 1 + len div 5] := 0; for i := 0 to len div 5 do qsrmsg[nextindex + 1 + i] := name[i]; conv.word := name[len div 5]; {make asciz} for i := len mod 5 to 4 do conv.chars[i] := chr(0); qsrmsg[nextindex + 1 + len div 5] := conv.word; nextindex := nextindex + 2 + len div 5; end; end; {Now here are the switches, in numerical order} procedure qcopies(copies:integer); begin queueswitch(11B,copies); end; procedure qform(name:alfa); begin queueswitch(12B,to6(name)); end; procedure qtapeform(form:ptpform); begin queueswitch(13B,ord(form)) end; procedure qdisposedelete; begin queueswitch(14B,1); end; procedure qunit(unit:integer); begin queueswitch(15B,unit+3000000B) end; procedure qlower; begin queueswitch(15B,1000000B) end; procedure qupper; begin queueswitch(15B,2000000B) end; procedure qafter(idtime:integer); begin queueswitch(16B,idtime) end; procedure qlimit(limit:integer); begin queueswitch(17B,limit) end; procedure qunique(unique:Boolean); begin queueswitch(20B,1+ord(unique)) end; procedure qrestart(restart:Boolean); begin queueswitch(21B,1+ord(restart)) end; procedure qoutput(log:outputlog); begin queueswitch(22B,ord(log)) end; procedure qaccount(var acctname:fstring;acctlen:integer); begin qtextswitch(23B,acctname,acctlen) end; procedure qnode(node:alfa); begin queueswitch(25B,to6(node)) end; procedure qusername(var username:fstring;userlen:integer); begin qtextswitch(26B,username,userlen) end; procedure quser(user:integer); begin queueswitch(27B,user) end; procedure qnotify(how:notification); begin queueswitch(30B,ord(how)) end; procedure qbatchlog(how:batchlog); begin queueswitch(31B,ord(how)) end; procedure qconnected(dir:integer); begin queueswitch(33B,dir) end; procedure qnote(var notestr:sstring;notelen:integer); {What fun! This switch takes 1 - 12 char's, and converts them to sixbit} var i:integer;a:alfa; begin a := ' '; with mess^ do begin qsrmsg[4] := qsrmsg[4] + 1; if notelen <= 6 { <= 6 char's, will take one word for value} then begin qsrmsg[nextindex] := 2000034B; {length,, arg type} for i := 1 to notelen do a[i] := notestr[i]; qsrmsg[nextindex+1] := to6(a); nextindex := nextindex+2 end else begin {two words for value (3 total)} qsrmsg[nextindex] := 3000034B; {length,, arg type} for i := 1 to 6 do a[i] := notestr[i]; qsrmsg[nextindex+1] := to6(a); a := ' '; for i := 7 to notelen do a[i-6] := notestr[i]; qsrmsg[nextindex+2] := to6(a); nextindex := nextindex + 3 end; end; end; procedure qbegin(block:integer); begin queueswitch(35B,block) end; procedure qpriority(priority:integer); begin queueswitch(36B,priority) end; procedure doqueue(doack:Boolean); {Now we send the request} begin if doack {If he wants an ack, set that flag} then mess^.qsrmsg[1] := 400000000000B; mess^.qsrmsg[0] := nextindex * 1000000B + 37B; {supply the total length} with packet do begin ipcfl := 200000B; {Page mode} ipcfs := mypid; ipcfr := qsrpid; ipcfpl := 512; ipcfpn := smesspage; end; jsys(msend,2,ret;4,packet); {Now send request} if ret <> 2 then fatal; if doack {and wait for ack if he wants it} then getack(true); end; procedure dokill(what:queue;jobname:alfa;mask:integer;seqnum,reqnum:integer; var owner:fstring;ownerlen:integer;doack:Boolean); {Kill a request. This is straightforward. See the documentation for what the args mean. We just pass them to Quasar.} var conv:record case Boolean of true:(word:integer); false:(chars:packed array[0..4]of char) end; begin qsrpid := getqsr; with mess^ do begin qsrmsg[0] := 20000012B; {length,,this is a kill} if doack {if he wants ack, ask for it} then qsrmsg[1] := 400000000000B; qsrmsg[2] := 0; {no ack code} qsrmsg[3] := queuetran[what]; {queue type} qsrmsg[4] := to6(jobname); {job name} qsrmsg[5] := mask; {job name mask} qsrmsg[6] := seqnum; qsrmsg[7] := reqnum; for i := 0 to ownerlen div 5 do {owner - make it ASCIZ} qsrmsg[8+i] := owner[i]; conv.word := owner[ownerlen div 5]; for i := ownerlen mod 5 to 4 do conv.chars[i] := chr(0); qsrmsg[8+ownerlen div 5] := conv.word; end; with packet do begin ipcfl := 0; ipcfs := mypid; ipcfr := qsrpid; ipcfpl := 20B; ipcfpt := mess; end; jsys(msend,2,ret;4,packet); {Now ask for kill} if ret <> 2 then fatal; if doack {and wait for ack if he wants it} then getack(true); end; procedure qsrinit; begin mypid := getme; getmem end .
unit CapitolSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, ComCtrls, InternationalizerComponent; const tidHasRuler = 'HasRuler'; tidYearsToElections = 'YearsToElections'; tidRulerActualPrestige = 'RulerActualPrestige'; tidRulerRating = 'RulerRating'; tidTycoonsRating = 'TycoonsRating'; tidCovCount = 'covCount'; const facStoppedByTycoon = $04; type TCapitolPoliticSheetHandler = class; TCapitolSheetViewer = class(TVisualControl) Label9: TLabel; xfer_ActualRuler: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; xfer_RulerRating: TLabel; xfer_TycoonsRating: TLabel; xfer_RulerPeriods: TLabel; xfer_YearsToElections: TLabel; btnVisitPolitics: TFramedButton; Label8: TLabel; xfer_QOL: TLabel; Label14: TLabel; Panel1: TPanel; Coverage: TListView; InternationalizerComponent1: TInternationalizerComponent; procedure btnVisitPoliticsClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TCapitolPoliticSheetHandler; protected procedure SetParent(which : TWinControl); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; end; TCapitolPoliticSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TCapitolSheetViewer; public function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedGetCoverage(const parms : array of const); procedure syncGetCoverage(const parms : array of const); end; var CapitolSheetViewer: TCapitolSheetViewer; function CapitolPoliticSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation {$R *.DFM} uses Threads, SheetHandlerRegistry, FiveViewUtils, CacheCommon, VoyagerServerInterfaces, ObjectInspectorHandleViewer, ObjectInspectorHandler, Literals, ClientMLS, CoolSB; // TCapitolPoliticSheetHandler function TCapitolPoliticSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TCapitolSheetViewer.Create(Owner); fControl.fHandler := self; //fContainer.ChangeHeight(130); result := fControl; end; function TCapitolPoliticSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TCapitolPoliticSheetHandler.RenderProperties(Properties : TStringList); var hasPresid : boolean; years : string; count : integer; begin FiveViewUtils.SetViewProp(fControl, Properties); hasPresid := Properties.Values[tidHasRuler] = '1'; years := Properties.Values[tidYearsToElections]; if trim(years) <> '1' then years := GetFormattedLiteral('Literal15', [years]) else years := GetLiteral('Literal16'); if not hasPresid then begin fControl.xfer_ActualRuler.Caption := GetLiteral('Literal17'); fControl.xfer_RulerRating.Caption := GetLiteral('Literal18'); fControl.xfer_TycoonsRating.Caption := GetLiteral('Literal19'); fControl.xfer_RulerPeriods.Caption := GetLiteral('Literal20'); end else begin fControl.xfer_RulerRating.Caption := Properties.Values[tidRulerRating] + '%'; fControl.xfer_TycoonsRating.Caption := Properties.Values[tidTycoonsRating] + '%'; end; fControl.xfer_YearsToElections.Caption := years; fControl.btnVisitPolitics.Enabled := true; count := StrToInt(Properties.Values[tidCovCount]); fControl.Coverage.Items.Clear; Fork( threadedGetCoverage, priNormal, [count] ); end; procedure TCapitolPoliticSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; fControl.btnVisitPolitics.Enabled := false; Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); end; end; procedure TCapitolPoliticSheetHandler.Clear; begin inherited; fControl.btnVisitPolitics.Enabled := false; end; procedure TCapitolPoliticSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; Prop : TStringList; begin try Update := parms[1].vInteger; FiveViewUtils.GetViewPropNames(fControl, Names); Names.Add(tidHasRuler); Names.Add(tidCovCount); try Prop := fContainer.GetProperties(Names); finally Names.Free; end; if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; except end; end; procedure TCapitolPoliticSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if fLastUpdate = parms[1].vInteger then RenderProperties(Prop); finally Prop.Free; end; except end; end; procedure TCapitolPoliticSheetHandler.threadedGetCoverage(const parms : array of const); var count : integer absolute parms[0].vInteger; i : integer; iStr : string; Values : TStringList; covName : string; covValue : integer; Proxy : olevariant; lng : string; begin try Proxy := fContainer.GetCacheObjectProxy; lng := ClientMLS.ActiveLanguage; for i := 0 to pred(count) do begin Values := TStringList.Create; try iStr := IntToStr(i); GetContainer.GetPropertyArray(Proxy, ['covValue' + iStr, 'covName' + iStr], Values); covName := Values.Values['covName' + iStr]; try covValue := StrToInt(Values.Values['covValue' + iStr]); except covValue := 0; end; Threads.Join(syncGetCoverage, [covName, covValue]); Values.Clear; finally fControl.SetBounds(fControl.Left,fControl.Top,fControl.Width,fControl.Height); Values.Free; end; end; except end; end; procedure TCapitolPoliticSheetHandler.syncGetCoverage(const parms : array of const); var covName : string; covValue : string; begin covName := parms[0].vPchar; covValue := IntToStr(parms[1].vInteger); if covName <> '' then with fControl.Coverage.Items.Add do begin Caption := covName; SubItems.Add(covValue + '%'); end; end; // CapitolPoliticSheetHandlerCreator function CapitolPoliticSheetHandlerCreator : IPropertySheetHandler; begin result := TCapitolPoliticSheetHandler.Create; end; // TCapitolSheetViewer procedure TCapitolSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TCapitolSheetViewer.btnVisitPoliticsClick(Sender: TObject); var URL : string; Clv : IClientView; begin Clv := fHandler.GetContainer.GetClientView; URL := Clv.getWorldURL + 'Visual/Voyager/Politics/politics.asp' + '?WorldName=' + Clv.getWorldName + '&TycoonName=' + Clv.getUserName + '&Password=' + Clv.getUserPassword + '&Capitol=YES' + '&X=' + IntToStr(fHandler.GetContainer.GetXPos) + '&Y=' + IntToStr(fHandler.GetContainer.GetYPos) + '&DAAddr=' + Clv.getDAAddr + '&DAPort=' + IntToStr(Clv.getDALockPort); URL := URL + '&frame_Id=PoliticsView&frame_Class=HTMLView&frame_NoBorder=Yes&frame_Align=client::?frame_Id=' + tidHandlerName_ObjInspector + '&frame_Close=yes'; fHandler.GetContainer.HandleURL(URL, false); end; procedure TCapitolSheetViewer.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var sum : integer; i : integer; begin inherited; {if (Coverage <> nil) and (Coverage.Items <> nil) then begin sum := 0; for i := 0 to pred(Coverage.Columns.Count-1) do inc(sum, Coverage.Columns[i].Width); Coverage.Columns[Coverage.Columns.Count-1].Width := Coverage.Width-sum-2; end;} end; procedure TCapitolSheetViewer.SetParent(which: TWinControl); begin inherited; if InitSkinImage and (which<>nil) then begin InitializeCoolSB(Coverage.Handle); if hThemeLib <> 0 then SetWindowTheme(Coverage.Handle, ' ', ' '); CoolSBEnableBar(Coverage.Handle, FALSE, TRUE); CustomizeListViewHeader( Coverage ); end; end; initialization SheetHandlerRegistry.RegisterSheetHandler('capitolGeneral', CapitolPoliticSheetHandlerCreator); end.
unit Stat; interface type TStat = record Name : string; RuName: string; end; var CrStats : array of TStat; CrStatsCnt : Integer; procedure Load; implementation procedure Add(Name, RuName: string); begin CrStatsCnt := CrStatsCnt + 1; SetLength(CrStats, CrStatsCnt); CrStats[CrStatsCnt - 1].Name := Name; CrStats[CrStatsCnt - 1].RuName := RuName; end; procedure Load; begin CrStatsCnt := 0; Add('Strength', 'Сила'); Add('Agility', 'Ловкость'); Add('Endurance', 'Выносливость'); Add('Intelligence', 'Интеллект'); Add('MinDamage', 'Мин. урон'); Add('MaxDamage', 'Макс. урон'); Add('Defense', 'Защита'); Add('Block', 'Шанс блока'); Add('BStrength', 'Бонус к силе'); Add('Sword', 'Меч'); Add('Axe', 'Топор'); Add('Bow', 'Лук'); Add('Throwing', 'Метание'); Add('Unarmed', 'Без оружия'); Add('Magic', 'Магия'); end; end.
unit attributes; interface uses Interfaces.base, System.RTTI; type TResultArray = array of string; TFieldAnonymous = record NameTable: string; Sep: string; // <-- utilizada para a separação dos campos no SQL PKs: TResultArray; // chave primária TipoRtti: TRttiType; end; TFuncReflection = reference to function(AField: TFieldAnonymous): Integer; TNameTable = class(TCustomAttribute) private FNameTable : string; public constructor Create(aNameTable: string); property NameTable: string read FNameTable write FNameTable; end; TField = class(TCustomAttribute) public function IsPk: Boolean; virtual; end; TFieldPK = class(TField) public function IsPk: Boolean; override; end; //Reflection para os comandos Sql function ReflectionSQL(ATabela: TTable; AnoniComando: TFuncReflection): Integer; function GetPks(AObject : TObject) : TResultArray; function GetNameTable(AObject : TObject) : string; implementation function ReflectionSQL(ATabela: TTable; AnoniComando: TFuncReflection): Integer; var AField: TFieldAnonymous; Context : TRttiContext; begin AField.NameTable := GetNameTable(ATabela); AField.PKs := GetPks(ATabela); Context := TRttiContext.Create; try AField.TipoRtti := Context.GetType( ATabela.ClassType ); //executamos os comandos Sql através do método anônimo AField.Sep := ''; Result := AnoniComando(AField); finally Context.free; end; end; function GetPks(AObject : TObject) : TResultArray; var Context : TRttiContext; TipoRtti : TRttiType; PropRtti : TRttiProperty; AtribRtti : TCustomAttribute; i: Integer; begin Context := TRttiContext.Create; TipoRtti := Context.GetType( AObject.ClassType ); i:=0; for PropRtti in TipoRtti.GetProperties do for AtribRtti in PropRtti.GetAttributes do if AtribRtti Is TField then if (AtribRtti as TField).isPk then begin SetLength(Result, i+1); Result[i] := PropRtti.Name; inc(i); end; Context.Free; end; function GetNameTable(AObject : TObject) : string; var Contexto : TRttiContext; TipoRtti : TRttiType; AtribRtti : TCustomAttribute; begin Contexto := TRttiContext.Create; TipoRtti := Contexto.GetType( AObject.ClassType ); for AtribRtti in TipoRtti.GetAttributes do if AtribRtti Is TNameTable then begin Result := (AtribRtti as TNameTable).NameTable; Break; end; Contexto.Free; end; { TTable } constructor TNameTable.Create(aNameTable: string); begin FNameTable := aNameTable; end; { TFields } function TField.IsPk: Boolean; begin Result := False; end; { TFieldsPK } function TFieldPK.IsPk: Boolean; begin Result := True; end; end.
unit ImportExportUnit; // Библиотека "GblAdapterLib" // Модуль: ImportExportUnit // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include nsDefine.inc} interface uses IOUnit, BaseTypesUnit ; type AuthorizationNeed = class {* Для проведения экспорта предвароительно необходимо авторизоваться } end;//AuthorizationNeed UnknownExportError = class {* Произошла неизвестная ошибка во время экспорта настроек } end;//UnknownExportError DataLoadFailed = class {* Возникает при ошибке загрузки данных из XML файла } end;//DataLoadFailed XercesAdapterNotFound = class end;//XercesAdapterNotFound IUserProfile5x = interface {* Структура провиля пользователя формата 5х } ['{D90D29AB-4C5F-4F71-8367-1A6B1D51D7FB}'] function GetName: IString; stdcall; class function Make(aUserHomeData); reintroduce; stdcall; property name: IString read GetName; end;//IUserProfile5x UserProfile5xList = array of UserProfile5x; IImport5x = interface {* Интерфейс для работы с импортом данных из 5х } ['{2B69C115-7D7D-47D7-8087-C49498949A9B}'] function GetUserProfile: IUserProfile5xList; stdcall; {* Возхвращает список необработанных пользовательских профилей из 5х } procedure ExportData(const aProfile: IUserProfile5x); stdcall; // can raise AuthorizationNeed, UnknownExportError, XercesAdapterNotFound {* Экспортирует в Немезис указанный провиль 5х и все связанные с ним данные (настройки, папки/закладки). В случае успеха помечает его как обработанный. Выполнение операции требует предварительной авторизации на сервере. } procedure LoadDataFromXML(aFileName: PChar); stdcall; // can raise InvalidXMLType, DataLoadFailed, XercesAdapterNotFound {* Загружает в Немезис указанный XML-файл, содержащий настройки, папки/закладки. Выполнение операции требует предварительной авторизации на сервере. Если XML-файл не содержит правильных данных, то генерится - EInvalidXMLType, если загрузка не удалась, то генерится - EDataLoadFailed } class function Make; reintroduce; stdcall; end;//IImport5x implementation end.
unit TypeUtils; interface { fazer método onde é passado um arquivo xsd para validar o conteúdo da string supondo que seja um xml } uses SysUtils, Classes, JclPCRE; const NOME_ARQUIVO = 'c:\arquivo.txt'; QUEBRA_DE_LINHA = #13#10; FILTRO_PADRAO_DE_ARQUIVO = '*.*'; // IString, IXString constants ACCENTED_CHARS: array [0 .. 56] of Char = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåæçèéêëìíîïñòóôõöùúûüýÿ'; UNACCENTED_CHARS: array [0 .. 56] of Char = 'AAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaaceeeeiiiinooooouuuuyy'; REGEX_FIRST_WORD_LETTER: UTF8String = '^\p{L}|(\p{P}|\p{Z})\p{L}'; REGEX_ACCENTED_CHARS: UTF8String = '[ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåæçèéêëìíîïñòóôõöùúûüýÿ]'; REGEX_PUNCTS_OR_SPACES: UTF8String = '[[:punct:]]|\s'; // IURI constants REGEX_SCHEME: UTF8String = '[a-zA-Z][+-.a-zA-Z]*'; REGEX_LAST_PATH: UTF8String = '([^/])([a-zA-Z][+-.a-zA-Z:?&\d#=]*)$'; REGEX_DOCUMENT: UTF8String = '^([][.-\w\d]*)([^?])'; // To avoid possible erros on large string regex; {$MAXSTACKSIZE $00200000} type TMatchOffSet = record Start: Integer; Stop: Integer; end; TProcedureString = procedure(Valor: string) of object; IMatchData = interface; IString = interface ['{09850B99-B6B6-4A59-9054-A2866B5C83F4}'] function AdicionarAntesDaString(AValue: string; Repetir: Integer = 1): string; function AdicionarDepoisDaString(AValue: string; Repetir: Integer = 1): string; function GetValue: string; function GetAt(De, Ate: Integer): string; procedure SetAt(De, Ate: Integer; const Value: string); function GetAtStr(De, Ate: string): string; procedure SetAtStr(De, Ate: string; const Value: string); function Vezes(AValue: Integer): string; function Menos(AValue: string): string; overload; function Menos(AValues: array of string): string; overload; function Mais(AValue: string): string; overload; function Mais(const AValue: IString): string; overload; function Centralizado(ATamanho: Integer = 38): string; function AlinhadoADireita(ATamanho: Integer = 38): string; function AlinhadoAEsquerda(ATamanho: Integer = 38): string; function ComZerosAEsquerda(ATamanho: Integer): string; function Contem(AValue: string): Boolean; overload; function Encripta(AChave: string): string; function EncriptSimples: string; function Decripta(AChave: string): string; function Format(AValues: array of const ): string; function EstaContidoEm(AValue: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3, AValue4: string): Boolean; overload; function EstaContidoEm(AValue: array of string): Boolean; overload; function Trim: string; function TrimLeft: string; function TrimRight: string; function GetChave(ANome: string): string; procedure SetChave(ANome: string; const Value: string); function Replace(AOldPattern, ANewPattern: string): string; overload; function Replace(ARegexPattern: UTF8String; ANewPattern: string): string; overload; function Replace(AOldPattern, ANewPattern: string; Flags: TReplaceFlags): string; overload; function Replace(AOldPatterns, ANewPatterns: array of string): string; overload; function Replace(AOldPatterns, ANewPatterns: array of string; Flags: TReplaceFlags): string; overload; function Replace(AOldPatterns: array of string; ANewPattern: string): string; overload; function Replace(AOldPatterns: array of string; ANewPattern: string; Flags: TReplaceFlags): string; overload; function ReplaceAll(AOldPattern, ANewPattern: string): string; overload; function Reverter: string; function Ate(APosicao: Integer): string; overload; function Ate(APosicao: string): string; overload; function AteAntesDe(APosicao: string): string; procedure SaveToFile(AArquivo: string = NOME_ARQUIVO); function ShowConfirmation: Boolean; procedure ShowError; procedure ShowWarning; procedure Show; function Modulo10: string; function Modulo11(Base: Integer = 9; Resto: Boolean = false): string; function Length: Integer; function Copy(AIndex, ACount: Integer): string; function ValidarComXSD(AArquivo: string): string; function LowerCase: string; function UpperCase: string; function IndexOf(ASubstring: string): Integer; overload; function IndexOf(ASubstring: string; AOffSet: Integer): Integer; overload; function ComAspas: string; function Aspas: string; function UTF8Decode: string; function UTF8Encode: string; function Humanize: string; function Desumanize: string; function Camelize: string; function Underscore: string; function AsInteger: Integer; function IndiceNoArray(AArray: array of string): Integer; function ListarArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): string; function ListarArquivosComPrefixoParaCopy(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): string; function ListarPastas(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): string; function ListarPastasEArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA; Recursividade: Boolean = false): string; function AsStringList: TStringList; // o programador precisa controlar o tempo de vida do retorno function LoadFromFile: string; function Equals(AValor: string): Boolean; overload; function Equals(AValor: IString): Boolean; overload; function IgualA(AValor: string): Boolean; overload; function IgualA(AValor: IString): Boolean; overload; property Chave[ANome: string]: string read GetChave write SetChave; property Get[De, Ate: Integer]: string read GetAt write SetAt; default; property Str[De, Ate: string]: string read GetAtStr write SetAtStr; function Contem(AValues: array of string): Boolean; overload; function GetVazia: Boolean; procedure SetValue(const Value: string); property Value: string read GetValue write SetValue; property Vazia: Boolean read GetVazia; function After(AIndex: Integer): string; procedure Clear; function Match(ARegex: UTF8String): Boolean; function MatchDataFor(ARegex: UTF8String): IMatchData; function AsClassName(AUnsingPrefix: string = 'T'): string; function IsEmpty(ATrimBefore: boolean = False): Boolean; function WithoutAccents: string; end; TString = class(TInterfacedObject, IString) private FValue: string; FRegex: TJclRegEx; function Regex: TJclRegEx; protected function GetAtStr(De, Ate: string): string; procedure SetAtStr(De, Ate: string; const AValue: string); function GetAt(De, Ate: Integer): string; procedure SetAt(De, Ate: Integer; const AValue: string); function GetVazia: Boolean; function GetValue: string; procedure SetValue(const Value: string); function GetChave(ANome: string): string; procedure SetChave(ANome: string; const Value: string); public function IndiceNoArray(AArray: array of string): Integer; function Vezes(AValue: Integer): string; function Menos(AValue: string): string; overload; function Menos(AValues: array of string): string; overload; function Mais(AValue: string): string; overload; function Mais(const AValue: IString): string; overload; function Centralizado(ATamanho: Integer = 38): string; function AlinhadoADireita(ATamanho: Integer = 38): string; function AlinhadoAEsquerda(ATamanho: Integer = 38): string; function ComZerosAEsquerda(ATamanho: Integer): string; function Contem(AValue: string): Boolean; overload; function EstaContidoEm(AValue: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3, AValue4: string): Boolean; overload; function EstaContidoEm(AValues: array of string): Boolean; overload; function EncriptSimples: string; function Encripta(AChave: string): string; function Decripta(AChave: string): string; function Format(AValues: array of const ): string; function Modulo10: string; function Modulo11(Base: Integer = 9; Resto: Boolean = false): string; function Trim: string; function TrimLeft: string; function TrimRight: string; function Replace(AOldPattern, ANewPattern: string): string; overload; function Replace(ARegexPattern: UTF8String; ANewPattern: string): string; overload; function Replace(AOldPattern, ANewPattern: string; Flags: TReplaceFlags): string; overload; function Replace(AOldPatterns, ANewPatterns: array of string): string; overload; function Replace(AOldPatterns, ANewPatterns: array of string; Flags: TReplaceFlags): string; overload; function Replace(AOldPatterns: array of string; ANewPattern: string): string; overload; function Replace(AOldPatterns: array of string; ANewPattern: string; Flags: TReplaceFlags): string; overload; function ReplaceAll(AOldPattern, ANewPattern: string): string; overload; function AdicionarAntesDaString(AValue: string; Repetir: Integer = 1): string; function AdicionarDepoisDaString(AValue: string; Repetir: Integer = 1): string; function Reverter: string; function Copy(AIndex, ACount: Integer): string; procedure SaveToFile(AArquivo: string = NOME_ARQUIVO); function ValidarComXSD(AArquivo: string): string; procedure Show; procedure ShowWarning; procedure ShowError; procedure Clear; function ShowConfirmation: Boolean; function Length: Integer; function LowerCase: string; function UpperCase: string; function IndexOf(ASubstring: string): Integer; overload; function IndexOf(ASubstring: string; AOffSet: Integer): Integer; overload; function ComAspas: string; function Aspas: string; function UTF8Decode: string; function UTF8Encode: string; function Humanize: string; function Camelize: string; function Desumanize: string; function Underscore: string; function AsInteger: Integer; function LoadFromFile: string; function ListarArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): string; function ListarArquivosComPrefixoParaCopy(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): string; function ListarPastas(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): string; function ListarPastasEArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA; IncluirSubPastas: Boolean = false): string; function Ate(APosicao: Integer): string; overload; function Ate(APosicao: string): string; overload; function AteAntesDe(APosicao: string): string; function AsStringList: TStringList; // o programador precisa controlar o tempo de vida do retorno function Equals(AValor: string): Boolean; overload; function Equals(AValor: IString): Boolean; overload; function IgualA(AValor: string): Boolean; overload; function IgualA(AValor: IString): Boolean; overload; property Get[De, Ate: Integer]: string read GetAt write SetAt; default; property Str[De, Ate: string]: string read GetAtStr write SetAtStr; property Value: string read GetValue write SetValue; property Vazia: Boolean read GetVazia; property Chave[ANome: string]: string read GetChave write SetChave; constructor Create(AValue: string); destructor Destroy; override; function After(AIndex: Integer): string; function Contem(AValues: array of string): Boolean; overload; function Match(ARegex: UTF8String): Boolean; function MatchDataFor(ARegex: UTF8String): IMatchData; function AsClassName(AUsingPrefix: string = 'T'): string; function IsEmpty(ATrimBefore: boolean = False): Boolean; function WithoutAccents: string; end; IXString = interface ['{296B0DD1-9E84-47EE-9211-F05E4604EEA9}'] function GetAt(De, Ate: Integer): IXString; procedure SetAt(De, Ate: Integer; const AValue: IXString); function AdicionarAntesDaString(AValue: string; Repetir: Integer = 1): IXString; function AdicionarDepoisDaString(AValue: string; Repetir: Integer = 1): IXString; function GetValue: string; function Vezes(AValue: Integer): IXString; function Menos(AValue: string): IXString; overload; function Menos(AValues: array of string): IXString; overload; function Mais(AValue: string): IXString; overload; function Mais(const AValue: IXString): IXString; overload; function Centralizado(ATamanho: Integer = 38): IXString; function AlinhadoADireita(ATamanho: Integer = 38): IXString; function AlinhadoAEsquerda(ATamanho: Integer = 38): IXString; function AsInteger: Integer; function ComZerosAEsquerda(ATamanho: Integer): IXString; function Contem(AValue: string): Boolean; overload; function Contem(AValues: array of string): Boolean; overload; function Encripta(AChave: string): IXString; function Decripta(AChave: string): IXString; function Format(AValues: array of const ): IXString; function EstaContidoEm(AValue: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3, AValue4: string): Boolean; overload; function EstaContidoEm(AValue: array of string): Boolean; overload; function Trim: IXString; function TrimLeft: IXString; function TrimRight: IXString; function Show: IXString; function ShowWarning: IXString; function ShowError: IXString; function ShowConfirmation: Boolean; function Reverter: IXString; function AsStringList: TStringList; // o programador precisa controlar o tempo de vida do retorno function Replace(AOldPattern, ANewPattern: string): IXString; overload; function Replace(ARegexPattern: UTF8String; ANewPattern: string): IXString; overload; function Replace(AOldPattern, ANewPattern: string; Flags: TReplaceFlags): IXString; overload; function Replace(AOldPatterns, ANewPatterns: array of string): IXString; overload; function Replace(AOldPatterns, ANewPatterns: array of string; Flags: TReplaceFlags): IXString; overload; function Replace(AOldPatterns: array of string; ANewPattern: string): IXString; overload; function Replace(AOldPatterns: array of string; ANewPattern: string; Flags: TReplaceFlags): IXString; overload; function ReplaceAll(AOldPattern, ANewPattern: string): IXString; function SaveToFile(AArquivo: string = NOME_ARQUIVO): IXString; function ValidarComXSD(AArquivo: string): IXString; function Copy(AIndex, ACount: Integer): IXString; function Length: Integer; function LowerCase: IXString; function UpperCase: IXString; function ComAspas: IXString; function UTF8Decode: IXString; function UTF8Encode: IXString; function IndexOf(ASubstring: string): Integer; overload; function IndexOf(ASubstring: string; AOffSet: Integer): Integer; overload; function Ate(APosicao: Integer): IXString; overload; function Ate(APosicao: string): IXString; overload; function AteAntesDe(APosicao: string): IXString; function Humanize: IXString; function Desumanize: IXString; function Camelize: IXString; function Underscore: IXString; function LoadFromFile: IXString; function ListarPastas(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True): IXString; function ListarArquivos(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = #13#10): IXString; function ListarArquivosComPrefixoParaCopy(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True): IXString; function ListarPastasEArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA; Recursividade: Boolean = false): IXString; procedure SetValue(const Value: string); function Equals(AValor: string): Boolean; overload; function Equals(AValor: IString): Boolean; overload; function Equals(AValor: IXString): Boolean; overload; function IgualA(AValor: string): Boolean; overload; function IgualA(AValor: IString): Boolean; overload; function IgualA(AValor: IXString): Boolean; overload; function IsEmpty(ATrimBefore: boolean = False): Boolean; function Match(ARegex: UTF8String): Boolean; procedure Clear; property Get[De, Ate: Integer]: IXString read GetAt write SetAt; default; property Value: string read GetValue write SetValue; function After(AIndex: Integer): IXString; function MatchDataFor(ARegex: UTF8String): IMatchData; function AsClassName(AUsingPrefix: string = 'T'): IXString; function WithoutAccents: IXString; end; TXString = class(TInterfacedObject, IXString) private FRegex: TJclRegEx; FValue: IString; function Regex: TJclRegEx; protected function GetAt(De, Ate: Integer): IXString; procedure SetAt(De, Ate: Integer; const AValue: IXString); function GetValue: string; procedure SetValue(const AValue: string); public constructor Create(AValue: string); destructor Destroy; override; function AdicionarAntesDaString(AValue: string; Repetir: Integer = 1): IXString; function AdicionarDepoisDaString(AValue: string; Repetir: Integer = 1): IXString; function Vezes(AValue: Integer): IXString; function Menos(AValue: string): IXString; overload; function Menos(AValues: array of string): IXString; overload; function Mais(AValue: string): IXString; overload; function Mais(const AValue: IXString): IXString; overload; function Centralizado(ATamanho: Integer = 38): IXString; function AlinhadoADireita(ATamanho: Integer = 38): IXString; function AlinhadoAEsquerda(ATamanho: Integer = 38): IXString; function ComZerosAEsquerda(ATamanho: Integer): IXString; function Contem(AValue: string): Boolean; overload; function Contem(AValues: array of string): Boolean; overload; function Encripta(AChave: string): IXString; function Decripta(AChave: string): IXString; function Format(AValues: array of const ): IXString; function EstaContidoEm(AValue: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3: string): Boolean; overload; function EstaContidoEm(AValue1, AValue2, AValue3, AValue4: string): Boolean; overload; function EstaContidoEm(AValues: array of string): Boolean; overload; function Trim: IXString; function TrimLeft: IXString; function TrimRight: IXString; function ShowWarning: IXString; function ShowError: IXString; function ShowConfirmation: Boolean; function Show: IXString; function LoadFromFile: IXString; function AsStringList: TStringList; // o programador precisa controlar o tempo de vida do retorno function Replace(AOldPattern, ANewPattern: string): IXString; overload; function Replace(ARegexPattern: UTF8String; ANewPattern: string): IXString; overload; function Replace(AOldPattern, ANewPattern: string; Flags: TReplaceFlags): IXString; overload; function Replace(AOldPatterns, ANewPatterns: array of string): IXString; overload; function Replace(AOldPatterns, ANewPatterns: array of string; Flags: TReplaceFlags): IXString; overload; function Replace(AOldPatterns: array of string; ANewPattern: string): IXString; overload; function Replace(AOldPatterns: array of string; ANewPattern: string; Flags: TReplaceFlags): IXString; overload; function ReplaceAll(AOldPattern, ANewPattern: string): IXString; function Reverter: IXString; function SaveToFile(AArquivo: string = NOME_ARQUIVO): IXString; function ValidarComXSD(AArquivo: string): IXString; function Copy(AIndex, ACount: Integer): IXString; function UTF8Decode: IXString; function UTF8Encode: IXString; function Length: Integer; function LowerCase: IXString; function UpperCase: IXString; function IndexOf(ASubstring: string): Integer; overload; function IndexOf(ASubstring: string; AOffSet: Integer): Integer; overload; function ComAspas: IXString; function Humanize: IXString; function Desumanize: IXString; function Camelize: IXString; function Underscore: IXString; function Ate(APosicao: Integer): IXString; overload; function Ate(APosicao: string): IXString; overload; function AteAntesDe(APosicao: string): IXString; function ListarArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA): IXString; function ListarArquivosComPrefixoParaCopy(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True): IXString; function ListarPastas(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True): IXString; function ListarPastasEArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA; Recursividade: Boolean = false): IXString; function Equals(AValor: string): Boolean; overload; function Equals(AValor: IString): Boolean; overload; function Equals(AValor: IXString): Boolean; overload; function IgualA(AValor: string): Boolean; overload; function IgualA(AValor: IString): Boolean; overload; function IgualA(AValor: IXString): Boolean; overload; procedure Clear; function Match(ARegex: UTF8String): Boolean; function MatchDataFor(ARegex: UTF8String): IMatchData; property Value: string read GetValue write SetValue; property Get[De, Ate: Integer]: IXString read GetAt write SetAt; default; function After(AIndex: Integer): IXString; function AsInteger: Integer; function IsEmpty(ATrimBefore: boolean = False): Boolean; function AsClassName(AUsingPrefix: string = 'T'): IXString; function WithoutAccents: IXString; end; IInteger = interface; IMatchData = interface(IInterface) ['{65DA766B-1565-489F-9389-9D5968CDE346}'] function GetCaptures(Index: Integer): IXString; function GetMatchedData: IXString; function GetPostMatch: IXString; function GetPreMatch: IXString; function GetSize: IInteger; procedure SetCaptures(Index: Integer; const Value: IXString); procedure SetMatchedData(const Value: IXString); procedure SetPostMatch(const Value: IXString); procedure SetPreMatch(const Value: IXString); procedure SetSize(const Value: IInteger); function GetOffSet(Index: Integer): TMatchOffSet; procedure SetOffSet(Index: Integer; const Value: TMatchOffSet); function GetStart(Index: Integer): IInteger; procedure SetStart(Index: Integer; const Value: IInteger); function GetStop(Index: Integer): IInteger; procedure SetStop(Index: Integer; const Value: IInteger); property MatchedData: IXString read GetMatchedData write SetMatchedData; property PostMatch: IXString read GetPostMatch write SetPostMatch; property PreMatch: IXString read GetPreMatch write SetPreMatch; property Size: IInteger read GetSize write SetSize; property Captures[Index: Integer]: IXString read GetCaptures write SetCaptures; default; property OffSet[Index: Integer]: TMatchOffSet read GetOffSet write SetOffSet; property Start[Index: Integer]: IInteger read GetStart write SetStart; property Stop[Index: Integer]: IInteger read GetStop write SetStop; end; TIntegerProc = reference to procedure; IInteger = interface(IInterface) ['{5F187942-611A-4DE2-9DC4-169BCC98E2C2}'] function GetValue: Integer; procedure SetValue(const Value: Integer); function AsString: string; function Format(AFormat: string = '000000'): string; procedure Times(AMetodo: TIntegerProc); function Next: Integer; property Value: Integer read GetValue write SetValue; end; IURI = interface(IInterface) ['{6F4B598A-01AE-4028-96D1-C1DE9F23C3C8}'] function GetURL: IXString; procedure SetURL(const Value: IXString); function Document: IXString; function EncodedURI: IXString; property URL: IXString read GetURL write SetURL; end; TInteger = class(TInterfacedObject, IInteger) private FValue: Integer; protected function GetValue: Integer; procedure SetValue(const Value: Integer); public constructor Create(AValue: Integer); procedure Times(AMetodo: TIntegerProc); function AsString: string; function Format(AFormat: string = '000000'): string; function Next: Integer; property Value: Integer read GetValue write SetValue; end; TMatchData = class(TInterfacedObject, IMatchData) private FCaptures: IInterfaceList; FOffSets: array of TMatchOffSet; FStarts: array of IInteger; FStops: array of IInteger; FMatchedData: IXString; FPostMatch: IXString; FPreMatch: IXString; FSize: IInteger; function GetCaptures(Index: Integer): IXString; function GetMatchedData: IXString; function GetOffSet(Index: Integer): TMatchOffSet; function GetPostMatch: IXString; function GetPreMatch: IXString; function GetSize: IInteger; function GetStart(Index: Integer): IInteger; function GetStop(Index: Integer): IInteger; procedure SetCaptures(Index: Integer; const Value: IXString); procedure SetMatchedData(const Value: IXString); procedure SetOffSet(Index: Integer; const Value: TMatchOffSet); procedure SetPostMatch(const Value: IXString); procedure SetPreMatch(const Value: IXString); procedure SetSize(const Value: IInteger); procedure SetStart(Index: Integer; const Value: IInteger); procedure SetStop(Index: Integer; const Value: IInteger); public constructor Create(const ASize: Integer); property Captures[Index: Integer]: IXString read GetCaptures write SetCaptures; default; property MatchedData: IXString read GetMatchedData write SetMatchedData; property OffSet[Index: Integer]: TMatchOffSet read GetOffSet write SetOffSet; property PostMatch: IXString read GetPostMatch write SetPostMatch; property PreMatch: IXString read GetPreMatch write SetPreMatch; property Size: IInteger read GetSize write SetSize; property Start[Index: Integer]: IInteger read GetStart write SetStart; property Stop[Index: Integer]: IInteger read GetStop write SetStop; end; TURI = class(TInterfacedObject, IURI) private FURL: IXString; FDocument: IXString; FEncodedURI: IXString; function GetURL: IXString; procedure InitInstance; procedure SetURL(const Value: IXString); public constructor Create(const AURL: string); overload; constructor Create(const AURL: IXString); overload; function Document: IXString; function EncodedURI: IXString; property URL: IXString read GetURL write SetURL; end; // IInteger function I(AIntegerValue: Integer): IInteger; // IString, IXString function S(Value: string): IString; function SX(Value: string): IXString; function SDoArquivo(AArquivo: string): IString; function SXDoArquivo(AArquivo: string): IXString; // IURI function URI(const AURI: string): IURI; function Concatenar(AStrings: array of string; AFormat: string = '"%s"'; ASeparador: string = ', '): string; function Aspas(AStr: string): string; procedure ArrayExecute(AValores: array of string; AMetodo: TProcedureString); function ReplaceMany(S: string; OldPatterns: array of string; NewPatterns: array of string; Flags: TReplaceFlags): string; overload; function ReplaceMany(S: string; OldPatterns: array of string; NewPattern: string; Flags: TReplaceFlags): string; overload; function CreateStringGUID: string; function NovoGUIDParaRegistro: string; function AddCharNaString(Texto: string; Tamanho: Integer; Caracter: Char = ' '; Esquerda: Boolean = True): string; function AlinhaTX(Texto: string; Alinhar: Char; Espaco: Integer): string; function AlinhaEsquerda(Texto: string; Tamanho: Integer): string; function AlinhaDireita(Texto: string; Tamanho: Integer): string; function EncriptSimples(Str: string): string; // criptografia de dados function GetFileList(FDirectory, Filter: TFileName; ShowFolder: Boolean; AUsaPrefixoCopy: Boolean = false): TStringList; function IndexOf(AValor: string; AArray: array of string): Integer; implementation uses Dialogs, Windows, Registry, StrUtils, forms, Math, HTTPApp; function IndexOf(AValor: string; AArray: array of string): Integer; var I: Integer; begin Result := -1; for I := 0 to High(AArray) do begin if AValor = AArray[I] then Result := I; end; end; function TemAtributo(Attr, Val: Integer): Boolean; begin Result := Attr and Val = Val; end; function ListarPastas(Diretorio: string; CaminhoCompleto: Boolean = True; AFiltro: string = '*.*'; ASeparador: string = #13#10): TStringList; var F: TSearchRec; Ret: Integer; begin Result := TStringList.Create; Ret := FindFirst(Diretorio + '\' + AFiltro, faAnyFile, F); try while Ret = 0 do begin if TemAtributo(F.Attr, faDirectory) then begin if (F.Name <> '.') and (F.Name <> '..') then begin if CaminhoCompleto then Result.Add(Diretorio + '\' + F.Name) else Result.Add(F.Name); end; end; Ret := FindNext(F); end; finally SysUtils.FindClose(F); end; end; function ListarPastasEArquivos(Diretorio: string; Sub: Boolean = True; AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True): TStrings; var F: TSearchRec; Ret: Integer; TempNome: string; LSubPasta: TStrings; begin Result := TStringList.Create; Ret := FindFirst(Diretorio + '\' + AFiltro, faAnyFile, F); try while Ret = 0 do begin if TemAtributo(F.Attr, faDirectory) then begin if (F.Name <> '.') and (F.Name <> '..') then begin if Sub then begin if AMostrarCaminhoCompleto then TempNome := Diretorio + '\' + F.Name else TempNome := F.Name; Result.Add(TempNome); LSubPasta := ListarPastasEArquivos(Diretorio + '\' + F.Name, True, AFiltro, AMostrarCaminhoCompleto); Result.Add(LSubPasta.Text); LSubPasta.Free; end; end; end else begin if AMostrarCaminhoCompleto then Result.Add(Diretorio + '\' + F.Name) else Result.Add(F.Name); end; Ret := FindNext(F); end; finally SysUtils.FindClose(F); end; end; function EncriptSimples(Str: string): string; // criptografia de dados var I, j, k, tam: Integer; straux, Ret: string; begin tam := Length(Str); // pega tamanho da string Ret := ''; // atribui vlr nulo ao retorno I := 1; // incializa variavel for k := 1 to tam do begin straux := Copy(Str, I, 6); // pega de 6 em 6 chr's for j := 1 to Length(straux) do begin if j = 1 then Ret := Ret + Chr(ord(straux[j]) + 76 + k + j) // primeiro caracter else if j = 2 then Ret := Ret + Chr(ord(straux[j]) + 69 + k + j) // segundo caracter else if j = 3 then Ret := Ret + Chr(ord(straux[j]) + 79 + k + j) // terceiro caracter else if j = 4 then Ret := Ret + Chr(ord(straux[j]) + 78 + k + j) // quarto caracter else if j = 5 then Ret := Ret + Chr(ord(straux[j]) + 73 + k + j) // quinto caracter else if j = 6 then Ret := Ret + Chr(ord(straux[j]) + 82 + k + j) // sexto caracter end; I := I + 6; // pula de 6 em 6 if I > tam then begin Result := Copy(Ret, 1, tam); // devolve resultado exit; // e sai da funcao end; end; Result := Copy(Ret, 1, tam); // devolve resultado end; function Aspas(AStr: string): string; begin Result := QuotedStr(AStr); end; function GetFileList(FDirectory, Filter: TFileName; ShowFolder: Boolean; AUsaPrefixoCopy: Boolean = false): TStringList; var ARec: TSearchRec; Res: Integer; begin {$WARNINGS off} if FDirectory[Length(FDirectory)] <> '\' then FDirectory := FDirectory + '\'; Result := TStringList.Create; try Res := FindFirst(FDirectory + Filter, faAnyFile or faArchive, ARec); while Res = 0 do begin if ((ARec.Attr and faArchive) = faAnyFile) or ((ARec.Attr and faArchive) = faArchive) then begin if ShowFolder then if AUsaPrefixoCopy then Result.Add('\COPY ' + StringReplace(LowerCase(ARec.Name), '.copy', '', [rfReplaceAll]) + ' FROM ''' + FDirectory + ARec.Name + '''') else Result.Add(FDirectory + ARec.Name) else if AUsaPrefixoCopy then Result.Add('\COPY ' + StringReplace(LowerCase(ARec.Name), '.copy', '', [rfReplaceAll]) + ' FROM ''' + ARec.Name + '''') else Result.Add(ARec.Name); end; Res := FindNext(ARec); end; SysUtils.FindClose(ARec); except Result.Free; end; {$WARNINGS on} end; function Concatenar(AStrings: array of string; AFormat: string = '"%s"'; ASeparador: string = ', '): string; var I: Integer; begin Result := ''; for I := 0 to High(AStrings) do begin Result := Result + Format(AFormat, [AStrings[I]]); if I <> High(AStrings) then Result := Result + ASeparador; end; end; procedure ArrayExecute(AValores: array of string; AMetodo: TProcedureString); var I: Integer; begin for I := 0 to High(AValores) do AMetodo(AValores[I]); end; function S(Value: string): IString; begin Result := TString.Create(Value); end; function SX(Value: string): IXString; begin Result := TXString.Create(Value); end; function CarregarStringDoArquivo(AArquivo: string): string; var LArquivo: TStringList; begin Result := ''; LArquivo := TStringList.Create; try LArquivo.LoadFromFile(AArquivo); Result := LArquivo.Text; finally LArquivo.Free; end; end; function SDoArquivo(AArquivo: string): IString; begin Result := S(CarregarStringDoArquivo(AArquivo)); end; function SXDoArquivo(AArquivo: string): IXString; begin Result := SX(CarregarStringDoArquivo(AArquivo)); end; function AlinhaDireita(Texto: string; Tamanho: Integer): string; begin Result := AddCharNaString(Texto, Tamanho); end; function AlinhaEsquerda(Texto: string; Tamanho: Integer): string; begin Result := AddCharNaString(Texto, Tamanho, ' ', false); end; function ReplaceMany(S: string; OldPatterns: array of string; NewPatterns: array of string; Flags: TReplaceFlags): string; var I: Integer; begin Result := S; for I := 0 to High(NewPatterns) do Result := StringReplace(Result, OldPatterns[I], NewPatterns[I], Flags); end; function ReplaceMany(S: string; OldPatterns: array of string; NewPattern: string; Flags: TReplaceFlags): string; var I: Integer; begin Result := S; for I := 0 to High(OldPatterns) do Result := StringReplace(Result, OldPatterns[I], NewPattern, Flags); end; function CreateStringGUID: string; var LGUID: TGUID; begin CreateGUID(LGUID); Result := GUIDToString(LGUID); end; function NovoGUIDParaRegistro: string; begin Result := ReplaceMany(CreateStringGUID, ['-', '{', '}'], ['', '', ''], [rfReplaceAll]); end; function AddCharNaString(Texto: string; Tamanho: Integer; Caracter: Char = ' '; Esquerda: Boolean = True): string; begin Result := Texto; if Length(Result) > Tamanho then begin Delete(Result, Tamanho + 1, Length(Result) - Tamanho); exit; end; if Esquerda then while Length(Result) < Tamanho do Result := Caracter + Result else begin while Length(Result) < Tamanho do Result := Result + Caracter; end; end; function AlinhaTX(Texto: string; Alinhar: Char; Espaco: Integer): string; // alinha textos var Retorno: string; begin Retorno := ''; if Length(Trim(Texto)) > Espaco then Retorno := Copy(Trim(Texto), 1, Espaco) else begin case Alinhar of 'D', 'd': Retorno := StringOfChar(' ', Espaco - Length(Trim(Texto))) + Trim(Texto); 'E', 'e': Retorno := Trim(Texto) + StringOfChar(' ', Espaco - Length(Trim(Texto))); 'C', 'c': Retorno := StringOfChar(' ', Trunc(Int((Espaco - Length(Trim(Texto))) / 2))) + Trim(Texto) + StringOfChar(' ', Trunc(Int((Espaco - Length(Trim(Texto))) / 2))); end; end; AlinhaTX := Retorno end; { TString } function TString.AdicionarAntesDaString(AValue: string; Repetir: Integer = 1): string; begin Result := S(AValue).Vezes(Repetir) + Value; end; function TString.AdicionarDepoisDaString(AValue: string; Repetir: Integer = 1): string; begin Result := Value + S(AValue).Vezes(Repetir); end; function TString.AlinhadoADireita(ATamanho: Integer = 38): string; begin Result := AlinhaTX(Value, 'D', ATamanho); end; function TString.AlinhadoAEsquerda(ATamanho: Integer = 38): string; begin Result := AlinhaTX(Value, 'E', ATamanho); end; function TString.Centralizado(ATamanho: Integer = 38): string; begin Result := AlinhaTX(Value, 'C', ATamanho); end; procedure TString.Clear; begin Value := ''; end; function TString.Contem(AValue: string): Boolean; begin Result := Pos(AValue, Value) > 0; end; constructor TString.Create(AValue: string); begin FValue := AValue; end; destructor TString.Destroy; begin if Assigned(FRegex) then FreeAndNil(FRegex); inherited; end; function TString.After(AIndex: Integer): string; begin Result := Copy(AIndex, Length); end; function TString.AsClassName(AUsingPrefix: string = 'T'): string; begin Result := SX(Value).Humanize.Camelize.WithoutAccents.Replace(REGEX_PUNCTS_OR_SPACES, '').AdicionarAntesDaString(AUsingPrefix).Value; end; function TString.EstaContidoEm(AValue: string): Boolean; begin Result := S(AValue).Contem(Value); end; function TString.EstaContidoEm(AValue1, AValue2: string): Boolean; begin Result := Self.EstaContidoEm([AValue1, AValue2]); end; function TString.EstaContidoEm(AValue1, AValue2, AValue3: string): Boolean; begin Result := Self.EstaContidoEm([AValue1, AValue2, AValue3]); end; function TString.EstaContidoEm(AValue1, AValue2, AValue3, AValue4: string): Boolean; begin Result := Self.EstaContidoEm([AValue1, AValue2, AValue3, AValue4]); end; function TString.EstaContidoEm(AValues: array of string): Boolean; var I: Integer; begin Result := false; for I := 0 to High(AValues) do begin Result := AValues[I] = Value; if Result then Break; end; end; function TString.GetValue: string; begin Result := FValue; end; function TString.Mais(AValue: string): string; begin Result := Value + AValue; end; function TString.Mais(const AValue: IString): string; begin Result := S(Value).Mais(AValue.Value); end; function TString.Match(ARegex: UTF8String): Boolean; begin Regex.Compile(ARegex, True, True); Regex.Match(Value); Result := Regex.Match(Value); end; function TString.MatchDataFor(ARegex: UTF8String): IMatchData; begin Result := SX(Value).MatchDataFor(ARegex); end; function TString.Menos(AValue: string): string; begin Result := StringReplace(Value, AValue, '', [rfReplaceAll]); end; function TString.Menos(AValues: array of string): string; begin Result := ReplaceMany(Value, AValues, '', [rfReplaceAll]); end; procedure TString.SetValue(const Value: string); begin FValue := Value; end; function TString.Trim: string; begin Result := SysUtils.Trim(Value); end; function TString.TrimLeft: string; begin Result := SysUtils.TrimLeft(Value); end; function TString.TrimRight: string; begin Result := SysUtils.TrimRight(Value); end; function TString.Vezes(AValue: Integer): string; var I: Integer; begin Result := ''; for I := 1 to AValue do Result := Value + Result; end; function TString.WithoutAccents: string; var LAccentedChar: UTF8String; LAccentedLetterIndex: Integer; LLastOffSet: Integer; LResult: IXString; begin Regex.Compile(REGEX_ACCENTED_CHARS, True, True); LResult := SX(Value); if Regex.Match(Value) then begin repeat LAccentedChar := Regex.Captures[0]; LAccentedLetterIndex := S(ACCENTED_CHARS).IndexOf(LAccentedChar); LLastOffSet := Regex.CaptureRanges[0].LastPos + 1; if LAccentedLetterIndex >= 0 then LResult.ReplaceAll(LAccentedChar, UNACCENTED_CHARS[LAccentedLetterIndex]); until not Regex.Match(Value, LLastOffSet); end; Value := LResult.Value; Result := LResult.Value; end; function TString.ComZerosAEsquerda(ATamanho: Integer): string; begin Result := Self.AdicionarAntesDaString('0', ATamanho - Length); end; function TString.Decripta(AChave: string): string; begin Result := ''; // Criptografia.Encripta('D', Value, AChave) end; function TString.Encripta(AChave: string): string; begin Result := ''; // Criptografia.Encripta('E', Value, AChave) end; function TString.Format(AValues: array of const ): string; begin Result := SysUtils.Format(Value, AValues); end; procedure TString.Show; begin ShowMessage(Value); end; procedure TString.ShowWarning; var LTitulo: string; begin LTitulo := Application.Title; Application.MessageBox(Pchar(Value), Pchar(LTitulo), mb_ok + mb_iconwarning); end; procedure TString.ShowError; var LTitulo: string; begin LTitulo := Application.Title; Application.MessageBox(Pchar(Value), Pchar(LTitulo), mb_ok + mb_iconerror); end; function TString.ShowConfirmation: Boolean; var LTitulo: string; begin Result := false; LTitulo := Application.Title; if Application.MessageBox(Pchar(Value), Pchar(LTitulo), mb_yesno + mb_iconquestion) = idYes then Result := True; end; function TString.Reverter: string; begin Result := ReverseString(Value); end; procedure TString.SaveToFile(AArquivo: string = NOME_ARQUIVO); var LArquivo: TStringList; begin LArquivo := TStringList.Create; try LArquivo.Text := Value; LArquivo.SaveToFile(AArquivo); finally LArquivo.Free; end; end; function TString.ValidarComXSD(AArquivo: string): string; begin raise Exception.Create('Ainda não implementado'); end; function TString.Copy(AIndex, ACount: Integer): string; begin Result := System.Copy(Value, AIndex + 1, ACount); end; function TString.GetAt(De, Ate: Integer): string; begin Result := S(Value).Copy(De, Ate - De + 1); end; function TString.Replace(AOldPattern, ANewPattern: string): string; begin Result := Replace(AOldPattern, ANewPattern, []); end; function TString.Replace(AOldPattern, ANewPattern: string; Flags: TReplaceFlags): string; begin Result := StringReplace(Value, AOldPattern, ANewPattern, Flags); end; function TString.Regex: TJclRegEx; begin if FRegex = nil then begin FRegex := TJclRegEx.Create; FRegex.Options := FRegex.Options + [roNotEmpty, roNewLineAny, roUTF8, roIgnoreCase]; end; Result := FRegex; end; function TString.Replace(ARegexPattern: UTF8String; ANewPattern: string): string; var LOffSet: Integer; begin Regex.Compile(ARegexPattern, True, True); if Regex.Match(FValue) then repeat LOffSet := Regex.CaptureRanges[0].FirstPos; Delete(FValue, LOffSet, System.Length(Regex.Captures[0])); Insert(ANewPattern, FValue, LOffSet); until not Regex.Match(FValue, Regex.CaptureRanges[0].LastPos); Result := FValue; end; function TString.Replace(AOldPatterns: array of string; ANewPattern: string; Flags: TReplaceFlags): string; begin Result := ReplaceMany(Value, AOldPatterns, ANewPattern, Flags); end; function TString.Replace(AOldPatterns, ANewPatterns: array of string; Flags: TReplaceFlags): string; begin Result := ReplaceMany(Value, AOldPatterns, ANewPatterns, Flags); end; function TString.Replace(AOldPatterns: array of string; ANewPattern: string): string; begin Result := ReplaceMany(Value, AOldPatterns, ANewPattern, []); end; function TString.Replace(AOldPatterns, ANewPatterns: array of string): string; begin Result := ReplaceMany(Value, AOldPatterns, ANewPatterns, []); end; procedure TString.SetAt(De, Ate: Integer; const AValue: string); begin Value := S(Value).Replace(S(Value).Get[De, Ate], AValue); end; function TString.Length: Integer; begin Result := System.Length(Value); end; function TString.LowerCase: string; begin Result := SysUtils.LowerCase(Value); end; function TString.IndexOf(ASubstring: string): Integer; begin Result := System.Pos(ASubstring, Value) - 1; end; function TString.IndexOf(ASubstring: string; AOffSet: Integer): Integer; begin Result := StrUtils.PosEx(ASubstring, Value, AOffSet + 1) - 1; end; function TString.ComAspas: string; begin Result := QuotedStr(Value); end; function TString.UpperCase: string; begin Result := SysUtils.UpperCase(Value); end; function TString.UTF8Decode: string; begin Result := System.UTF8Decode(Value); end; function TString.UTF8Encode: string; begin Result := System.UTF8Encode(Value); end; function TString.Humanize: string; begin Result := Value; if Value <> '' then begin Result := SX(Value).ReplaceAll('_', ' ').LowerCase.Value; Result[1] := System.UpCase(Result[1]); end end; function TString.Camelize: string; var LOffset: Cardinal; begin Result := Value; Regex.Compile(REGEX_FIRST_WORD_LETTER, True, True); if Regex.Match(Result) then begin repeat LOffset := Regex.CaptureRanges[0].FirstPos; Delete(Result, LOffset, System.Length(Regex.Captures[0])); Insert(SysUtils.AnsiUpperCase(Regex.Captures[0]), Result, LOffset); until not Regex.Match(Result, Regex.CaptureRanges[0].LastPos + 1); end; end; function TString.Underscore: string; begin raise Exception.Create('Ainda não implementado'); end; function TString.Desumanize: string; begin raise Exception.Create('Ainda não implementado'); end; function TString.Modulo10: string; var Auxiliar: string; Contador, Peso: Integer; Digito: Integer; begin Auxiliar := ''; Peso := 2; for Contador := S(Value).Length downto 1 do begin Auxiliar := IntToStr(StrToInt(Value[Contador]) * Peso) + Auxiliar; if Peso = 1 then Peso := 2 else Peso := 1; end; Digito := 0; for Contador := 1 to S(Auxiliar).Length do begin Digito := Digito + StrToInt(Auxiliar[Contador]); end; Digito := 10 - (Digito mod 10); if (Digito > 9) then Digito := 0; Result := IntToStr(Digito); end; function TString.Modulo11(Base: Integer = 9; Resto: Boolean = false): string; var Soma: Integer; Contador, Peso, Digito: Integer; begin Soma := 0; Peso := 2; for Contador := S(Value).Length downto 1 do begin Soma := Soma + (StrToInt(Value[Contador]) * Peso); if Peso < Base then Peso := Peso + 1 else Peso := 2; end; if Resto then Result := IntToStr(Soma mod 11) else begin Digito := 11 - (Soma mod 11); if (Digito > 9) then Digito := 0; Result := IntToStr(Digito); end end; function TString.AsInteger: Integer; begin Result := StrToInt(Value); end; function TString.GetVazia: Boolean; begin Result := System.Length(Value) = 0; end; function TString.ReplaceAll(AOldPattern, ANewPattern: string): string; begin Result := S(Value).Replace(AOldPattern, ANewPattern, [rfReplaceAll]); end; function TString.ListarArquivos(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = #13#10): string; var LArquivos: TStringList; I: Integer; begin LArquivos := GetFileList(Value, AFiltro, AMostrarCaminhoCompleto); Result := ''; for I := 0 to LArquivos.Count - 1 do begin Result := Result + LArquivos[I]; if I <> LArquivos.Count - 1 then Result := Result + ASeparador; end; LArquivos.Free; end; function TString.ListarArquivosComPrefixoParaCopy(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = #13#10): string; var LArquivos: TStringList; I: Integer; begin LArquivos := GetFileList(Value, AFiltro, AMostrarCaminhoCompleto, True); Result := ''; for I := 0 to LArquivos.Count - 1 do begin Result := Result + LArquivos[I]; if I <> LArquivos.Count - 1 then Result := Result + ASeparador; end; LArquivos.Free; end; function TString.ListarPastas(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = #13#10): string; var LPastas: TStringList; I: Integer; begin LPastas := TypeUtils.ListarPastas(Value, AMostrarCaminhoCompleto, AFiltro); Result := ''; for I := 0 to LPastas.Count - 1 do begin Result := Result + LPastas[I]; if I <> LPastas.Count - 1 then Result := Result + ASeparador; end; LPastas.Free; end; function TString.ListarPastasEArquivos(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = #13#10; IncluirSubPastas: Boolean = false): string; var LItems: TStrings; I: Integer; begin LItems := TypeUtils.ListarPastasEArquivos(Value, IncluirSubPastas, AFiltro, AMostrarCaminhoCompleto); Result := ''; for I := 0 to LItems.Count - 1 do begin Result := Result + LItems[I]; if I <> LItems.Count - 1 then Result := Result + ASeparador; end; LItems.Free; end; function TString.Aspas: string; begin Result := S(Value).ComAspas; end; function TString.GetAtStr(De, Ate: string): string; begin Result := Self[IndexOf(De), IndexOf(Ate)]; end; procedure TString.SetAtStr(De, Ate: string; const AValue: string); begin Self[IndexOf(De), IndexOf(Ate)] := AValue; end; function TString.Ate(APosicao: Integer): string; begin Result := Self[0, APosicao]; end; function TString.Ate(APosicao: string): string; begin Result := Self[0, IndexOf(APosicao)]; end; function TString.AteAntesDe(APosicao: string): string; begin Result := Self[0, IndexOf(APosicao) - 1]; end; function TString.EncriptSimples: string; begin Result := ''; // Encript(Value); end; function TString.LoadFromFile: string; var LArquivo: TStringList; begin LArquivo := TStringList.Create; try LArquivo.LoadFromFile(Value); Result := LArquivo.Text; finally LArquivo.Free end; end; function TString.AsStringList: TStringList; begin Result := TStringList.Create; Result.Text := Value; end; function TString.Contem(AValues: array of string): Boolean; var I: Integer; begin Result := false; for I := 0 to High(AValues) do if S(Value).Contem(AValues[I]) then begin Result := True; Break; end; end; function TString.IndiceNoArray(AArray: array of string): Integer; begin Result := TypeUtils.IndexOf(Value, AArray); end; function TString.Equals(AValor: IString): Boolean; begin Result := Equals(AValor.Value); end; function TString.Equals(AValor: string): Boolean; begin Result := Value = AValor; end; function TString.IgualA(AValor: IString): Boolean; begin Result := Equals(AValor.Value); end; function TString.IgualA(AValor: string): Boolean; begin Result := Equals(AValor); end; function TString.GetChave(ANome: string): string; var LArquivo: TStringList; I: Integer; begin Result := ''; LArquivo := TStringList.Create; try LArquivo.LoadFromFile(Value); for I := 0 to LArquivo.Count - 1 do begin if S(LArquivo[I]).Contem(ANome) then begin Result := SX(LArquivo[I]).Reverter.AteAntesDe(':').Reverter.Trim.Value; Break; end; end; finally LArquivo.Free; end end; function TString.IsEmpty(ATrimBefore: boolean = False): Boolean; begin Result := SX(Value).IsEmpty(ATrimBefore); end; procedure TString.SetChave(ANome: string; const Value: string); begin // end; { TXString } function TXString.AdicionarAntesDaString(AValue: string; Repetir: Integer): IXString; begin Value := S(Value).AdicionarAntesDaString(AValue, Repetir); Result := Self; end; function TXString.AdicionarDepoisDaString(AValue: string; Repetir: Integer): IXString; begin Value := S(Value).AdicionarDepoisDaString(AValue, Repetir); Result := Self; end; function TXString.AlinhadoADireita(ATamanho: Integer): IXString; begin Value := S(Value).AlinhadoADireita(ATamanho); Result := Self; end; function TXString.AlinhadoAEsquerda(ATamanho: Integer): IXString; begin Value := S(Value).AlinhadoAEsquerda(ATamanho); Result := Self; end; function TXString.Camelize: IXString; begin Value := S(Value).Camelize; Result := Self; end; function TXString.Centralizado(ATamanho: Integer): IXString; begin Value := S(Value).Centralizado(ATamanho); Result := Self; end; procedure TXString.Clear; begin Value := ''; end; function TXString.ComAspas: IXString; begin Value := S(Value).ComAspas; Result := Self; end; function TXString.ComZerosAEsquerda(ATamanho: Integer): IXString; begin Value := S(Value).ComZerosAEsquerda(ATamanho); Result := Self; end; function TXString.Contem(AValue: string): Boolean; begin Result := S(Self.Value).Contem(AValue); end; function TXString.Copy(AIndex, ACount: Integer): IXString; begin Value := S(Value).Copy(AIndex, ACount); Result := Self; end; constructor TXString.Create(AValue: string); begin FValue := TString.Create(AValue); end; function TXString.After(AIndex: Integer): IXString; begin Result := Copy(AIndex, Length); end; function TXString.AsClassName(AUsingPrefix: string = 'T'): IXString; begin Value := S(Value).AsClassName(AUsingPrefix); Result := Self; end; function TXString.AsInteger: Integer; begin Result := StrToInt(Value); end; function TXString.Decripta(AChave: string): IXString; begin Value := S(Value).Decripta(AChave); Result := Self; end; function TXString.Encripta(AChave: string): IXString; begin Value := S(Value).Encripta(AChave); Result := Self; end; function TXString.EstaContidoEm(AValue: string): Boolean; begin Result := S(Self.Value).EstaContidoEm(AValue); end; function TXString.EstaContidoEm(AValues: array of string): Boolean; begin Result := S(Self.Value).EstaContidoEm(AValues); end; function TXString.Format(AValues: array of const ): IXString; begin Value := S(Value).Format(AValues); Result := Self; end; function TXString.GetAt(De, Ate: Integer): IXString; begin Value := S(Value)[De, Ate]; Result := Self; end; function TXString.GetValue: string; begin Result := FValue.Value; end; function TXString.IndexOf(ASubstring: string): Integer; begin Result := S(Value).IndexOf(ASubstring); end; function TXString.Humanize: IXString; begin Value := S(Value).Humanize; Result := Self; end; function TXString.IndexOf(ASubstring: string; AOffSet: Integer): Integer; begin Result := S(Value).IndexOf(ASubstring, AOffSet); end; function TXString.IsEmpty(ATrimBefore: boolean = False): Boolean; begin if not ATrimBefore then Result := System.Length(Value) = 0 else Result := Self.Trim.IsEmpty; end; function TXString.Length: Integer; begin Result := S(Value).Length; end; function TXString.LowerCase: IXString; begin Value := S(Value).LowerCase; Result := Self; end; function TXString.Mais(AValue: string): IXString; begin Value := S(Value).Mais(AValue); Result := Self; end; function TXString.Mais(const AValue: IXString): IXString; begin Result := Self.Mais(AValue.Value); end; function TXString.Match(ARegex: UTF8String): Boolean; begin Result := S(Value).Match(ARegex); end; function TXString.MatchDataFor(ARegex: UTF8String): IMatchData; var LCaptureIndex: Integer; LFirstMatchedCharPos: Integer; LLastMatchedCharPos: Integer; LOffSet: TMatchOffSet; begin Result := nil; Regex.Compile(ARegex, True, True); if Regex.Match(Value) then begin Result := TMatchData.Create(Regex.CaptureCount); Result.MatchedData := SX(Regex.Captures[0]); LFirstMatchedCharPos := Regex.CaptureRanges[0].FirstPos; LLastMatchedCharPos := Regex.CaptureRanges[0].LastPos; if LFirstMatchedCharPos > 1 then Result.PreMatch := SX(Value).Ate(LFirstMatchedCharPos - 2) else Result.PreMatch := SX(''); Result.PostMatch := SX(Value).After(LLastMatchedCharPos); for LCaptureIndex := 0 to Regex.CaptureCount - 1 do begin Result[LCaptureIndex] := SX(Regex.Captures[LCaptureIndex]); LOffSet.Start := Regex.CaptureRanges[LCaptureIndex].FirstPos; LOffSet.Stop := Regex.CaptureRanges[LCaptureIndex].LastPos; Result.OffSet[LCaptureIndex] := LOffSet; Result.Start[LCaptureIndex] := I(Regex.CaptureRanges[LCaptureIndex].FirstPos); Result.Stop[LCaptureIndex] := I(Regex.CaptureRanges[LCaptureIndex].LastPos); end; // LCaptureIndex := 0; // repeat // Result[LCaptureIndex] := SX(Regex.Captures[0]); // Inc(LCaptureIndex); // until not Regex.Match(Value, Regex.CaptureRanges[0].LastPos + 1); Result.Size := I(Regex.CaptureCount); end; end; function TXString.Menos(AValues: array of string): IXString; begin Value := S(Value).Menos(AValues); Result := Self; end; function TXString.Menos(AValue: string): IXString; begin Value := S(Value).Menos(AValue); Result := Self; end; function TXString.Replace(AOldPattern, ANewPattern: string): IXString; begin Value := S(Value).Replace(AOldPattern, ANewPattern); Result := Self; end; function TXString.Replace(AOldPattern, ANewPattern: string; Flags: TReplaceFlags): IXString; begin Value := S(Value).Replace(AOldPattern, ANewPattern, Flags); Result := Self; end; function TXString.Replace(AOldPatterns: array of string; ANewPattern: string; Flags: TReplaceFlags): IXString; begin Value := S(Value).Replace(AOldPatterns, ANewPattern, Flags); Result := Self; end; function TXString.Replace(ARegexPattern: UTF8String; ANewPattern: string): IXString; begin Value := S(Value).Replace(ARegexPattern, ANewPattern); Result := Self; end; function TXString.Replace(AOldPatterns, ANewPatterns: array of string; Flags: TReplaceFlags): IXString; begin Value := S(Value).Replace(AOldPatterns, ANewPatterns, Flags); Result := Self; end; function TXString.Replace(AOldPatterns: array of string; ANewPattern: string): IXString; begin Value := S(Value).Replace(AOldPatterns, ANewPattern, []); Result := Self; end; function TXString.Replace(AOldPatterns, ANewPatterns: array of string): IXString; begin Value := S(Value).Replace(AOldPatterns, ANewPatterns, []); Result := Self; end; function TXString.Reverter: IXString; begin Value := S(Value).Reverter; Result := Self; end; function TXString.SaveToFile(AArquivo: string = NOME_ARQUIVO): IXString; begin S(Value).SaveToFile(AArquivo); Result := Self; end; procedure TXString.SetAt(De, Ate: Integer; const AValue: IXString); begin S(Value)[De, Ate] := Value; end; procedure TXString.SetValue(const AValue: string); begin FValue.Value := AValue; end; function TXString.Show: IXString; begin S(Value).Show; Result := Self; end; function TXString.ShowWarning: IXString; begin S(Value).ShowWarning; Result := Self; end; function TXString.ShowError: IXString; begin S(Value).ShowWarning; Result := Self; end; function TXString.ShowConfirmation: Boolean; begin Result := S(Value).ShowConfirmation; ; end; function TXString.Trim: IXString; begin Value := S(Value).Trim; Result := Self; end; function TXString.TrimLeft: IXString; begin Value := S(Value).TrimLeft; Result := Self; end; function TXString.TrimRight: IXString; begin Value := S(Value).TrimRight; Result := Self; end; function TXString.UpperCase: IXString; begin Value := S(Value).UpperCase; Result := Self; end; function TXString.UTF8Decode: IXString; begin Value := S(Value).UTF8Decode; Result := Self; end; function TXString.UTF8Encode: IXString; begin Value := S(Value).UTF8Encode; Result := Self; end; function TXString.ValidarComXSD(AArquivo: string): IXString; begin S(Value).ValidarComXSD(AArquivo); Result := Self; end; function TXString.Vezes(AValue: Integer): IXString; begin Value := S(Value).Vezes(AValue); Result := Self; end; function TXString.WithoutAccents: IXString; begin Value := S(Value).WithoutAccents; Result := Self; end; function TXString.Underscore: IXString; begin Value := S(Value).Underscore; Result := Self; end; destructor TXString.Destroy; begin inherited; if Assigned(FRegex) then FreeAndNil(FRegex); end; function TXString.Desumanize: IXString; begin Value := S(Value).Desumanize; Result := Self; end; function TXString.ReplaceAll(AOldPattern, ANewPattern: string): IXString; begin Value := S(Value).ReplaceAll(AOldPattern, ANewPattern); Result := Self; end; function TXString.ListarArquivos(AFiltro: string = '*.*'; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = #13#10): IXString; begin Value := S(Value).ListarArquivos(AFiltro, AMostrarCaminhoCompleto, ASeparador); Result := Self; end; function TXString.ListarArquivosComPrefixoParaCopy(AFiltro: string; AMostrarCaminhoCompleto: Boolean): IXString; begin Value := S(Value).ListarArquivosComPrefixoParaCopy(AFiltro, AMostrarCaminhoCompleto); Result := Self; end; function TXString.Ate(APosicao: Integer): IXString; begin Value := S(Value).Ate(APosicao); Result := Self; end; function TXString.Ate(APosicao: string): IXString; begin Value := S(Value).Ate(APosicao); Result := Self; end; function TXString.AteAntesDe(APosicao: string): IXString; begin Value := S(Value).AteAntesDe(APosicao); Result := Self; end; function TXString.LoadFromFile: IXString; begin Value := S(Value).LoadFromFile; Result := Self; end; function TXString.EstaContidoEm(AValue1, AValue2: string): Boolean; begin Result := S(Self.Value).EstaContidoEm(AValue1, AValue2); end; function TXString.EstaContidoEm(AValue1, AValue2, AValue3: string): Boolean; begin Result := S(Self.Value).EstaContidoEm(AValue1, AValue2, AValue3); end; function TXString.EstaContidoEm(AValue1, AValue2, AValue3, AValue4: string): Boolean; begin Result := S(Self.Value).EstaContidoEm(AValue1, AValue2, AValue3, AValue4); end; function TXString.ListarPastas(AFiltro: string; AMostrarCaminhoCompleto: Boolean): IXString; begin Value := S(Value).ListarPastas(AFiltro, AMostrarCaminhoCompleto); Result := Self; end; function TXString.ListarPastasEArquivos(AFiltro: string = FILTRO_PADRAO_DE_ARQUIVO; AMostrarCaminhoCompleto: Boolean = True; ASeparador: string = QUEBRA_DE_LINHA; Recursividade: Boolean = false): IXString; begin Value := S(Value).ListarPastasEArquivos(AFiltro, AMostrarCaminhoCompleto, ASeparador, Recursividade); Result := Self; end; function TXString.AsStringList: TStringList; begin Result := S(Value).AsStringList; end; function TXString.Equals(AValor: IXString): Boolean; begin Result := Equals(AValor.Value); end; function TXString.Equals(AValor: IString): Boolean; begin Result := Equals(AValor.Value); end; function TXString.Equals(AValor: string): Boolean; begin Result := Value = AValor; end; function TXString.IgualA(AValor: IXString): Boolean; begin Result := Equals(AValor.Value); end; function TXString.IgualA(AValor: IString): Boolean; begin Result := Equals(AValor.Value); end; function TXString.IgualA(AValor: string): Boolean; begin Result := Equals(AValor); end; function TXString.Contem(AValues: array of string): Boolean; begin Result := S(Value).Contem(AValues); end; function TXString.Regex: TJclRegEx; begin if FRegex = nil then begin FRegex := TJclRegEx.Create; FRegex.Options := FRegex.Options + [roNotEmpty, roNewLineAny, roUTF8, roIgnoreCase]; end; Result := FRegex; end; function I(AIntegerValue: Integer): IInteger; begin Result := TInteger.Create(AIntegerValue); end; function URI(const AURI: string): IURI; begin Result := TURI.Create(AURI); end; { TInteger } function TInteger.AsString: string; begin Result := IntToStr(FValue); end; constructor TInteger.Create(AValue: Integer); begin FValue := AValue; end; function TInteger.Format(AFormat: string = '000000'): string; begin Result := FormatFloat(AFormat, FValue); end; function TInteger.GetValue: Integer; begin Result := FValue; end; function TInteger.Next: Integer; begin Inc(FValue); Result := FValue; end; procedure TInteger.SetValue(const Value: Integer); begin FValue := Value; end; procedure TInteger.Times(AMetodo: TIntegerProc); var I: Integer; begin for I := 0 to Value - 1 do AMetodo; end; constructor TMatchData.Create(const ASize: Integer); begin inherited Create; FCaptures := TInterfaceList.Create; FSize := I(ASize); SetLength(FOffSets, ASize); SetLength(FStarts, ASize); SetLength(FStops, ASize); end; function TMatchData.GetCaptures(Index: Integer): IXString; begin Result := FCaptures[Index] as IXString; end; function TMatchData.GetMatchedData: IXString; begin Result := FMatchedData; end; function TMatchData.GetPostMatch: IXString; begin Result := FPostMatch; end; function TMatchData.GetPreMatch: IXString; begin Result := FPreMatch; end; function TMatchData.GetSize: IInteger; begin Result := FSize; end; function TMatchData.GetOffSet(Index: Integer): TMatchOffSet; begin Result := FOffSets[Index]; end; procedure TMatchData.SetCaptures(Index: Integer; const Value: IXString); begin if (FCaptures.Count - 1 < Index) then FCaptures.Add(Value) else FCaptures[Index] := Value; end; procedure TMatchData.SetMatchedData(const Value: IXString); begin FMatchedData := Value; end; procedure TMatchData.SetOffSet(Index: Integer; const Value: TMatchOffSet); begin FOffSets[Index] := Value; end; procedure TMatchData.SetPostMatch(const Value: IXString); begin FPostMatch := Value; end; procedure TMatchData.SetPreMatch(const Value: IXString); begin FPreMatch := Value; end; procedure TMatchData.SetSize(const Value: IInteger); begin FSize := Value; end; function TMatchData.GetStart(Index: Integer): IInteger; begin Result := FStarts[Index]; end; procedure TMatchData.SetStart(Index: Integer; const Value: IInteger); begin FStarts[Index] := Value; end; function TMatchData.GetStop(Index: Integer): IInteger; begin Result := FStops[Index]; end; procedure TMatchData.SetStop(Index: Integer; const Value: IInteger); begin FStops[Index] := Value; end; constructor TURI.Create(const AURL: string); begin InitInstance; FURL.Value := AURL; end; constructor TURI.Create(const AURL: IXString); begin InitInstance; FURL.Value := AURL.Value; end; function TURI.Document: IXString; begin FDocument := FURL.MatchDataFor(REGEX_LAST_PATH).MatchedData.MatchDataFor(REGEX_DOCUMENT).MatchedData; Result := FDocument; end; function TURI.EncodedURI: IXString; begin FEncodedURI.Value := HTTPEncode(FURL.Value); Result := FEncodedURI; end; function TURI.GetURL: IXString; begin Result := FURL; end; procedure TURI.InitInstance; begin FDocument := SX(''); FURL := SX(''); FEncodedURI := SX(''); end; procedure TURI.SetURL(const Value: IXString); begin FURL := Value; end; end.
unit nscDocumentListTreeView; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Components\nscDocumentListTreeView.pas" // Стереотип: "GuiControl" // Элемент модели: "TnscDocumentListTreeView" MUID: (51D56E9F004B) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , nscTreeViewWithAdapterDragDrop {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} , nscDocumentHistory {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) , Messages , Classes , l3Interfaces , Graphics , vtLister , ActiveX , bsTypes ; type TdltGetNodeTypeEvent = function(anIndex: Integer): TbsListNodeType of object; TnscDocumentListTreeView = class(TnscTreeViewWithAdapterDragDrop{$If NOT Defined(Admin) AND NOT Defined(Monitorings)} , InscDocumentHistoryListener {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) ) private f_OnGetNodeType: TdltGetNodeTypeEvent; private procedure WMGetText(var Msg: TWMGetText); message WM_GetText; procedure WMGetTextLength(var Msg: TWMGetTextLength); message WM_GETTEXTLENGTH; protected function GetCurrentText: AnsiString; virtual; {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} procedure NewDocumentInHistory; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; procedure DoOnGetItemStyle(aItemIndex: Integer; const aFont: Il3Font; var aTextBackColor: TColor; var aItemBackColor: TColor; var aVJustify: TvtVJustify; var aFocused: Boolean; var theImageVertOffset: Integer); override; procedure DoOnGetItemFont(Index: LongInt; const aFont: Il3Font; anItemPart: TvtListerItemPart); override; function DoOnGetItemIndentEx(anItemIndex: Integer): Integer; override; {* для каждой ноды можно задать свой "персональный" сдвиг } function CanAcceptData(const aData: IDataObject): Boolean; override; function GetRealClientWidth: Integer; override; function NeedAssignTreeStructFromHistory: Boolean; override; public constructor Create(AOwner: TComponent); override; public property OnGetNodeType: TdltGetNodeTypeEvent read f_OnGetNodeType write f_OnGetNodeType; end;//TnscDocumentListTreeView implementation uses l3ImplUses , l3ControlsTypes , l3TreeInterfaces , Windows , SysUtils , l3String , evStyleTableTools , l3Units , l3ScreenIC , evdStyles , DynamicDocListUnit , DynamicTreeUnit {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *51D56E9F004Bimpl_uses* //#UC END# *51D56E9F004Bimpl_uses* ; function TnscDocumentListTreeView.GetCurrentText: AnsiString; //#UC START# *51E01CC7023D_51D56E9F004B_var* var l_Node: Il3SimpleNode; //#UC END# *51E01CC7023D_51D56E9F004B_var* begin //#UC START# *51E01CC7023D_51D56E9F004B_impl* // Здесь если просто проверить IsEmpty - получаем весь список СКР к документу // при возврате по истории. Может что-то отъехать. // http://mdp.garant.ru/pages/viewpage.action?pageId=476810519 if IsTreeStructAssigned and (not IsEmpty) then begin l_Node := TreeStruct.Nodes[Current]; Result := l3Str(l_Node.Text); end else Result := ''; //#UC END# *51E01CC7023D_51D56E9F004B_impl* end;//TnscDocumentListTreeView.GetCurrentText procedure TnscDocumentListTreeView.WMGetText(var Msg: TWMGetText); //#UC START# *51E00D2000A7_51D56E9F004B_var* //#UC END# *51E00D2000A7_51D56E9F004B_var* begin //#UC START# *51E00D2000A7_51D56E9F004B_impl* Msg.Result := StrLen(StrPLCopy(Msg.Text, GetCurrentText, Msg.TextMax - 1)); //#UC END# *51E00D2000A7_51D56E9F004B_impl* end;//TnscDocumentListTreeView.WMGetText procedure TnscDocumentListTreeView.WMGetTextLength(var Msg: TWMGetTextLength); //#UC START# *51E00DAD024C_51D56E9F004B_var* //#UC END# *51E00DAD024C_51D56E9F004B_var* begin //#UC START# *51E00DAD024C_51D56E9F004B_impl* Msg.Result := Length(GetCurrentText); //#UC END# *51E00DAD024C_51D56E9F004B_impl* end;//TnscDocumentListTreeView.WMGetTextLength {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} procedure TnscDocumentListTreeView.NewDocumentInHistory; //#UC START# *55E6CC91033A_51D56E9F004B_var* //#UC END# *55E6CC91033A_51D56E9F004B_var* begin //#UC START# *55E6CC91033A_51D56E9F004B_impl* DropDrawPoints; //#UC END# *55E6CC91033A_51D56E9F004B_impl* end;//TnscDocumentListTreeView.NewDocumentInHistory {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) procedure TnscDocumentListTreeView.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_51D56E9F004B_var* //#UC END# *479731C50290_51D56E9F004B_var* begin //#UC START# *479731C50290_51D56E9F004B_impl* TnscDocumentHistory.Instance.RemoveListener(Self); inherited; //#UC END# *479731C50290_51D56E9F004B_impl* end;//TnscDocumentListTreeView.Cleanup procedure TnscDocumentListTreeView.InitFields; //#UC START# *47A042E100E2_51D56E9F004B_var* //#UC END# *47A042E100E2_51D56E9F004B_var* begin //#UC START# *47A042E100E2_51D56E9F004B_impl* inherited; TnscDocumentHistory.Instance.AddListener(Self); //#UC END# *47A042E100E2_51D56E9F004B_impl* end;//TnscDocumentListTreeView.InitFields constructor TnscDocumentListTreeView.Create(AOwner: TComponent); //#UC START# *47D1602000C6_51D56E9F004B_var* //#UC END# *47D1602000C6_51D56E9F004B_var* begin //#UC START# *47D1602000C6_51D56E9F004B_impl* inherited; ViewOptions := [voShowInterRowSpace, voShowIcons, voShowExpandable, voShowOpenChip{, voDoNotShowFocusRect, voFullLineSelect}]; //#UC END# *47D1602000C6_51D56E9F004B_impl* end;//TnscDocumentListTreeView.Create procedure TnscDocumentListTreeView.DoOnGetItemStyle(aItemIndex: Integer; const aFont: Il3Font; var aTextBackColor: TColor; var aItemBackColor: TColor; var aVJustify: TvtVJustify; var aFocused: Boolean; var theImageVertOffset: Integer); //#UC START# *508F825303E4_51D56E9F004B_var* function l_IsVisited(const aNode: Il3SimpleNode): Boolean; var l_DocId: Integer; l_NB: INodeBase; l_DN: IDynListNode; begin if Supports(aNode, INodeBase, l_NB) then if Supports(l_NB, IDynListNode, l_DN) then begin l_DocId := l_DN.GetDocumentId; if l_DocId <> 0 then begin Assert(l_DocId >= 100000); if TnscDocumentHistory.Instance.HasDocument(l_DN.GetDocumentId - 100000) then begin Result := True; Exit; end; end; end; Result := False; end; var l_Color: TColor; l_Node: Il3SimpleNode; //#UC END# *508F825303E4_51D56E9F004B_var* begin //#UC START# *508F825303E4_51D56E9F004B_impl* inherited DoOnGetItemStyle(aItemIndex, aFont, aTextBackColor, aItemBackColor, aVJustify, aFocused, theImageVertOffset); if not SelfDrawNodes then if Assigned(TreeStruct.Nodes[aItemIndex]) then if not IsEmpty then begin l_Color := aFont.ForeColor; try l_Node := TreeStruct.Nodes[aItemIndex]; if l_IsVisited(l_Node) then evGetStyleFont(aFont, ev_saVisitedDocumentInList); finally if aFocused then aFont.ForeColor := l_Color; end; end; //#UC END# *508F825303E4_51D56E9F004B_impl* end;//TnscDocumentListTreeView.DoOnGetItemStyle procedure TnscDocumentListTreeView.DoOnGetItemFont(Index: LongInt; const aFont: Il3Font; anItemPart: TvtListerItemPart); //#UC START# *5152C7D50201_51D56E9F004B_var* //#UC END# *5152C7D50201_51D56E9F004B_var* begin //#UC START# *5152C7D50201_51D56E9F004B_impl* inherited DoOnGetItemFont(Index, aFont, anItemPart); if (anItemPart in [vt_lipTextHint, vt_lipIconHint]) then aFont.Style := aFont.Style - [fsBold]; //#UC END# *5152C7D50201_51D56E9F004B_impl* end;//TnscDocumentListTreeView.DoOnGetItemFont function TnscDocumentListTreeView.DoOnGetItemIndentEx(anItemIndex: Integer): Integer; {* для каждой ноды можно задать свой "персональный" сдвиг } //#UC START# *51D2DC290320_51D56E9F004B_var* //#UC END# *51D2DC290320_51D56E9F004B_var* begin //#UC START# *51D2DC290320_51D56E9F004B_impl* Result := 0; if Assigned(TreeStruct.Nodes[anItemIndex]) then if (not IsEmpty) and (TreeStruct.Nodes[anItemIndex].GetLevel > 1) then if Assigned(f_OnGetNodeType) then if f_OnGetNodeType(anItemIndex) = lntBlock then Result := l3CrtIC.LP2DP(l3PointX(evGetStyleFirstIndent(ev_saSnippet))).X else Result := 5; //#UC END# *51D2DC290320_51D56E9F004B_impl* end;//TnscDocumentListTreeView.DoOnGetItemIndentEx function TnscDocumentListTreeView.CanAcceptData(const aData: IDataObject): Boolean; //#UC START# *51EEB81F017C_51D56E9F004B_var* var l_List: IDynList; //#UC END# *51EEB81F017C_51D56E9F004B_var* begin //#UC START# *51EEB81F017C_51D56E9F004B_impl* if Supports(TreeStruct, IDynList, l_List) and l_List.GetIsSnippet then Result := False else Result := inherited CanAcceptData(aData); //#UC END# *51EEB81F017C_51D56E9F004B_impl* end;//TnscDocumentListTreeView.CanAcceptData function TnscDocumentListTreeView.GetRealClientWidth: Integer; //#UC START# *543239ED008D_51D56E9F004B_var* //#UC END# *543239ED008D_51D56E9F004B_var* begin //#UC START# *543239ED008D_51D56E9F004B_impl* Result := inherited GetRealClientWidth; if (not IsVScrollVisible) then Dec(Result, GetSystemMetrics(SM_CXVSCROLL)); // - http://mdp.garant.ru/pages/viewpage.action?pageId=516166484 //#UC END# *543239ED008D_51D56E9F004B_impl* end;//TnscDocumentListTreeView.GetRealClientWidth function TnscDocumentListTreeView.NeedAssignTreeStructFromHistory: Boolean; //#UC START# *5604EC1403A8_51D56E9F004B_var* //#UC END# *5604EC1403A8_51D56E9F004B_var* begin //#UC START# *5604EC1403A8_51D56E9F004B_impl* Result := (not LoadingCloneState); //#UC END# *5604EC1403A8_51D56E9F004B_impl* end;//TnscDocumentListTreeView.NeedAssignTreeStructFromHistory initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TnscDocumentListTreeView); {* Регистрация TnscDocumentListTreeView } {$IfEnd} // NOT Defined(NoScripts) end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 产品退货单处理 *******************************************************************************} unit UFrameProductReturn; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, UGridPainter, cxControls, cxLookAndFeels, cxLookAndFeelPainters, Grids, UGridExPainter, cxPC, StdCtrls, ExtCtrls, cxGraphics, Menus, cxButtons; type TfFrameProductReturn = class(TfFrameBase) PanelR: TPanel; LabelHint: TLabel; wPage: TcxPageControl; Sheet1: TcxTabSheet; Sheet2: TcxTabSheet; GridBill: TDrawGridEx; GridDone: TDrawGridEx; procedure BtnExitClick(Sender: TObject); procedure wPageChange(Sender: TObject); private { Private declarations } FPainter: TGridPainter; FPainter2: TGridPainter; //绘图对象 FDoneLoaded: Boolean; //载入标记 procedure LoadProductReturn; procedure LoadProductReturnDone; //产品列表 procedure OnBtnClick(Sender: TObject); procedure OnBtnClick2(Sender: TObject); procedure OnBtnClick3(Sender: TObject); //点击按钮 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses IniFiles, ULibFun, UDataModule, DB, UMgrControl, USysConst, USysDB, USysFun, UFormReturnConfirm, UFormProductReturnAdjust, UFormProductReturnView; class function TfFrameProductReturn.FrameID: integer; begin Result := cFI_FrameReturnDL; end; procedure TfFrameProductReturn.OnCreateFrame; var nIni: TIniFile; begin FDoneLoaded := False; Name := MakeFrameName(FrameID); FPainter := TGridPainter.Create(GridBill); FPainter2 := TGridPainter.Create(GridDone); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('状态', 50); AddHeader('退货单号', 50); AddHeader('商品款式', 50); AddHeader('退货件数', 50); AddHeader('现有库存', 50); AddHeader('退货人', 50); AddHeader('退货日期', 50); AddHeader('操作', 50); end; with FPainter2 do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('退货单号', 50); AddHeader('商品款式', 50); AddHeader('退货件数', 50); AddHeader('退货人', 50); AddHeader('退货日期', 50); AddHeader('收货人', 50); AddHeader('收货日期', 50); AddHeader('操作', 50); end; nIni := TIniFile.Create(gPath + sFormConfig); try LoadDrawGridConfig(Name, GridBill, nIni); LoadDrawGridConfig(Name, GridDone, nIni); wPage.ActivePage := Sheet1; LoadProductReturn; finally nIni.Free; end; end; procedure TfFrameProductReturn.OnDestroyFrame; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveDrawGridConfig(Name, GridBill, nIni); SaveDrawGridConfig(Name, GridDone, nIni); finally nIni.Free; end; FPainter.Free; FPainter2.Free; end; procedure TfFrameProductReturn.BtnExitClick(Sender: TObject); begin Close; end; //Desc: 载入未完成退单 procedure TfFrameProductReturn.LoadProductReturn; var nStr,nHint: string; nDS: TDataSet; nIdx,nInt: Integer; nBtn: TcxButton; nData: TGridDataArray; begin nStr := 'Select Top 50 rt.*,rd.*,P_Number,StyleName,ColorName,' + 'SizeName From $RD rd ' + ' Left Join $PT pt On pt.ProductID=rd.D_Product ' + ' Left Join $ST st On st.StyleID=pt.StyleID ' + ' Left Join $SZ sz On sz.SizeID=pt.SizeID ' + ' Left Join $CR cr On cr.ColorID=pt.ColorID ' + ' Left Join $RT rt On rt.T_ID=rd.D_Return ' + ' Left Join $TP tp On tp.P_ID=rd.D_Product ' + 'Where T_TerminalId=''$ID'' And T_Status<>''$OK'' ' + 'Order By D_Return DESC'; //xxxxx nStr := MacroValue(nStr, [MI('$RD', sTable_ReturnDtl), MI('$TP', sTable_Product), MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size), MI('$CR', sTable_DL_Color), MI('$RT', sTable_Return), MI('$ID', gSysParam.FTerminalID), MI('$OK', sFlag_BillDone)]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin First; nInt := 1; while not Eof do begin SetLength(nData, 10); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := BillStatusDesc(FieldByName('T_Status').AsString, False); nData[2].FText := FieldByName('D_Return').AsString; nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString, FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]); nData[3].FText := nStr; nData[4].FText := FieldByName('D_Number').AsString; nData[5].FText := IntToStr(FieldByName('P_Number').AsInteger); nData[6].FText := FieldByName('T_Man').AsString; nData[7].FText := DateTime2Str(FieldByName('T_Date').AsDateTime); with nData[8] do begin FText := ''; FAlign := taLeftJustify; FCtrls := TList.Create; if FieldByName('T_Status').AsString = sFlag_BillLock then begin nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '调整'; Width := 35; Height := 18; OnClick := OnBtnClick2; Tag := FPainter.DataCount; end; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '确认'; Width := 35; Height := 18; OnClick := OnBtnClick2; Tag := FPainter.DataCount; end; end else begin nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '查看'; Width := 35; Height := 18; OnClick := OnBtnClick; Tag := FPainter.DataCount; end; end; end; nData[9].FText := FieldByName('R_ID').AsString; FPainter.AddData(nData); Next; end; end; FDoneLoaded := False; finally FDM.ReleaseDataSet(nDS); end; end; //Desc: 载入已完成退单 procedure TfFrameProductReturn.LoadProductReturnDone; var nStr,nHint: string; nDS: TDataSet; nIdx,nInt: Integer; nBtn: TcxButton; nData: TGridDataArray; begin if FDoneLoaded then Exit; //重复载入判定 nStr := 'Select Top 50 rt.*,rd.*,StyleName,ColorName,SizeName From $RD rd ' + ' Left Join $PT pt On pt.ProductID=rd.D_Product ' + ' Left Join $ST st On st.StyleID=pt.StyleID ' + ' Left Join $SZ sz On sz.SizeID=pt.SizeID ' + ' Left Join $CR cr On cr.ColorID=pt.ColorID ' + ' Left Join $RT rt On rt.T_ID=rd.D_Return ' + 'Where T_TerminalId=''$ID'' And T_Status=''$OK'' ' + 'Order By D_Return DESC'; //xxxxx nStr := MacroValue(nStr, [MI('$RD', sTable_ReturnDtl), MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size), MI('$CR', sTable_DL_Color), MI('$RT', sTable_Return), MI('$ID', gSysParam.FTerminalID), MI('$OK', sFlag_BillDone)]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter2.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin First; nInt := 1; while not Eof do begin SetLength(nData, 9); for nIdx:=Low(nData) to High(nData) do begin nData[nIdx].FCtrls := nil; nData[nIdx].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FieldByName('D_Return').AsString; nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString, FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]); nData[2].FText := nStr; nData[3].FText := FieldByName('D_Number').AsString; nData[4].FText := FieldByName('T_Man').AsString; nData[5].FText := DateTime2Str(FieldByName('T_Date').AsDateTime); nData[6].FText := FieldByName('T_ActMan').AsString; nData[7].FText := DateTime2Str(FieldByName('T_ActDate').AsDateTime); with nData[8] do begin FText := ''; FCtrls := TList.Create; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '查看'; Width := 35; Height := 18; OnClick := OnBtnClick3; Tag := FPainter2.DataCount; end; end; FPainter2.AddData(nData); Next; end; end; FDoneLoaded := True; finally FDM.ReleaseDataSet(nDS); end; end; //Desc: 页面切换 procedure TfFrameProductReturn.wPageChange(Sender: TObject); begin if wPage.ActivePage = Sheet2 then LoadProductReturnDone; end; //Desc: 调整未确认单 procedure TfFrameProductReturn.OnBtnClick2(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; if Sender = FPainter.Data[nTag][8].FCtrls[0] then begin if ShowProductReturnAdjust(FPainter.Data[nTag][2].FText) then LoadProductReturn; end else //调整 if Sender = FPainter.Data[nTag][8].FCtrls[1] then begin if ShowReturnConfirmForm(FPainter.Data[nTag][2].FText) then LoadProductReturn; //确认 end; end; procedure TfFrameProductReturn.OnBtnClick(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; if Sender = FPainter.Data[nTag][8].FCtrls[0] then begin ShowProductReturnView(FPainter.Data[nTag][2].FText); end; end; procedure TfFrameProductReturn.OnBtnClick3(Sender: TObject); var nTag: Integer; begin nTag := TComponent(Sender).Tag; if Sender = FPainter2.Data[nTag][8].FCtrls[0] then begin ShowProductReturnView(FPainter2.Data[nTag][1].FText); end; end; initialization gControlManager.RegCtrl(TfFrameProductReturn, TfFrameProductReturn.FrameID); end.
unit TLibDemo_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // PASTLWTR : 1.2 // File generated on 10/8/2002 1:05:38 AM from Type Library described below. // ************************************************************************ // // Type Lib: E:\books\md7code\12\TLibDemo\Tlibdemo.tlb (1) // LIBID: {89855B41-8EFE-11D0-98D0-444553540000} // LCID: 0 // Helpfile: // HelpString: TLibDemo Library // DepndLst: // (1) v1.0 stdole, (C:\WINDOWS\System32\stdole32.tlb) // (2) v2.0 StdType, (C:\WINDOWS\System32\OLEPRO32.DLL) // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} interface uses Windows, ActiveX, Classes, Graphics, StdVCL, Variants; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions TLibDemoMajorVersion = 1; TLibDemoMinorVersion = 0; LIBID_TLibDemo: TGUID = '{89855B41-8EFE-11D0-98D0-444553540000}'; IID_IFirstServer: TGUID = '{89855B42-8EFE-11D0-98D0-444553540000}'; CLASS_FirstServer: TGUID = '{89855B43-8EFE-11D0-98D0-444553540000}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IFirstServer = interface; IFirstServerDisp = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// FirstServer = IFirstServer; // *********************************************************************// // Interface: IFirstServer // Flags: (4432) Hidden Dual OleAutomation Dispatchable // GUID: {89855B42-8EFE-11D0-98D0-444553540000} // *********************************************************************// IFirstServer = interface(IDispatch) ['{89855B42-8EFE-11D0-98D0-444553540000}'] procedure ChangeColor; safecall; function Get_Value: Integer; safecall; procedure Set_Value(Value: Integer); safecall; property Value: Integer read Get_Value write Set_Value; end; // *********************************************************************// // DispIntf: IFirstServerDisp // Flags: (4432) Hidden Dual OleAutomation Dispatchable // GUID: {89855B42-8EFE-11D0-98D0-444553540000} // *********************************************************************// IFirstServerDisp = dispinterface ['{89855B42-8EFE-11D0-98D0-444553540000}'] procedure ChangeColor; dispid 1; property Value: Integer dispid 2; end; // *********************************************************************// // The Class CoFirstServer provides a Create and CreateRemote method to // create instances of the default interface IFirstServer exposed by // the CoClass FirstServer. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoFirstServer = class class function Create: IFirstServer; class function CreateRemote(const MachineName: string): IFirstServer; end; implementation uses ComObj; class function CoFirstServer.Create: IFirstServer; begin Result := CreateComObject(CLASS_FirstServer) as IFirstServer; end; class function CoFirstServer.CreateRemote(const MachineName: string): IFirstServer; begin Result := CreateRemoteComObject(MachineName, CLASS_FirstServer) as IFirstServer; end; end.
// ********************************************************************** // // Copyright (c) 2001 MT Tools. // // All Rights Reserved // // MT_DORB is based in part on the product DORB, // written by Shadrin Victor // // See Readme.txt for contact information // // ********************************************************************** unit iior_int; interface uses orbtypes,Classes,addr_int,code_int,SysUtils; type IIORProfile = interface ['{02F45D6A-203A-11d4-9CCB-204C4F4F5020}'] function address(): IAddress; function clone(): IIORProfile; procedure encode(const enc: IEncoder); function id(): ProfileId; function encode_id(): ProfileId; function objkeylen: _ulong; function objkey(var len: _ulong): Identifier; procedure set_objectkey(const val: Identifier; const len : _ulong); procedure print(s: TStream); function reachable(): boolean; function compare(const p: IIORProfile): boolean; function get_components(): IInterface; end; IIORProfileDecoder = interface ['{02F45D6B-203A-11d4-9CCB-204C4F4F5020}'] function has_id(id: ProfileID): Boolean; function decode(const dec: IDecoder;pid: ProfileID;len : _ulong): IIORProfile; end; {** Describes Interoperable Object Reference **} IIOR = interface ['{02F45D6C-203A-11d4-9CCB-204C4F4F5020}'] procedure clean(); procedure add_profile(const prof : IIORProfile); function decode(const dec: IDecoder): Boolean; procedure encode(const enc: IEncoder); function from_string(const Value: AnsiString): Boolean; function get_profile(id: ProfileID = TAG_ANY; find_unreachable: boolean = false; prev: IIORProfile = nil): IIORProfile; function address(id: ProfileID = TAG_ANY; find_unreachable: boolean = false; prev: IIORProfile = nil): IAddress; function active_profile(var AIndex: _ulong): IIORProfile; overload; procedure active_profile(const AProfile: IIORProfile); overload; function addressing_disposition(): AddressingDisposition; overload; procedure addressing_disposition(const AddrDisp: AddressingDisposition); overload; function objid: AnsiString; procedure print(s : TStream); function profile(ind: _ulong): IIORProfile; procedure set_objectkey(const key: AnsiString; const len: _ulong); procedure set_objectid(const oid: AnsiString); function size: integer; function stringify: AnsiString; end; IUnknownProfile = interface(IIORProfile) ['{1070DE2C-CB15-4D70-830C-AE958F37FD38}'] function tagdata: OctetSeq; end; implementation end.
program probabilityTest(output); var n, i : Integer; sum, accum : Real; begin write('N: '); read(n); sum := 0.0; accum := 2; for i := 0 to n do begin accum := accum * 2; sum := sum + (i / accum); end; writeln('Sum: ', sum:4:5); end.
(** This module contains a class to represent a configuation for for the applications options. @Version 1.0 @Author David Hoyle @Date 07 Apr 2016 **) Unit DGHIDEHelphelperConfigForm; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, CheckLst, ExtCtrls, DGHIDEHelphelperOptionsFrame; Type (** This class represents a form for editing the applications options. **) TfrmDGHIDEHelphelperConfig = Class(TForm) btnOK: TBitBtn; btnCancel: TBitBtn; pnlFrame: TPanel; procedure FormCreate(Sender: TObject); Strict Private Private {Private declarations} FFrame : TfmIDEHelpHelperOptions; Public {Public declarations} Class Function Execute(slSearchURLs, slPermanentURLs : TStringList; var iSearchURL : Integer) : Boolean; End; Implementation {$IFDEF CodeSiteLogging} Uses CodeSiteLogging; {$ENDIF} {$R *.dfm} { TfrmDGHIDEHelphelperConfig } (** This is the forms main interface method for invoking the dialogue. The method will return true if the dialogue was confirmed and the data has changed. @precon The string lists must be valid instances. @postcon The pass variables are updated in the dialogue is confirmed and true is returned else they are not modified and false is returned. @param slSearchURLs as a TStringList @param slPermanentURLs as a TStringList @param iSearchURL as an Integer as a reference @return a Boolean **) Class Function TfrmDGHIDEHelphelperConfig.Execute(slSearchURLs, slPermanentURLs : TStringList; var iSearchURL : Integer): Boolean; Begin Result := False; With TfrmDGHIDEHelphelperConfig.Create(Nil) Do Try FFrame.InitialiseFrame(slSearchURLs, slPermanentURLs, iSearchURL); If ShowModal = mrOk Then Begin FFrame.FinaliseFrame(slSearchURLs, slPermanentURLs, iSearchURL); Result := True; End; Finally Free; End; End; (** This is an OnFormCreate Event Handler for the TfrmDGHIDEHelpHelperConfig class. @precon None. @postcon Initialises the FClickIndex variable to -1. @param Sender as a TObject **) Procedure TfrmDGHIDEHelphelperConfig.FormCreate(Sender: TObject); Begin FFrame := TfmIDEHelpHelperOptions.Create(Self); FFrame.Parent := pnlFrame; FFrame.Align := alClient; End; End.
unit uFiredac; interface uses FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.FMXUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite, FireDAC.Dapt, FireDAC.Phys.FBDef, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.Comp.DataSet {$IFDEF ANDROID} ,System.IOUtils {$ENDIF} ; type TFiredac = class private FDConnection: TFDConnection; FQuery: TFDQuery; function FBEstaAtivo:Boolean; public constructor Create; destructor Destroy; override; class function New: TFiredac; function Active (aValue: Boolean): TFiredac; function AddParan(aParem: String; aValue: Variant): TFiredac; function DataSet: TFDDataSet; function ExceSQL: TFiredac; function Open: TFiredac; function SQL(aValue: String) : TFiredac; function SQLClear: TFiredac; end; implementation uses System.SysUtils, Vcl.Forms, Winapi.Windows, System.Classes, Tlhelp32; { TModelComponnentsConeectionFiredac } function TFiredac.Active(aValue: Boolean): TFiredac; begin Result := Self; fQuery.Active := aValue; end; function TFiredac.AddParan(aParem: String; aValue: Variant): TFiredac; begin Result := Self; FQuery.ParamByName(aParem).Value := aValue; end; constructor TFiredac.Create; begin if not FileExists(ExtractFileDir(application.ExeName) + '\Config.ini') then raise Exception.Create('Não foi possivel localizar o arquivo config.ini'); if not FBEstaAtivo then raise Exception.Create('o serviço "fbserver" deve estar desativado ou não esta intalado'); try FDConnection := TFDConnection.Create(Nil); FQuery := TFDQuery.Create(Nil); FQuery.Connection := FDConnection; FDConnection.LoginPrompt := False; FDConnection.Params.Clear; FDConnection.Params.Add('LockingMode=Normal'); FDConnection.Params.LoadFromFile(ExtractFileDir(application.ExeName) + '\Config.ini'); FDConnection.Connected := True; except on E: Exception do raise Exception.Create('Não foi possivel conectar ao banco de dados' + #13 + E.Message ); end; end; function TFiredac.DataSet: TFDDataSet; begin Result := fQuery; end; destructor TFiredac.Destroy; begin FQuery.DisposeOf; FDConnection.DisposeOf; inherited; end; function TFiredac.ExceSQL: TFiredac; begin Result := Self; FQuery.ExecSQL; end; function TFiredac.FBEstaAtivo: Boolean; const PROCESS_TERMINATE = $0001; var Co: BOOL; FS: THandle; FP: TProcessEntry32; s: string; begin FS := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FP.dwSize := Sizeof(FP); Co := Process32First(FS, FP); while integer(Co) <> 0 do begin s := s + FP.szExeFile + #13; Co := Process32Next(FS, FP); end; CloseHandle(FS); if pos('fbserver', s) > 0 then result := true else result := false; end; class function TFiredac.New: TFiredac; begin Result := Self.Create; end; function TFiredac.Open: TFiredac; begin Result := Self; FQuery.Open; end; function TFiredac.SQL(aValue: String): TFiredac; begin Result := self; FQuery.SQL.Add(aValue); end; function TFiredac.SQLClear: TFiredac; begin Result := self; FQuery.SQL.Clear; end; end.
// // icop 的数据压缩单元 // 主要摘自 Zlib 目录下相应单元,有修改 // unit iocp_zlib; interface uses Classes, SysUtils, DateUtils, ZLibEx, ZLibExApi, ZLibExGZ; type TZipLevel = ( // = TZCompressionLevel zcNone, zcFastest, zcDefault, zcMax, zcLevel1, zcLevel2, zcLevel3, zcLevel4, zcLevel5, zcLevel6, zcLevel7, zcLevel8, zcLevel9 ); // Zip:尝试压缩一段内存到 outBuffer function TryZCompress(const inBuffer: Pointer; inSize: Integer; const outBuffer: Pointer; var outSize: Integer; Level: TZipLevel): Boolean; // Zip:压缩一段内存到 outBuffer procedure ZCompress(const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; Level: TZipLevel); // Zip:解压一段内存到 outBuffer(估算长度 outEstimate) procedure ZDecompress(const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; outEstimate: Integer = 0); // Zip:压缩流 procedure ZCompressStream(inStream, outStream: TStream; level: TZipLevel = zcDefault); // Zip:解压流 procedure ZDecompressStream(inStream, outStream: TStream); // =============================================================== // GZip:压缩一段内存到 outBuffer procedure GZCompress(const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; Level: TZipLevel); // GZip:压缩文件、流 procedure GZCompressFile(const SourceFileName, TargetFileName: String); procedure GZCompressStream(inStream, outStream: TStream; const FileName: String = ''); // GZip: 解压流,返回文件名称 procedure GZDecompressStream(inStream, outStream: TStream; var FileName: String); implementation function ZCompressCheck(code: Integer): Integer; begin result := code; if code < 0 then raise Exception.Create('压缩异常'); end; function ZDecompressCheck(code: Integer; raiseBufferError: Boolean = True): Integer; begin result := code; if code < 0 then if (code <> Z_BUF_ERROR) or raiseBufferError then raise Exception.Create('解压异常'); end; procedure ZInternalCompress(var zstream: TZStreamRec; const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer); const delta = 256; var zresult: Integer; begin outSize := ((inSize + (inSize div 10) + 12) + 255) and not 255; outBuffer := Nil; try try zstream.next_in := inBuffer; zstream.avail_in := inSize; repeat ReallocMem(outBuffer, outSize); zstream.next_out := PByte(NativeUInt(outBuffer) + zstream.total_out); zstream.avail_out := NativeUInt(outSize) - zstream.total_out; zresult := ZCompressCheck(deflate(zstream, ZFlushes[zfNoFlush])); Inc(outSize, delta); until (zresult = Z_STREAM_END) or (zstream.avail_in = 0); while zresult <> Z_STREAM_END do begin ReallocMem(outBuffer, outSize); zstream.next_out := PByte(NativeUInt(outBuffer) + zstream.total_out); zstream.avail_out := NativeUInt(outSize) - zstream.total_out; zresult := ZCompressCheck(deflate(zstream, ZFlushes[zfFinish])); Inc(outSize, delta); end; finally ZCompressCheck(deflateEnd(zstream)); end; ReallocMem(outBuffer, zstream.total_out); outSize := zstream.total_out; except FreeMem(outBuffer); raise; end; end; procedure ZInternalDecompress(zstream: TZStreamRec; const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; outEstimate: Integer); var zresult: Integer; delta : Integer; begin delta := (inSize + 255) and not 255; if outEstimate = 0 then // 估计数 outSize := delta else outSize := outEstimate; outBuffer := Nil; try try zresult := Z_OK; zstream.avail_in := inSize; zstream.next_in := inBuffer; while (zresult <> Z_STREAM_END) and (zstream.avail_in > 0) do repeat ReallocMem(outBuffer, outSize); zstream.next_out := PByte(NativeUInt(outBuffer) + zstream.total_out); zstream.avail_out := NativeUInt(outSize) - zstream.total_out; zresult := ZDecompressCheck(inflate(zstream, ZFlushes[zfNoFlush]), False); Inc(outSize, delta); until (zresult = Z_STREAM_END) or (zstream.avail_out > 0); finally ZDecompressCheck(inflateEnd(zstream)); end; ReallocMem(outBuffer, zstream.total_out); outSize := zstream.total_out; except if Assigned(outBuffer) then FreeMem(outBuffer); raise; end; end; procedure ZInternalCompressStream(zStream: TZStreamRec; inStream, outStream: TStream); const bufferSize = 32768; var zresult : Integer; inBuffer : Array [0..bufferSize - 1] of Byte; outBuffer: Array [0..bufferSize - 1] of Byte; outSize : Integer; begin zresult := Z_STREAM_END; zstream.avail_in := inStream.Read(inBuffer, bufferSize); while zstream.avail_in > 0 do begin zstream.next_in := @inBuffer; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := ZCompressCheck(deflate(zStream, ZFlushes[zfNoFlush])); outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zresult = Z_STREAM_END) or (zstream.avail_in = 0); zstream.avail_in := inStream.Read(inBuffer, bufferSize); end; while zresult <> Z_STREAM_END do begin zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := ZCompressCheck(deflate(zstream, ZFlushes[zfFinish])); outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); end; ZCompressCheck(deflateEnd(zstream)); end; procedure ZInternalDecompressStream(zstream: TZStreamRec; inStream, outStream: TStream); const bufferSize = 32768; var zresult : Integer; inBuffer : Array [0..bufferSize-1] of Byte; outBuffer: Array [0..bufferSize-1] of Byte; outSize : Integer; begin try zresult := Z_OK; zstream.avail_in := inStream.Read(inBuffer, bufferSize); while (zresult <> Z_STREAM_END) and (zstream.avail_in > 0) do begin zstream.next_in := @inBuffer; repeat zstream.next_out := @outBuffer; zstream.avail_out := bufferSize; zresult := ZDecompressCheck(inflate(zstream, ZFlushes[zfNoFlush]), False); outSize := bufferSize - zstream.avail_out; outStream.Write(outBuffer, outSize); until (zresult = Z_STREAM_END) or (zstream.avail_out > 0); if zstream.avail_in > 0 then begin inStream.Position := inStream.Position - zstream.avail_in; end; if zresult <> Z_STREAM_END then begin zstream.avail_in := inStream.Read(inBuffer, bufferSize); end; end; finally ZDecompressCheck(inflateEnd(zstream)); end; end; function TryZCompress(const inBuffer: Pointer; inSize: Integer; const outBuffer: Pointer; var outSize: Integer; Level: TZipLevel): Boolean; var TempBuffer: Pointer; ZipSize: Integer; begin // 尝试压缩一段内存 inBuffer 到 outBuffer // outSize: 传入的内存长度,压缩后改为压缩数据长度 TempBuffer := nil; try ZCompress(inBuffer, inSize, TempBuffer, ZipSize, Level); if (ZipSize < outSize) then begin // 压缩后数据变少 System.Move(TempBuffer^, outBuffer^, ZipSize); outSize := ZipSize; Result := True; end else begin // 放弃压缩 outSize := inSize; System.Move(inBuffer^, outBuffer^, inSize); Result := False; end; finally if Assigned(TempBuffer) then FreeMem(TempBuffer); end; end; procedure ZCompress(const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; Level: TZipLevel); var zStream: TZStreamRec; begin FillChar(zStream, SizeOf(TZStreamRec), 0); ZCompressCheck(deflateInit_(zStream, ZLevels[TZCompressionLevel(level)], ZLIB_VERSION, SizeOf(TZStreamRec))); ZInternalCompress(zStream, inBuffer, inSize, outBuffer, outSize); end; procedure ZDecompress(const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; outEstimate: Integer = 0); var zStream: TZStreamRec; begin FillChar(zStream, SizeOf(TZStreamRec), 0); ZDecompressCheck(inflateInit_(zStream, ZLIB_VERSION, SizeOf(TZStreamRec))); ZInternalDecompress(zStream, inBuffer, inSize, outBuffer, outSize, outEstimate); end; procedure ZCompressStream(inStream, outStream: TStream; level: TZipLevel); var zStream: TZStreamRec; begin FillChar(zStream, SizeOf(TZStreamRec), 0); ZCompressCheck(deflateInit_(zStream, ZLevels[TZCompressionLevel(level)], ZLIB_VERSION, SizeOf(TZStreamRec))); ZInternalCompressStream(zStream, inStream, outStream); end; procedure ZDecompressStream(inStream, outStream: TStream); var zStream: TZStreamRec; begin FillChar(zStream, SizeOf(TZStreamRec), 0); ZDecompressCheck(inflateInit_(zStream, ZLIB_VERSION, SizeOf(TZStreamRec))); ZInternalDecompressStream(zStream, inStream, outStream); end; procedure GZCompress(const inBuffer: Pointer; inSize: Integer; out outBuffer: Pointer; out outSize: Integer; Level: TZipLevel); var header : TGZHeader; trailer: TGZTrailer; oBuffer: Pointer; zStream: TZStreamRec; begin // GZip 压缩一个数据包 // (压缩后的空间可能变大) // 1. 准备头 // FillChar(header, SizeOf(TGZHeader), 0); // 优化删除 header.Id1 := $1F; header.Id2 := $8B; header.Method := Z_DEFLATED; header.ExtraFlags := GZ_EXTRA_DEFAULT; header.Flags := 0; header.OS := 0; header.Time := 0; // 2. 计算 CRC32 // FillChar(trailer, SizeOf(TGZTrailer), 0); // 优化删除 trailer.Crc := crc32(0, inBuffer^, inSize); trailer.Size := inSize; // 3. 压缩 inBuffer FillChar(zStream, SizeOf(TZStreamRec), 0); // .. 初始化 ZCompressCheck(deflateInit2_(zStream, ZLevels[TZCompressionLevel(level)], Z_DEFLATED, GZ_ZLIB_WINDOWBITS, GZ_ZLIB_MEMLEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, SizeOf(TZStreamRec))); // .. 压缩 ZInternalCompress(zStream, inBuffer, inSize, oBuffer, outSize); // 4. 结果:头部 + oBuffer + 尾 try GetMem(outBuffer, outSize + SizeOf(TGZHeader) + SizeOf(TGZTrailer)); System.Move(header, outBuffer^, SizeOf(TGZHeader)); System.Move(oBuffer^, Pointer(LongWord(outBuffer) + SizeOf(TGZHeader))^, outSize); System.Move(trailer, Pointer(LongWord(outBuffer) + SizeOf(TGZHeader) + LongWord(outSize))^, SizeOf(TGZTrailer)); Inc(outSize, SizeOf(TGZHeader) + SizeOf(TGZTrailer)); finally FreeMem(oBuffer); end; end; procedure GZCompressFile(const SourceFileName, TargetFileName: String); var Source, Target: TStream; begin Source := TFileStream.Create(SourceFileName, fmOpenRead or fmShareDenyWrite); Target := TFileStream.Create(TargetFileName, fmCreate); try GZCompressStream(Source, Target); finally if Assigned(Source) then Source.Free; if Assigned(Target) then Target.Free; end; end; procedure GZCompressStream(inStream, outStream: TStream; const FileName: String); const bufferSize = 32768; var zStream : TZStreamRec; header : TGZHeader; trailer : TGZTrailer; buffer : Array [0..bufferSize-1] of Byte; count : Integer; position : Int64; nilString: String; begin // FillChar(header, SizeOf(TGZHeader), 0); // 优化删除 header.Id1 := $1F; header.Id2 := $8B; header.Method := Z_DEFLATED; header.ExtraFlags := GZ_EXTRA_DEFAULT; if (Length(FileName) > 0) then header.Flags := 0 or GZ_FILENAME else header.Flags := 0; header.OS := 0; header.Time := 0; // DateTimeToUnix(Now); // FillChar(trailer, SizeOf(TGZTrailer), 0); // 优化删除 trailer.Crc := 0; position := inStream.Position; while inStream.Position < inStream.Size do begin count := inStream.Read(buffer[0],bufferSize); trailer.Crc := Crc32(trailer.Crc, buffer[0], count); end; inStream.Position := position; trailer.Size := inStream.Size - inStream.Position; // mark outStream.Write(header, SizeOf(TGZHeader)); if Length(filename) > 0 then begin nilString := fileName + #$00; outStream.Write(nilString[1], Length(nilString)); end; // .. 压缩 FillChar(zStream, SizeOf(TZStreamRec), 0); ZCompressCheck(deflateInit2_(zStream, ZLevels[TZCompressionLevel(zcDefault)], Z_DEFLATED, GZ_ZLIB_WINDOWBITS, GZ_ZLIB_MEMLEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, SizeOf(TZStreamRec))); ZInternalCompressStream(zStream, inStream, outStream); outStream.Write(trailer, SizeOf(TGZTrailer)); end; procedure GZDecompressStream(inStream, outStream: TStream; var FileName: String); const bufferSize = 32768; var header : TGZHeader; trailer : TGZTrailer; zStream : TZStreamRec; buffer : Array [0..bufferSize-1] of Byte; count : Integer; position : Int64; // delphi 7 不能用 endPosition: Int64; size : Integer; crc : Longint; c : AnsiChar; begin if inStream.Read(header,SizeOf(TGZHeader)) <> SizeOf(TGZHeader) then raise Exception.Create('解压异常'); if (header.Id1 <> $1F) or (header.Id2 <> $8B) or (header.Method <> Z_DEFLATED) or ((header.Flags and GZ_RESERVED) <> 0) then raise Exception.Create('解压异常'); if (header.Flags and GZ_EXTRA_FIELD) <> 0 then begin if inStream.Read(size,SizeOf(Word)) <> SizeOf(Word) then raise Exception.Create('解压异常'); inStream.Position := inStream.Position + size; end; fileName := ''; if (header.Flags and GZ_FILENAME) <> 0 then begin c := ' '; while (inStream.Position < inStream.Size) and (c <> #$00) do begin inStream.Read(c,1); if c <> #$00 then fileName := fileName + c; end; end; if (header.Flags and GZ_HEADER_CRC) <> 0 then begin // todo: validate header crc inStream.Position := inStream.Position + SizeOf(Word); end; if inStream.Position >= inStream.Size then raise Exception.Create('解压异常'); position := outStream.Position; // 解压流 FillChar(zstream, SizeOf(TZStreamRec), 0); ZDecompressCheck(inflateInit2(zStream, GZ_ZLIB_WINDOWBITS)); ZInternalDecompressStream(zStream, inStream, outStream); // ... endPosition := outStream.Position; if inStream.Read(trailer,SizeOf(TGZTrailer)) <> SizeOf(TGZTrailer) then raise Exception.Create('解压异常');; crc := 0; outStream.Position := position; while outStream.Position < endPosition do begin size := bufferSize; if size > (endPosition - outStream.Position) then begin size := endPosition - outStream.Position; end; count := outStream.Read(buffer[0], size); crc := Crc32(crc, buffer[0], count); end; if (trailer.Crc <> crc) or (trailer.Size <> Cardinal(endPosition - position)) then raise Exception.Create('解压异常');; end; end.