text
stringlengths
14
6.51M
program someName(input, output); var n, result : integer; procedure factorial(k : integer; var answer : integer); begin if k = 0 then answer := 1 else begin factorial(k - 1, answer); answer := answer * k end end; { factorial } begin writeString('Value for n: '); readInteger(n); factorial(n, result); writeln; end.
unit TImageTextButtonData; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, FMX.Layouts, FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects, System.Types, StrUtils, FMX.Dialogs, misc; type TImageTextButton = class(TButton) private { Private declarations } procedure _onClick(Sender: TObject); protected { Protected declarations } public img: TImage; lbl: Tlabel; constructor Create(AOwner: TComponent); override; procedure LoadImage(ResourceName: AnsiString); published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TImageTextButton]); end; { TImageTextButtonData } procedure TImageTextButton._onClick(Sender: TObject); begin OnClick(Sender); end; procedure TImageTextButton.LoadImage(ResourceName: AnsiString); var stream: TResourceStream; begin stream := TResourceStream.Create(HInstance, ResourceName, RT_RCDATA); try img.Bitmap.LoadFromStream(stream); finally stream.Free; end; end; constructor TImageTextButton.Create(AOwner: TComponent); begin inherited Create(AOwner); img := TImage.Create(self); img.Parent := self; img.Visible := true; img.Align := TAlignLayout.Left; img.Width := 64; img.HitTest := false; img.OnClick := _onClick; lbl := Tlabel.Create(self); lbl.Parent := self; lbl.Visible := true; lbl.Align := TAlignLayout.Client; lbl.HitTest := true; lbl.OnClick := _onClick; end; end.
Program trees; Type root = ^tree; tree = Record data : integer; left : root; right: root; End; Type node = ^list; list = Record data : integer; next : node; End; Type fnReturn = ^returnBlok; returnBlok = Record val : integer; child: node; next: fnReturn; End; Var head, element : root; //var queue : node; //* For list {in order to help in the tree traversal process} Procedure nodeMakerV2 (Var el: node; val : integer); Begin new(el); el^.data:= val; el^.next := Nil; End; Function listLengthCounter( start : node): integer; Var walker: node; lengthCount: integer; Begin walker := start; If (walker = Nil) Then listLengthCounter := 0 Else If (walker^.next =Nil )Then listLengthCounter := 1 Else Begin lengthCount := 1; While (walker^.next <> Nil) Do Begin walker := walker^.next; lengthCount := lengthCount+1; End; listLengthCounter := lengthCount; End; End; Procedure printList(head: node); Var tmp: node; Begin If (head = Nil ) Then writeln('List empty') Else Begin tmp := head; While (tmp <> Nil ) Do Begin writeln('data is equal to ', tmp^.data); tmp := tmp^.next; End; End; End; Function shift(Var head: node): fnReturn; Begin If (head <> Nil) Then Begin new(shift); shift^.child := head; head := head^.next; shift^.child^.next := Nil; shift^.val := listLengthCounter(head); End; End; Function push(Var head : node; val : integer): fnReturn; Var tmp, el : node; Begin nodeMakerV2(el, val); If (head = Nil) Then head :=el Else Begin tmp := head; While (tmp^.next <> Nil) Do tmp := tmp^.next; tmp^.next:= el; End; new(push); push^.child := Nil; push^.val := listLengthCounter(head); End; //* For Trees Procedure treeMaker(Var root : root); Begin new(root); writeln('enter your data'); writeln(root^.data); root^.left := Nil; root^.right := Nil; End; Procedure treeMakerV2(Var root : root; value: integer); Begin new(root); root^.data := value; root^.left := Nil; root^.right := Nil; End; Function max(x,y: integer):integer; Begin if(x < y) then max:=y else max:=x; end; Function treeLength(root : root): integer; Begin If (root = Nil ) Then treeLength := 0 Else If ((root^.left = Nil ) And (root^.right = Nil )) Then treeLength := 1 Else treeLength := 1 +max( treeLength(root^.left) , treeLength(root^.right)); End; //* Tree traversal. Function inserter(Var root , son: root) : root; Begin If (root = Nil) Then Begin root := son; new(inserter); inserter := root; End Else Begin If (root^.data > son^.data) Then Begin If (root^.left = Nil ) Then root^.left := son Else inserter(root^.left, son); End; If (root^.data < son^.data) Then Begin If (root^.right = Nil) Then root^.right := son Else inserter(root^.right, son); End; End; new(inserter); inserter := root; End; Function inserterV2(Var root : root; value : integer) : root; Var son : root; Begin If (root = Nil) Then Begin treeMakerV2(root, value); new(inserterV2); inserterV2 := root; End Else Begin If (root^.data > value) Then Begin If (root^.left = Nil ) Then Begin treeMakerV2(son,value); root^.left := son; End Else inserterV2(root^.left, value); End; If (root^.data < value) Then Begin If (root^.right = Nil) Then Begin treeMakerV2(son, value); root^.right := son; End Else inserterV2(root^.right, value); End; End; new(inserterV2); inserterV2 := root; End; Procedure displayer(head : root); // depth fisrt search / preOrder traversal principle Begin if(head = nil) then writeln('empty tree') else Begin writeln('the data inside of this node is equal to ', head^.data); writeln('on the left'); displayer(head^.left); writeln('on the right'); displayer(head^.right); end; end; function searcher(head : root ; query : integer):root; var tmp: root; begin if(head = nil) then searcher := nil else if (head^.data = query) then searcher:= head else begin if(query < head^.data) then searcher:= searcher(head^.left , query); if(query > head^.data) then searcher:= searcher(head^.right, query); end; end; function breadth_vs(var head : root) : node; // breadth first search traversal principle var queue, current : node; branch : root; Begin queue:=nil; current:=nil; breadth_vs:=nil; if(head = nil ) then writeln('empty tree') else begin push(queue, head^.data); while (listLengthCounter(queue) > 0) do begin current:= shift(queue)^.child; push(breadth_vs,current^.data ); branch:= searcher(head, current^.data); if(branch^.left <> nil ) then push(queue, branch^.left^.data); if(branch^.right <> nil ) then push(queue, branch^.right^.data); end; end; end; //* Depth first search. Procedure dfs_PreOrder(head : root;var store : node); //visit the node then traverse the left side of it, then righ one. Begin if(head = nil) then writeln('empty tree') else Begin push(store, head^.data ); if(head^.left <> nil) then dfs_PreOrder(head^.left, store); if(head^.right <> nil)then dfs_PreOrder(head^.right,store); end; end; Procedure dfs_inOnder(head : root; var store : node); // traverse the left side of a node, then visit the node before going through the right side. Begin if(head = nil) then writeln('empty tree') else Begin if(head^.left <> nil) then dfs_PreOrder(head^.left, store); push(store, head^.data ); if(head^.right <> nil)then dfs_PreOrder(head^.right, store); end; end; Procedure dfs_postOnder(head : root; var store: node); // traverse the left side of a node, then the right side, and finaly the node itself. Begin if(head = nil) then writeln('empty tree') else Begin if(head^.left <> nil) then dfs_PreOrder(head^.left, store); if(head^.right <> nil)then dfs_PreOrder(head^.right, store); push(store, head^.data ); end; end; Procedure visulizeTree(tree : root; choice : integer); var resault : node; Begin if(choice = 1) then Begin writeln('this is the breadth first search, // basicly we visit all the sibling nodes befor moving forwards'); writeln('Note: sibling nodes is a group of nodes that are located in the same row or tree level.'); resault:= breadth_vs(tree); printList(resault); end; if(choice = 2) then begin writeln('this is the depth first search traversal pattern ,Option: Pre Order'); writeln('basicly you visit a node then all the left side of it ,before going to the right side;'); dfs_PreOrder(tree, resault); printList(resault); end; if(choice = 3) then begin writeln('this is the depth first search traversal pattern, Option: In Order'); writeln('basicly you visit the left side of a node ,then the node itself, then the right side of it '); dfs_inOnder(tree, resault); printList(resault); end; if(choice = 4) then begin writeln('this is the depth first search traversal pattern, Option: Post Order'); writeln('Basicly you visit the left side of a node, then the right side before the node itself'); dfs_postOnder(tree, resault); printList(resault); end; end; Procedure filler(var tree : root; nodeCount : integer); var counter, val : integer; begin for counter:=1 to nodeCount do begin writeln('enter your data {integer type}'); readln(val); inserterV2(tree, val); end; end; //* Main program // begin writeln('filling the tree'); inserterV2(head,10); inserterV2(head,6); inserterV2(head,3); inserterV2(head,8); inserterV2(head,15); inserterV2(head,20); //* Run any function you want visulizeTree(head, 2); displayer(head); readln; End.
unit MessageBox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, FramedButton, InternationalizerComponent; type TMsgBoxFrm = class(TForm) BorderPanel: TPanel; Panel2: TPanel; CaptionPanel: TPanel; TextPanel: TPanel; Text: TLabel; BtnsPanel: TPanel; bOK: TFramedButton; bCancel: TFramedButton; Panel1: TPanel; IconNotebook: TNotebook; Image1: TImage; Image2: TImage; Image3: TImage; InternationalizerComponent1: TInternationalizerComponent; procedure FormShow(Sender: TObject); procedure bOKClick(Sender: TObject); procedure bCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; function ShowMsgBox( Title, Body : string; Icon : integer; ShowOk, ShowCancel : boolean ) : TModalResult; function ShowMsgBoxYN(const Title, Body : string; const mIcon: integer; const ShowYES, ShowNO: boolean): TModalResult; implementation {$R *.DFM} uses Literals; procedure TMsgBoxFrm.FormShow(Sender: TObject); begin TextPanel.Height := Text.Height; Height := TextPanel.Height + CaptionPanel.Height + TextPanel.Top + BtnsPanel.Height + 2*BorderPanel.BevelWidth + 25; end; function ShowMsgBox( Title, Body : string; Icon : integer; ShowOk, ShowCancel : boolean ) : TModalResult; var Box : TMsgBoxFrm; begin Box := TMsgBoxFrm.Create( nil ); try try Box.CaptionPanel.Caption := Title; Box.Text.Caption := Body; Box.IconNotebook.PageIndex := Icon; Box.bOK.Visible := ShowOK; Box.bCancel.Visible := ShowCancel; result := Box.ShowModal; except result := mrCancel; end; finally Box.Free; end; end; function ShowMsgBoxYN(const Title, Body : string; const mIcon: integer; const ShowYES, ShowNO: boolean): TModalResult; var Box : TMsgBoxFrm; begin Box := TMsgBoxFrm.Create( nil ); try with Box do try CaptionPanel.Caption := Title; Text.Caption := Body; IconNotebook.PageIndex := mIcon; bOK.Visible := ShowYES; bOK.Text := GetLiteral('LiteralYES'); bCancel.Visible := ShowNo; bCancel.Text := GetLiteral('LiteralNo'); result := ShowModal; except result := mrCancel; end; finally Box.Free; end; end; procedure TMsgBoxFrm.bOKClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TMsgBoxFrm.bCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clGZip; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} SysUtils, Windows, Classes, {$ELSE} System.SysUtils, Winapi.Windows, System.Classes, {$ENDIF} clZLibStreams, clZLibBase, clWUtils, clUtils; type TclGZip = class(TComponent) private FBatchSize: Integer; FOnProgress: TclProgressEvent; FFlags: Integer; FCompressionLevel: TclCompressionLevel; FStrategy: TclCompressionStrategy; procedure CopyFrom(ASource, ADestination: TStream); protected procedure DoProgress(ABytesProceed, ATotalBytes: Int64); dynamic; public constructor Create(AOwner: TComponent); override; procedure Compress(const AFileSource, AFileDestination: string); overload; procedure Uncompress(const AFileSource, AFileDestination: string); overload; procedure Compress(ASource, ADestination: TStream); overload; procedure Uncompress(ASource, ADestination: TStream); overload; published property BatchSize: Integer read FBatchSize write FBatchSize default 8192; property CompressionLevel: TclCompressionLevel read FCompressionLevel write FCompressionLevel default clDefault; property Strategy: TclCompressionStrategy read FStrategy write FStrategy default csDefault; property Flags: Integer read FFlags write FFlags default 0; property OnProgress: TclProgressEvent read FOnProgress write FOnProgress; end; implementation procedure TclGZip.Uncompress(ASource, ADestination: TStream); var compressor: TStream; begin compressor := TclGZipInflateStream.Create(ADestination); try CopyFrom(ASource, compressor); finally compressor.Free(); end; end; procedure TclGZip.Uncompress(const AFileSource, AFileDestination: string); var inFile, outFile: TStream; begin inFile := nil; outFile := nil; try inFile := TFileStream.Create(AFileSource, fmOpenRead or fmShareDenyWrite); outFile := TFileStream.Create(AFileDestination, fmCreate); Uncompress(inFile, outFile); finally outFile.Free(); inFile.Free(); end; end; constructor TclGZip.Create(AOwner: TComponent); begin inherited Create(AOwner); FBatchSize := 8192; FCompressionLevel := clDefault; FStrategy := csDefault; FFlags := 0; end; procedure TclGZip.Compress(const AFileSource, AFileDestination: string); var inFile, outFile: TStream; begin inFile := nil; outFile := nil; try inFile := TFileStream.Create(AFileSource, fmOpenRead or fmShareDenyWrite); outFile := TFileStream.Create(AFileDestination, fmCreate); Compress(inFile, outFile); finally outFile.Free(); inFile.Free(); end; end; procedure TclGZip.CopyFrom(ASource, ADestination: TStream); var bufLen, bytesRead, proceed, total: Int64; buf: PclChar; begin bufLen := BatchSize; total := (ASource.Size - ASource.Position); if total < bufLen then begin bufLen := total; end; proceed := 0; GetMem(buf, bufLen); try repeat bytesRead := ASource.Read(buf^, bufLen); if (bytesRead > 0) then begin ADestination.Write(buf^, bytesRead); proceed := proceed + bytesRead; DoProgress(proceed, total); end; until (bytesRead = 0); finally FreeMem(buf); end; end; procedure TclGZip.Compress(ASource, ADestination: TStream); var compressor: TStream; begin compressor := TclGZipDeflateStream.Create(ADestination, CompressionLevel, Strategy, Flags); try CopyFrom(ASource, compressor); finally compressor.Free(); end; end; procedure TclGZip.DoProgress(ABytesProceed, ATotalBytes: Int64); begin if Assigned(OnProgress) then begin OnProgress(Self, ABytesProceed, ATotalBytes); end; end; end.
unit Cargos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Buttons; type TFrmCargos = class(TForm) btnNovo: TSpeedButton; btnSalvar: TSpeedButton; BtnEditar: TSpeedButton; btnExcluir: TSpeedButton; grid: TDBGrid; EdtNome: TEdit; lb_nome: TLabel; procedure btnNovoClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure gridCellClick(Column: TColumn); procedure BtnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); private { Private declarations } procedure associarCampos; procedure listar; procedure verificaCadastro; public { Public declarations } end; var FrmCargos: TFrmCargos; id : string; implementation {$R *.dfm} uses Modulo; procedure TFrmCargos.verificaCadastro; begin //verificar se o cargo já está cadastrado dm.query_cargos.Close; dm.query_cargos.SQL.Clear; dm.query_cargos.SQL.Add('SELECT * FROM cargos WHERE cargo = ' + QuotedStr(Trim(EdtNome.Text))); dm.query_cargos.Open; end; procedure TFrmCargos.associarCampos; begin dm.tb_Cargos.FieldByName('cargo').Value := EdtNome.Text; end; procedure TFrmCargos.BtnEditarClick(Sender: TObject); var cargo: string; begin if Trim(EdtNome.Text) = '' then begin MessageDlg('Preencha o Cargo!', mtInformation, mbOKCancel, 0); EdtNome.SetFocus; exit; end; verificaCadastro; if not dm.query_cargos.IsEmpty then begin cargo := dm.query_cargos['cargo']; MessageDlg('O cargo ' + cargo + ' já esta cadastrado!', mtInformation, mbOKCancel, 0); EdtNome.Text := ''; EdtNome.SetFocus; Exit; end; associarCampos; dm.query_cargos.Close; dm.query_cargos.SQL.Clear; dm.query_cargos.SQL.Add('UPDATE cargos set cargo = :cargo WHERE id = :id'); dm.query_cargos.ParamByName('cargo').Value := EdtNome.Text; dm.query_cargos.ParamByName('id').Value := id; dm.query_cargos.ExecSQL; listar; MessageDlg('Editado com sucesso!!', mtInformation, mbOKCancel, 0); btnEditar.Enabled := False; btnExcluir.Enabled := False; EdtNome.Text :=''; EdtNome.Enabled :=False; end; procedure TFrmCargos.btnExcluirClick(Sender: TObject); begin if MessageDlg('Deseja Excluir o registro?', mtConfirmation,[mbYes,mbNo],0) = mrYes then begin dm.tb_cargos.Close; dm.tb_cargos.SQL.Clear; dm.tb_cargos.SQL.Add('DELETE FROM cargos WHERE id = :id'); dm.tb_cargos.ParamByName('id').Value := id; dm.tb_cargos.ExecSQL; MessageDlg('Deletado com Sucesso!', mtInformation, mbOKCancel,0); listar; btnEditar.Enabled := False; btnExcluir.Enabled := False; EdtNome.Text :=''; EdtNome.Enabled :=False; end; end; procedure TFrmCargos.btnNovoClick(Sender: TObject); begin btnSalvar.Enabled := True; EdtNome.Enabled := True; EdtNome.Text := ''; EdtNome.SetFocus; dm.tb_Cargos.Insert; end; procedure TFrmCargos.btnSalvarClick(Sender: TObject); var cargo: string; begin if Trim(EdtNome.Text) = '' then begin MessageDlg('Preencha o Cargo!', mtInformation, mbOKCancel, 0); EdtNome.SetFocus; exit; end; verificaCadastro; if not dm.query_cargos.IsEmpty then begin cargo := dm.query_cargos['cargo']; MessageDlg('O cargo ' + cargo + ' já esta cadastrado!', mtInformation, mbOKCancel, 0); EdtNome.Text := ''; EdtNome.SetFocus; Exit; end; associarCampos; dm.tb_Cargos.Post; MessageDlg('Salvo com Sucesso!', mtInformation, mbOKCancel,0); EdtNome.Text := ''; EdtNome.Enabled := false; btnSalvar.Enabled := false; listar; end; procedure TFrmCargos.FormCreate(Sender: TObject); begin dm.tb_Cargos.Active := true; listar; end; procedure TFrmCargos.gridCellClick(Column: TColumn); begin EdtNome.Enabled := True; BtnEditar.Enabled := True; BtnExcluir.Enabled := True; dm.tb_Cargos.Edit; if dm.query_cargos.FieldByName('cargo').Value <> null then begin EdtNome.Text := dm.query_cargos.FieldByName('cargo').Value; id := dm.query_cargos.FieldByName('id').Value; end; end; procedure TFrmCargos.listar; begin dm.query_cargos.Close; dm.query_cargos.SQL.Clear; dm.query_cargos.SQL.Add('SELECT * FROM cargos order by cargo asc'); dm.query_cargos.Open; end; end.
unit TestBaseJsonMarshalUnit; interface uses TestFramework, Classes, SysUtils; type TTestBaseJsonMarshal = class abstract(TTestCase) protected procedure SaveTestDataToFile(s: String); procedure CheckEquals(EtalonFilename: String; Actual: String); function EtalonFilename(TestName: String): String; end; implementation { TTestOptimizationParametersToJson } procedure TTestBaseJsonMarshal.CheckEquals(EtalonFilename, Actual: String); var EtalonList: TStringList; ActualList: TStringList; begin EtalonList := TStringList.Create; ActualList := TStringList.Create; try EtalonList.LoadFromFile(EtalonFilename); ActualList.Text := Actual; // SaveTestDataToFile(Actual); CheckTrue(EtalonList.Equals(ActualList)); finally FreeAndNil(ActualList); FreeAndNil(EtalonList); end; end; function TTestBaseJsonMarshal.EtalonFilename(TestName: String): String; begin Result := '..\..\Etalons\' + TestName + '.json'; end; procedure TTestBaseJsonMarshal.SaveTestDataToFile(s: String); var st: TStringList; begin st := TStringList.Create; try st.Text := s; st.SaveToFile('TestData.txt'); finally FreeAndNil(st); end; end; end.
unit Mensa; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, DB, DBTables, StdCtrls, Grids, DBGrids, Buttons, ExtCtrls, NxColumns, NxColumnClasses, NxScrollControl, NxCustomGridControl, NxCustomGrid, NxGrid, FMTBcd, SqlExpr, Menus; type TfrmMensa = class(TForm) Panel1: TPanel; cmdCerrar: TBitBtn; cmdAgregar: TBitBtn; Panel2: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label6: TLabel; Label4: TLabel; Tabla: TNextGrid; Banca: TNxTextColumn; Agencia: TNxTextColumn; fechini: TNxDateColumn; fechafin: TNxDateColumn; mensaje: TNxMemoColumn; tipo: TNxTextColumn; status: TNxTextColumn; PopupMenu2: TPopupMenu; ReportexFecha1: TMenuItem; DestaparTodo1: TMenuItem; BorrarTodo1: TMenuItem; xbr: TButton; xba: TButton; cLoteriar: TEdit; cLoteria: TEdit; procedure FormShow(Sender: TObject); procedure cmdCerrarClick(Sender: TObject); procedure cLoteriaChange(Sender: TObject); procedure cmdAgregarClick(Sender: TObject); procedure fechaChange(Sender: TObject); procedure cLoteriaClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure ReportexFecha1Click(Sender: TObject); procedure DestaparTodo1Click(Sender: TObject); procedure BorrarTodo1Click(Sender: TObject); procedure CambioAge(elreso: string); procedure xbrClick(Sender: TObject); procedure xbaClick(Sender: TObject); private { Private declarations } public B,XSQL,XSQL1:string; procedure Actualizar(); { Public declarations } end; var frmMensa: TfrmMensa; implementation uses Data, CargaMensaje, RPTListas, BuscoAge, BuscoRece; {$R *.dfm} procedure TfrmMensa.FormShow(Sender: TObject); begin /// if frmData.Tipo='R' then begin XSQL:='SELECT codigo_ban,nombre_ban FROM datos_banca where esmirec(codigo_ban,'+ quotedstr(frmdata.BDBANCA)+')='+quotedstr('SI'); cLoteriar.Text:=frmdata.BDBANCA+' '; xbr.Caption:=frmdata.BDBANCA+' '; end else begin XSQL:='SELECT codigo_ban,nombre_ban FROM datos_banca' ; cLoteriar.Text:='TODOS '; xbr.Caption:='TODOS '; end; /// cLoteria.Text:='TODAS '; xba.Caption:='TODAS '; cambioAge(cLoteriar.Text); Actualizar(); Label3.Caption:=IntToStr(frmdata.Query1.RecordCount); end; procedure TfrmMensa.cmdCerrarClick(Sender: TObject); begin frmMensa.Close; end; procedure TfrmMensa.Actualizar(); var SQL: string; begin frmdata.Query1.Close; frmdata.Query1.SQL.Clear; SQL:=''; if cLoteriar.Text='TODOS ' then begin if cLoteria.Text='TODAS ' then SQL:='SELECT * FROM mensajes' else SQL:='SELECT * FROM mensajes where cod_agencia='+quotedstr(frmdata.mino(cLoteria.Text)); end else begin if cLoteria.Text='TODAS ' then SQL:='SELECT * FROM mensajes where EsMiAg(cod_agencia,'+quotedStr(frmdata.mino(cloteriar.Text))+')='+quotedStr('SI') else SQL:='SELECT * FROM mensajes where cod_banca='+quotedstr(frmdata.mino(cLoteriar.Text))+' and cod_agencia='+ quotedstr(frmdata.mino(cLoteria.Text)); end; frmdata.Query1.SQL.Add(SQL); frmData.Ejecutar(frmdata.Query1); Tabla.ClearRows; while not frmdata.Query1.Eof do begin Tabla.AddRow(1); Tabla.Cells[0,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['cod_banca']; Tabla.Cells[1,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['cod_agencia']; Tabla.Cells[2,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['fecha1']; Tabla.Cells[3,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['fecha2']; Tabla.Cells[4,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['mensaje']; Tabla.Cells[5,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['tipo']; Tabla.Cells[6,Tabla.RowCount-1]:=frmdata.Query1.FieldValues['estatus']; frmdata.Query1.Next; end; Label3.Caption:=IntToStr(frmdata.Query1.RecordCount); frmdata.Query1.Close; end; procedure TfrmMensa.cLoteriaChange(Sender: TObject); var I:integer; begin I:=Pos(' ',cLoteria.Text); B:=Copy(cLoteria.Text,1,I-1); Actualizar(); end; procedure TfrmMensa.cmdAgregarClick(Sender: TObject); begin frmcargamensa.elreso.Caption:=cloteriar.Text; frmCargamensa.showmodal; actualizar(); end; procedure TfrmMensa.fechaChange(Sender: TObject); begin Actualizar(); end; procedure TfrmMensa.cLoteriaClick(Sender: TObject); var I:integer; begin I:=Pos(' ',cLoteria.Text); B:=Copy(cLoteria.Text,1,I-1); end; procedure TfrmMensa.Button1Click(Sender: TObject); begin actualizar() end; procedure TfrmMensa.ReportexFecha1Click(Sender: TObject); var merata,cp1,clo: string; begin if Application.MessageBox('Borrará Mensajes de la Agencia Seleccionada, ¿Esta Seguro de Esto?','Advertencia',MB_YESNO)=ID_YES then begin cLo:=Tabla.Cell[0, Tabla.SelectedRow].AsString; merata:=Tabla.Cell[1, Tabla.SelectedRow].AsString; frmdata.Query.SQL.Clear; frmdata.Query.SQL.Add('CALL Borramen('+quotedStr(cLo)+','+quotedStr(merata)+');'); frmdata.Query.ExecSQL; // Auditoria cp1:=('Borro Mensaje para el Receptor: '+cLoteriar.Text+' Agencia : '+merata); frmRPTListas.elmiron(cp1); // Actualizar(); end; end; procedure TfrmMensa.DestaparTodo1Click(Sender: TObject); var merata,cp1,clo: string; begin if Application.MessageBox('Borrará Todos los mensajes del Receptor Seleccionado , ¿Esta Seguro de Esto?','Advertencia',MB_YESNO)=ID_YES then begin clo:=Tabla.Cell[0, Tabla.SelectedRow].AsString; merata:='TT'; frmdata.Query.SQL.Clear; frmdata.Query.SQL.Add('CALL Borramen('+quotedStr(cLo)+','+quotedStr(merata)+');'); frmdata.Query.ExecSQL; // Auditoria cp1:=('Borro Mensaje para EL Receptor: '+cLoteriar.Text+' Agencia : '+merata); frmRPTListas.elmiron(cp1); // Actualizar(); end; end; procedure TfrmMensa.BorrarTodo1Click(Sender: TObject); var merata,cp1,clo: string; begin if frmData.Tipo<>'R' then begin if Application.MessageBox('Borrará Todos los mensajes de Todos los Receptores , ¿Esta Seguro de Esto?','Advertencia',MB_YESNO)=ID_YES then begin clo:='TT'; merata:='TT'; frmdata.Query.SQL.Clear; frmdata.Query.SQL.Add('CALL Borramen('+quotedStr(cLo)+','+quotedStr(merata)+');'); frmdata.Query.ExecSQL; // Auditoria cp1:=('Borro Mensaje para Todos Los Receptores'); frmRPTListas.elmiron(cp1); // Actualizar(); end; end; end; ////////////////////////////////////////////////////// LO NUEVO DE BUSCAR 01-07-2016 //////////////////////////////////////////////////////// procedure TfrmMensa.CambioAge(elreso: string); begin if (elreso='') or (elreso='TODOS ') then if frmData.Tipo='R' then XSQL1:= 'SELECT codigo_age,nombre_age,codigo_ban FROM agencias_banca WHERE codigo_ban='+quotedStr(frmdata.BDBANCA) else XSQL1:= 'SELECT codigo_age,nombre_age,codigo_ban FROM agencias_banca' else XSQL1:= 'SELECT codigo_age,nombre_age,codigo_ban FROM agencias_banca WHERE codigo_ban='+quotedStr(frmdata.mino(elreso)); end; procedure TfrmMensa.xbaClick(Sender: TObject); var voyAge:string; begin xba.Caption:='..Espere un Momento...'; frmBuscoAge.el_sql.Caption:=XSQL1; frmBuscoAge.xLeft.Caption := inttostr(frmMensa.Left + 526); frmBuscoAge.xTop.Caption := inttostr(frmMensa.Top + 90);//trae 67 el top del boton o sea sume 67+113 frmBuscoAge.xtodo.Caption :='TODAS'; frmBuscoAge.ShowModal; if frmBuscoAge.agencia.Caption<>'' then begin xba.Caption:=frmBuscoAge.agencia.Caption; cLoteria.Text:=frmBuscoAge.agencia.Caption; end else xba.Caption:=cLoteria.Text; Actualizar(); end; procedure TfrmMensa.xbrClick(Sender: TObject); var voyrece:string; begin xbr.Caption:='..Espere un Momento...'; frmBuscoRece.el_sql.Caption:=XSQL; frmBuscoRece.xLeft.Caption := inttostr(frmMensa.Left + 174); frmBuscoRece.xTop.Caption := inttostr(frmMensa.Top + 90); //trae 67 el top del boton o sea sume 67+113 if frmData.Tipo='R' then frmBuscoRece.xtodo.Caption :=frmdata.BDBANCA else frmBuscoRece.xtodo.Caption :='TODOS'; voyrece:=cLoteriar.Text; frmBuscoRece.ShowModal; if frmBuscoRece.agencia.Caption<>'' then begin xbr.Caption:=frmBuscoRece.agencia.Caption; cLoteriar.Text:=frmBuscoRece.agencia.Caption; end else xbr.Caption:=cLoteriar.Text; if voyrece<>cLoteriar.Text then begin xba.Caption:='TODAS '; cLoteria.Text:='TODAS '; cambioAge(cLoteriar.Text); end; Actualizar(); end; end.
unit PowerPointUtils; interface uses Classes, MainUtils, ResourceUtils, ActiveX, ComObj, WinINet, Variants, sysutils, Types, StrUtils; type TPowerPointConverter = Class(TDocumentConverter) Private FPPVersion : String; PPApp : OleVariant; public constructor Create(); function CreateOfficeApp() : boolean; override; function DestroyOfficeApp() : boolean; override; function ExecuteConversion(fileToConvert: String; OutputFilename: String; OutputFileFormat : Integer): TConversionInfo; override; function AvailableFormats() : TStringList; override; function FormatsExtensions(): TStringList; override; function OfficeAppVersion() : String; override; End; implementation { TPowerPointConverter } function TPowerPointConverter.AvailableFormats: TStringList; begin Formats := TResourceStrings.Create('PPFORMATS'); result := Formats; end; constructor TPowerPointConverter.Create; begin inherited; //setup defaults InputExtension := '.ppt*'; OfficeAppName := 'Powerpoint'; end; function TPowerPointConverter.CreateOfficeApp: boolean; begin if VarIsEmpty(PPApp) then begin PPApp := CreateOleObject('PowerPoint.Application'); // ppApp.Visible := 0; end; Result := true; end; function TPowerPointConverter.DestroyOfficeApp: boolean; begin if not VarIsEmpty(PPApp) then begin PPApp.Quit; end; Result := true; end; function TPowerPointConverter.ExecuteConversion( fileToConvert, OutputFilename: String; OutputFileFormat: Integer): TConversionInfo; begin logDebug('Trying to Convert: ' + fileToConvert, Debug); Result.Successful := false; Result.InputFile := fileToConvert; // Open file ppApp.Presentations.Open(fileToConvert); // Save as file and close PPApp.ActivePresentation.SaveAs(OutputFileName, OutputFileFormat, false); PPApp.ActivePresentation.Save; PPApp.ActivePresentation.Close; Result.InputFile := fileToConvert; Result.Successful := true; Result.OutputFile := OutputFilename; end; function TPowerPointConverter.FormatsExtensions: TStringList; var Extensions : TStringList; begin Extensions := Tstringlist.Create(); LoadStringListFromResource('PPEXTENSIONS',Extensions); result := Extensions; end; function TPowerPointConverter.OfficeAppVersion(): String; begin FPPVersion := ReadOfficeAppVersion; if FPPVersion = '' then begin CreateOfficeApp(); FPPVersion := PPApp.Version; WriteOfficeAppVersion(FPPVersion); end; result := FPPVersion; end; end. 
program fppower; { Rtl_power produces a compact CSV file with minimal redundancy. The columns are: date, time, Hz low, Hz high, Hz step, samples, dB, dB, dB, ... Date and time apply across the entire row. The exact frequency of a dB value can be found by (hz_low + N * hz_step). The samples column indicated how many points went into each average. } {$GOTO ON} {$mode objfpc}{$H+} {$IFDEF Linux} {$DEFINE Unix} {$ENDIF} uses sysutils,math,strutils,ccsv; var mycsv : tcsv; r,c:integer; v:float; freq,vs,s:string; i:integer; format,evaluate:string; tmptime:string; log:boolean; //Logvalue freq,first_date,first_time,last_date,last_time,last_db,peak,occurances procedure logvalues(filename:string; freq,stime,sdate,db:string); var logcsv:tcsv; i,f:integer; p:float; found:boolean; S : AnsiString; begin //Create csv object logcsv := TCsv.Create(filename); with logcsv do begin Delimiter := ';'; OpenCsv(); //Check if open if MyCsv.IsOpen then begin found:=false; for i:=0 to recordcount-1 do begin if GetFieldValue(i,0)=freq then begin found:=true; f:=i; break; end; end; if found=true then begin //found SetFieldValue(f,3,sdate); SetFieldValue(f,4,stime); if strtofloat(getfieldvalue(f,6))<strtofloat(db) then setfieldvalue(f,6,db); SetFieldValue(f,5,db); p:=strtofloat(getfieldvalue(f,7))+1; setfieldvalue(f,7,floattostr(p)); end else begin //not found DateTimeToString(s,'YYYY-MM-DD',Date); AddRecord(freq+';'+s+';'+timetostr(time)+';'+sdate+';'+stime+';'+db+';'+db+';1;'); end; UpdateCsv; savecsv(filename); end; end; end; procedure writecsvdata(filename:string; str:string); var filevar:textfile; begin assignfile(filevar,filename); {$I+} try rewrite(filevar); writeln(filevar,str); closefile(filevar); except on E: EInOutError do begin writeln('File error'); end; end; end; procedure checkvalues(cvsfile:string); begin //Create csv object MyCsv := TCsv.Create(cvsfile); with mycsv do begin Delimiter := ','; OpenCsv(); //Check if open if MyCsv.IsOpen then begin for r := 0 to RecordCount - 1 do begin if format='SPECTRUM' then begin if tmptime<>GetFieldValue(r, 1) then begin writeln('Time: ',GetFieldValue(r, 1)); tmptime:=GetFieldValue(r, 1); end; end; for c := 6 to fieldcount -1 do begin //Show first name. try v:=strtofloat(GetFieldValue(r,c)); case evaluate of 'MORE' : begin if v > strtofloat(paramstr(1)) then begin freq:=FormatFloat('#,##0.00;;Zero',strtofloat(GetFieldValue(r, 2)) + strtofloat(GetFieldValue(r, 4)) * c); vs:=FormatFloat('#,##0.00;;Zero',v); case format of 'NORMAL': begin writeln('[',GetFieldValue(r, 0),' / ',GetFieldValue(r, 1),'] Freq: ',freq,' Hz, Value: ', vs); end; 'CSV' : begin writeln(GetFieldValue(r, 0),';',GetFieldValue(r, 1),';',freq,';', vs); end; 'SPECTRUM' : begin writeln(freq,'| ',dupestring('#',round(30+(v*40/30))),vs); end; end; end; if log then logvalues('./fppower_log.csv',freq,GetFieldValue(r, 1),GetFieldValue(r, 0),vs); end; 'LESS' : begin if v < strtofloat(paramstr(1)) then begin freq:=FormatFloat('#,##0.00;;Zero',strtofloat(GetFieldValue(r, 2)) + strtofloat(GetFieldValue(r, 4)) * c); vs:=FormatFloat('#,##0.00;;Zero',v); case format of 'NORMAL': begin writeln('[',GetFieldValue(r, 0),' / ',GetFieldValue(r, 1),'] Freq: ',freq,' Hz, Value: ', vs); end; 'CSV' : begin writeln(GetFieldValue(r, 0),';',GetFieldValue(r, 1),';',freq,';', vs); end; 'SPECTRUM' : begin writeln(freq,'| ',dupestring('#',round(30+(v*40/30))),vs); end; end; end; if log then logvalues('./fppower_log.csv',freq,GetFieldValue(r, 1),GetFieldValue(r, 0),vs); end; end; except writeln('Conversion error [021]'); end; end; end; end; end; end; procedure helpscreen; begin writeln; writeln('Filter rtl_power results to get active frequencies.'); writeln; writeln('[] Usage:'); writeln(' fppower <value> [filename] [options]'); writeln; writeln(' <value> : float number, indicates strength of signal from rtl_power'); writeln(' [filename] : file to get values from. Leave empty to get values from stdin'); writeln; writeln('[] Options'); writeln(' -csv : Format output as CSV'); writeln(' -spectrum : Display results like a spectrum analyzer'); writeln(' -more : Value is over, target value [default]'); writeln(' -less : Value is under, target value'); writeln(' -log : keeps a log file, with found results'); writeln; writeln('[] Example:'); writeln(' fppower -40 rtlpower.csv'); writeln(' rtl_power -f 146M:175M:5k | ./fppower -40'); writeln(' fppower -40 rtlpower.csv -csv -less'); writeln(' rtl_power -f 119M:175M:2k | ./fppower 1 -more -csv | cut -d '';'' -f3'); writeln(' rtl_power -f 119M:175M:2k | ./fppower 2 -log'); writeln; writeln('[] Log file'); writeln(' The log file (fppower_log.csv) is a CSV file with the results that match'); writeln(' the criteria. This file is for searches, so if you want a different file'); writeln(' for each search, you must copy the existing one'); writeln; end; begin format:='NORMAL'; evaluate:='MORE'; tmptime:=''; log:=false; if paramcount<1 then begin helpscreen; exit; end; try strtofloat(paramstr(1)); except helpscreen; exit; end; if paramcount>=2 then begin for i:=2 to paramcount do begin if uppercase(paramstr(i))='-CSV' then format:='CSV'; if uppercase(paramstr(i))='-SPECTRUM' then format:='SPECTRUM'; if uppercase(paramstr(i))='-LESS' then evaluate:='LESS'; if uppercase(paramstr(i))='-MORE' then evaluate:='MORE'; if uppercase(paramstr(i))='-LOG' then log:=true; end; end; if not fileexists(paramstr(2)) then begin while not EOF do begin ReadLn(s); writecsvdata('./tmp.csv',s); checkvalues('./tmp.csv'); end; end else begin checkvalues(paramstr(2)); end; end.
{ Wolverine Hudson Message Base Extensions - 13th Dec 96 - 03:46 - SSG } unit WHudson; interface uses WTypes; type PHudsonBase = ^THudsonBase; THudsonBase = object(TObject) constructor Init(awhere,apacketid:FnameStr); function Load:boolean;virtual; function ReadMsgText(amsg:PMsg):PMsgText;virtual; procedure MsgToFile(amsg:Pmsg; afile:FnameStr);virtual; end; implementation const maDeleted = 1; {Message is deleted} maUnmovedNet = 2; {Unexported Netmail message} maNetMail = 4; {Message is netmail message} maPriv = 8; {Message is private} maRcvd = 16; {Message is received} maUnmovedEcho = 32; {Unexported Echomail message} maLocal = 64; {"Locally" entered message} naKillSent = 1; {Delete after exporting} naSent = 2; {Msg has been sent} naFAttach = 4; {Msg has file attached} naCrash = 8; {Msg is crash} naReqRcpt = 16; {Msg requests receipt} naReqAudit = 32; {Msg requests audit} naRetRcpt = 64; {Msg is a return receipt} naFileReq = 128; {Msg is a file request} type TMsgTxtRec = string[255]; TMsgToIdxRec = string[35]; TMsgInfo = record LowMsg,HighMsg : word; Active : word; AreaActive : array[1..200] of word; {msgs active in each area} end; TMsgIdxRec = record MsgNum : word; Area : byte; end; TMsgHdr = record MsgNum : word; ReplyTo: Word; {Message is reply to this number} SeeAlso: Word; {Message has replies} Extra: Word; {No longer used} StartRec: Word; {starting seek offset in MsgTxt.Bbs} NumRecs: Word; {number of MsgTxt.Bbs records} DestNet: Integer; {NetMail Destination Net} DestNode: Integer; {NetMail Destination Node} OrigNet: Integer; {NetMail Originating Net} OrigNode: Integer; {NetMail Originating Node} DestZone: Byte; {NetMail Destination Zone} OrigZone: Byte; {NetMail Originating Zone} Cost: Word; {NetMail Cost} MsgAttr: Byte; {Message attribute - see constants} NetAttr: Byte; {Netmail attribute - see constants} Area: Byte; {Message area} Time: String[5]; {Message time in HH:MM} Date: String[8]; {Message date in MM-DD-YY} MsgTo: String[35]; {Message is intended for} MsgFrom: String[35]; {Message was written by} Subj: String[72]; {Message subject} end; TLastRead = array[1..200] of word; const areaFile : string[12] = 'AREAS.BBS'; msginfoFile : string[12] = 'MSGINFO.BBS'; constructor THudsonBase.Init; begin inherited Init(awhere,apacketid); Config := 0; end; function THudsonBase.Load; var T:TDosStream; arearec:string[35]; mirec:TMsgInfo; b:byte; Pa:PArea; begin Load := false; Debug('hudson base loading'); with user do begin Name := '?'; Alias := '?'; SysOp := '?'; BBS := '?'; NetFlags := 0; end; T.Init(Where + msginfoFile,stOpenRead); T.Read(mirec,SizeOf(mirec)); T.Done; T.Init(Where + areaFile,stOpenRead); for b:=1 to 200 do begin {areas} if (highmsg > lowmsg) then begin New(Pa); Pa^.Name := 'Area #'+l2s(b); Pa^.Number := b; Pa^.AreaType := watEcho; Pa^.Flags := 0; Pa^.Pers := 0; Pa^.Unread := if mirec.AreaActive[ end; end; function THudsonBase.ReadMsgText; begin end; procedure THudsonBase.MsgToFile; begin end; end.
unit ufrmSettingAplikasi; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefault, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, Vcl.Menus, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, System.ImageList, Vcl.ImgList, Datasnap.DBClient, Datasnap.Provider, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, cxCheckBox, cxGridLevel, cxClasses, cxGridCustomView, Vcl.StdCtrls, cxButtons, Vcl.ComCtrls, Vcl.ExtCtrls, cxPC, dxStatusBar, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, uSettingApp, cxCurrencyEdit; type TfrmSettingAplikasi = class(TfrmDefault) lblGudangPenjualan: TLabel; cbbGudangPenjualan: TcxExtLookupComboBox; lblCabang: TLabel; cbbCabang: TcxExtLookupComboBox; lblGudangTransit: TLabel; cbbGudangTransit: TcxExtLookupComboBox; lblMaxBelanja: TLabel; edMaxBelanjaHari: TcxCurrencyEdit; procedure ActionBaruExecute(Sender: TObject); procedure ActionRefreshExecute(Sender: TObject); procedure cxPCDataChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure btnHapusClick(Sender: TObject); private FSettingApp: TSettingApp; function GetSettingApp: TSettingApp; procedure InisialisasiCBBGudang; procedure InisialisasiCBBCabang; property SettingApp: TSettingApp read GetSettingApp write FSettingApp; { Private declarations } public destructor Destroy; override; procedure LoadData(AID : String); { Public declarations } end; var frmSettingAplikasi: TfrmSettingAplikasi; implementation uses uDBUtils, uAppUtils, uModel, ClientModule; {$R *.dfm} destructor TfrmSettingAplikasi.Destroy; begin inherited; SettingApp.Free; end; procedure TfrmSettingAplikasi.ActionBaruExecute(Sender: TObject); begin inherited; LoadData(''); end; procedure TfrmSettingAplikasi.ActionRefreshExecute(Sender: TObject); var lcds: TClientDataSet; begin inherited; if chkKonsolidasi1.Checked then lcds := TDBUtils.DSToCDS(ClientDataModule.ServerLaporanClient.RetriveSettingApp(nil), cxGridDBTableOverview) else lcds := TDBUtils.DSToCDS(ClientDataModule.ServerLaporanClient.RetriveSettingApp(ClientDataModule.Cabang), cxGridDBTableOverview); cxGridDBTableOverview.SetDataset(lcds, True); cxGridDBTableOverview.SetVisibleColumns(['ID', 'CABANGID'], False); cxGridDBTableOverview.ApplyBestFit(); end; procedure TfrmSettingAplikasi.btnHapusClick(Sender: TObject); begin inherited; if not TAppUtils.ConfirmHapus then Exit; try if ClientDataModule.ServerSettingAppClient.Delete(SettingApp) then begin TAppUtils.InformationBerhasilHapus; LoadData(''); end; except raise end; end; procedure TfrmSettingAplikasi.btnSaveClick(Sender: TObject); begin inherited; if not ValidateEmptyCtrl([1]) then Exit; SettingApp.Cabang := TCabang.CreateID(cbbCabang.EditValue); SettingApp.GudangPenjualan := TGudang.CreateID(cbbGudangPenjualan.EditValue); SettingApp.GudangTransit := TGudang.CreateID(cbbGudangTransit.EditValue); SettingApp.MaxBelanjaSantri:= edMaxBelanjaHari.Value; try if ClientDataModule.ServerSettingAppClient.Save(SettingApp) then begin TAppUtils.InformationBerhasilSimpan; end; except raise end; end; procedure TfrmSettingAplikasi.cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin inherited; LoadData(cxGridDBTableOverview.DS.FieldByName('ID').AsString); cxPCData.ActivePageIndex := 1; end; procedure TfrmSettingAplikasi.cxPCDataChange(Sender: TObject); begin inherited; btnCetak.Enabled := False; end; procedure TfrmSettingAplikasi.FormCreate(Sender: TObject); begin inherited; InisialisasiCBBGudang; InisialisasiCBBCabang; end; function TfrmSettingAplikasi.GetSettingApp: TSettingApp; begin if FSettingApp = nil then FSettingApp := TSettingApp.Create; Result := FSettingApp; end; procedure TfrmSettingAplikasi.InisialisasiCBBGudang; var lCDSGudang: TClientDataSet; sSQL: string; begin // gudang penjualan sSQL := 'select Nama,Kode,ID from TGudang'; lCDSGudang := TDBUtils.OpenDataset(sSQL); cbbGudangPenjualan.Properties.LoadFromCDS(lCDSGudang,'ID','Nama',['ID'],Self); cbbGudangPenjualan.Properties.SetMultiPurposeLookup; //Gudang transit sSQL := 'select Nama,Kode,ID from TGudang'; lCDSGudang := TDBUtils.OpenDataset(sSQL); cbbGudangTransit.Properties.LoadFromCDS(lCDSGudang,'ID','Nama',['ID'],Self); cbbGudangTransit.Properties.SetMultiPurposeLookup; end; procedure TfrmSettingAplikasi.InisialisasiCBBCabang; var lCDSCabang: TClientDataSet; sSQL: string; begin sSQL := 'select * from tcabang'; lCDSCabang := TDBUtils.OpenDataset(sSQL); cbbCabang.Properties.LoadFromCDS(lCDSCabang,'ID','Nama',['ID'],Self); cbbCabang.Properties.SetMultiPurposeLookup; end; procedure TfrmSettingAplikasi.LoadData(AID : String); begin ClearByTag([0,1]); FreeAndNil(FSettingApp); if AID = '' then Exit; FSettingApp := ClientDataModule.ServerSettingAppClient.Retrieve(AID); if FSettingApp = nil then Exit; if FSettingApp.ID = '' then Exit; cbbCabang.EditValue := FSettingApp.Cabang.ID; cbbGudangPenjualan.EditValue := FSettingApp.GudangPenjualan.ID; cbbGudangTransit.EditValue := FSettingApp.GudangTransit.ID; edMaxBelanjaHari.Value := FSettingApp.MaxBelanjaSantri; end; end.
unit DW.PushKit; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} // Full instructions on VoIP setup: https://stackoverflow.com/a/28562124/3164070 // Also: https://www.raywenderlich.com/8164-push-notifications-tutorial-getting-started // Setting up a server: https://docs.developer.pv.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server?language=objc interface type TPushKit = class; TCustomPlatformPushKit = class(TObject) private FPushKit: TPushKit; protected procedure DoMessageReceived(const AJSON: string); procedure DoTokenReceived(const AToken: string; const AIsNew: Boolean); function GetStoredToken: string; virtual; procedure Start; virtual; property PushKit: TPushKit read FPushKit; public constructor Create(const APushKit: TPushKit); virtual; end; TPushKitTokenReceivedEvent = procedure(Sender: TObject; const Token: string; const IsNew: Boolean) of object; TPushKitMessageReceivedEvent = procedure(Sender: TObject; const JSON: string) of object; TPushKit = class(TObject) private FPlatformPushKit: TCustomPlatformPushKit; FOnMessageReceived: TPushKitMessageReceivedEvent; FOnTokenReceived: TPushKitTokenReceivedEvent; function GetStoredToken: string; protected procedure DoMessageReceived(const AJSON: string); procedure DoTokenReceived(const AToken: string; const AIsNew: Boolean); public constructor Create; destructor Destroy; override; procedure Start; property StoredToken: string read GetStoredToken; property OnMessageReceived: TPushKitMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived; property OnTokenReceived: TPushKitTokenReceivedEvent read FOnTokenReceived write FOnTokenReceived; end; implementation {$IF Defined(IOS)} uses DW.OSLog, DW.PushKit.iOS; {$ELSE} type TPlatformPushKit = class(TCustomPlatformPushKit); {$ENDIF} { TCustomPlatformPushKit } constructor TCustomPlatformPushKit.Create(const APushKit: TPushKit); begin inherited Create; FPushKit := APushKit; end; procedure TCustomPlatformPushKit.DoMessageReceived(const AJSON: string); begin TOSLog.d('TCustomPlatformPushKit.DoMessageReceived: %s', [AJSON]); FPushKit.DoMessageReceived(AJSON); end; procedure TCustomPlatformPushKit.DoTokenReceived(const AToken: string; const AIsNew: Boolean); begin FPushKit.DoTokenReceived(AToken, AIsNew); end; function TCustomPlatformPushKit.GetStoredToken: string; begin Result := ''; end; procedure TCustomPlatformPushKit.Start; begin // end; { TPushKit } constructor TPushKit.Create; begin inherited; FPlatformPushKit := TPlatformPushKit.Create(Self); end; destructor TPushKit.Destroy; begin FPlatformPushKit.Free; inherited; end; procedure TPushKit.DoMessageReceived(const AJSON: string); begin if Assigned(FOnMessageReceived) then FOnMessageReceived(Self, AJSON); end; procedure TPushKit.DoTokenReceived(const AToken: string; const AIsNew: Boolean); begin if Assigned(FOnTokenReceived) then FOnTokenReceived(Self, AToken, AIsNew); end; function TPushKit.GetStoredToken: string; begin Result := FPlatformPushKit.GetStoredToken; end; procedure TPushKit.Start; begin FPlatformPushKit.Start; end; end.
unit BaseDataIO; interface uses DataChain; type PDataIO = ^TDataIO; PDataBuffer = ^TDataBuffer; PDataBufferNode = ^TDataBufferNode; TDataIO = packed record Owner : Pointer; DoDataIn : procedure(ADataIO: PDataIO; AData: PDataBuffer); DoDataOut : procedure(ADataIO: PDataIO; AData: PDataBuffer); end; TDataBufferHead = packed record DataType : Integer; Owner : Pointer; ChainNode : PChainNode; BufferSize : Integer; DataLength : Integer; end; TDataBuffer = packed record BufferHead : TDataBufferHead; Data : array[0..64 * 1024 - 1] of AnsiChar; end; TDataBufferNodeHead = packed record DataType : Integer; Buffer : PDataBuffer; BufferSize : Integer; DataLength : Integer; PrevSibling : PDataBufferNode; NextSibling : PDataBufferNode; end; TDataBufferNode = packed record NodeHead : TDataBufferNodeHead; Data : array[0..4 * 1024 - 1] of AnsiChar; end; implementation end.
unit guests; interface uses net,jpeg,main,common; type TGuestChar = class(TObject) private fimage:TJPEGImage; fnick: String; fcol: word; fvisible:boolean; fnpc:boolean; filh,firh,fineck,fiarm,fihead,firring,filring,ficloak,figaunt,fiboot,fibp,firap,filap,firfp,filfp:integer; flh,frh,fneck,farm,fhead,frring,flring,fcloak,fgaunt,fboot,fbp,frap,flap,frfp,flfp:string; fhp:word; public constructor Create(const nick:string; const image: string; const color:word; const hp:word; const visible:byte; const npc:byte); overload; constructor Create(const col: integer; const visible: boolean); overload; destructor Destroy(); override; procedure Update(const attr:str_arr; const iattr:wrd_arr); property nick: String read fnick write fnick; property col: word read fcol write fcol; property bp: string read fbp write fbp; property rap: string read frap write frap; property lap: string read flap write flap; property rfp: string read frfp write frfp; property lfp: string read flfp write flfp; property lh: string read flh write flh; property rh: string read frh write frh; property neck: string read fneck write fneck; property arm: string read farm write farm; property head: string read fhead write fhead; property cloak: string read fcloak write fcloak; property gaunt: string read fgaunt write fgaunt; property boot: string read fboot write fboot; property rring: string read frring write frring; property lring: string read flring write flring; property ibp: integer read fibp write fibp; property irap: integer read firap write firap; property ilap: integer read filap write filap; property irfp: integer read firfp write firfp; property ilfp: integer read filfp write filfp; property ilh: integer read filh write filh; property irh: integer read firh write firh; property ineck: integer read fineck write fineck; property iarm: integer read fiarm write fiarm; property ihead: integer read fihead write fihead; property icloak: integer read ficloak write ficloak; property igaunt: integer read figaunt write figaunt; property iboot: integer read fiboot write fiboot; property irring: integer read firring write firring; property ilring: integer read filring write filring; property hp: word read fhp write fhp; property visible: boolean read fvisible write fvisible; property npc: boolean read fnpc write fnpc; property image: TJPEGImage read fimage write fimage; end; type TString = class(TObject) private fStr: String; public constructor Create(const AStr: String) ; procedure Append(ap: string); property Str: String read FStr write FStr; end; var last_guest, MyNick: string; implementation uses SysUtils,bmpTools; constructor TGuestChar.Create(const nick:string; const image: string; const color:word; const hp:word; const visible:byte; const npc:byte); begin inherited Create; if (not f_main.ingame) then exit; fimage:=GetJPEG(image,AppDir+'\avatars\'+fnick+'.jpg',AppDir+'\img\none.jpg'); fcol:=color; fhp:=hp; fvisible:=(visible=1); fnpc:=(npc=1); end; destructor TGuestChar.Destroy(); begin fimage.Free; inherited; end; procedure TGuestChar.Update(const attr:str_arr; const iattr:wrd_arr); begin fbp:=attr[0]; fibp:=iattr[0]; frap:=attr[1]; firap:=iattr[1]; flap:=attr[2]; filap:=iattr[2]; frfp:=attr[3]; firfp:=iattr[3]; flfp:=attr[4]; filfp:=iattr[4]; fhead:=attr[5]; fihead:=iattr[5]; fneck:=attr[6]; fineck:=iattr[6]; frh:=attr[7]; firh:=iattr[7]; flh:=attr[8]; filh:=iattr[8]; frring:=attr[9]; firring:=iattr[9]; flring:=attr[10]; filring:=iattr[10]; farm:=attr[11]; fiarm:=iattr[11]; fboot:=attr[12]; fiboot:=iattr[12]; fcloak:=attr[13]; ficloak:=iattr[13]; fgaunt:=attr[14]; figaunt:=iattr[14]; end; constructor TGuestChar.Create(const col: integer; const visible: boolean); begin inherited Create; fcol:=col; fvisible:=visible; end; constructor TString.Create(const AStr: String) ; begin inherited Create; FStr := AStr; end; procedure TString.Append(ap: string); begin FStr := FStr + ap +'<BR>'; end; end.
Unit HashMap; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} interface (* Some very basic hashing.. You need to write your own hash function if you want the Key to be anything else then UInt32/Cardinal/LongWord. *) {$mode objfpc}{$H+} {$macro on} {$modeswitch advancedrecords} {$inline on} uses Classes, CoreTypes, SysUtils; type //----------------------------------------\\ //-----------<UInt32, ColorLAB>-----------\\ TEntryLAB = record Key: UInt32; Value: ColorLAB; end; TLABHash = class private FTable: Array of Array of TEntryLAB; FLen: Integer; public constructor Create(Size:Integer); function Get(Key: UInt32; out Value: ColorLAB): Boolean; Inline; function Add(Key: UInt32; Value: ColorLAB): Boolean; Inline; Destructor Destroy; override; end; //----------------------------------------\\ //-------------<UInt32, Int32>------------\\ TEntryI32 = record Key: UInt32; Value: Int32; end; TI32Hash = class private FTable: Array of Array of TEntryI32; FLen: Integer; public constructor Create(Size:Integer); function Get(Key: UInt32; var Value: Int32): Boolean; Inline; function Add(Key: UInt32; Value:Int32): Boolean; Inline; Destructor Destroy; override; end; //----------------------------------------\\ //------------<UInt32, Single>------------\\ TEntryF32 = record Key: UInt32; Value: Single; end; TF32Hash = class private FTable: Array of Array of TEntryF32; FLen: Integer; public constructor Create(Size:Integer); function Get(Key: UInt32; var Value: Single): Boolean; Inline; function Add(Key: UInt32; Value:Single): Boolean; Inline; Destructor Destroy; override; end; //----------------------------------------\\ //--------------<Key, Value>--------------\\ generic THashMap<K,V> = record private FHashFunc: function(const key:K): UInt32; FTable: Array of Array of record Key: UInt32; Value: Single; end; FLen: Integer; public procedure Create(Size:Int32; HashFunc:Pointer); function Get(Key: K; var Value: V): Boolean; Inline; function Add(Key: K; Value:V): Boolean; Inline; procedure Destroy; end; //Hash-functions to go with the hashtable. function Hash(const k: Byte): UInt32; Inline; overload; function Hash(const k: UInt32): UInt32; Inline; overload; function Hash(const k: Int32): UInt32; Inline; overload; function Hash(const k: Int64): UInt32; Inline; overload; function Hash(const k: TPoint): UInt32; Inline; overload; function Hash(const k: Single): UInt32; Inline; overload; function Hash(const k: AnsiString): UInt32; Inline; overload; //------------------------------------------------------------------------------ implementation uses CoreMath; (******************************* Hash Functions *******************************) //Hash Byte - ofc this will only result in max 255 buckets no matter. function Hash(const k: Byte): UInt32; Inline; overload; begin Result := k; end; //Hash UInt32 function Hash(const k: UInt32): UInt32; Inline; overload; begin Result := k; end; //Hash Int32 function Hash(const k: Int32): UInt32; Inline; overload; begin Result := UInt32(k); end; //Hash a Int64 function Hash(const k: Int64): UInt32; Inline; overload; begin Result := UInt32(k); end; //Hash 4 byte floating point (Single) function Hash(const k: Single): UInt32; Inline; overload; begin Result := UInt32(k); end; //Hash a TPoint (x,y record) | Should work well. function Hash(const k: TPoint): UInt32; Inline; overload; begin Result := UInt32((k.y * $0f0f1f1f) xor k.x); end; //Hash a string.. untested. function Hash(const k: AnsiString): UInt32; Inline; overload; var i: Int32; begin Result := 0; for i:=1 to Length(k) do Result := ((Result shl 2) or (Result shr (SizeOf(Result)*8-2))) xor Byte(k[I]); end; (******************************** Hash Tables *********************************) { <UInt32, ColorLAB> A supersimple hashmap, should be pretty decent performancewise as long as enough space is allocated, what ever size you give it it will allocate NextPowerOfTwo(size*1.25) mem, this allows us to use bitshifting instead of division (mod-operator), the "1.25" is just to overallocate a bit, for performance. FTable is like an "array of buckets", where each bucket represents a hash-index. } constructor TLABHash.Create(Size:Integer); begin inherited Create; FLen := NextPow2m1(Trunc(Size * 1.25)); SetLength(FTable, FLen+1); end; destructor TLABHash.Destroy; begin inherited Destroy; SetLength(FTable, 0); end; function TLABHash.Add(Key: UInt32; Value: ColorLAB): Boolean; Inline; var h,l,i: Int32; begin h := Key and FLen; l := Length(Self.FTable[h]); for i:=0 to l-1 do if(self.FTable[h][i].Key = Key) then begin Self.FTable[h][i].Value := Value; Exit(True); end; SetLength(Self.FTable[h], l+1); Self.FTable[h][l].Key := Key; Self.FTable[h][l].Value := Value; Result := True; end; function TLABHash.Get(Key: UInt32; out Value: ColorLAB): Boolean; Inline; var h,i,l: Int32; begin h := Key and FLen; l := Length(Self.FTable[h]) - 1; for i:=0 to l do if(self.FTable[h][i].Key = Key) then begin Value := Self.FTable[h][i].Value; Exit(True); end; Result := False; end; { <UInt32, Int32> A supersimple hashmap, should be pretty decent performancewise as long as enough space is allocated, what ever size you give it it will allocate NextPowerOfTwo(size*1.25) mem, this allows us to use bitshifting instead of division (mod-operator). FTable is like an "array of buckets", where each bucket represents a hash-index. } constructor TI32Hash.Create(Size:Integer); begin inherited Create; FLen := NextPow2m1(Trunc(Size * 1.25)); SetLength(FTable, FLen+1); end; destructor TI32Hash.Destroy; begin inherited Destroy; SetLength(FTable, 0); end; function TI32Hash.Add(Key: UInt32; Value:Int32): Boolean; Inline; var h,l,i: Int32; begin h := Key and FLen; l := Length(Self.FTable[h]); for i:=0 to l-1 do if(self.FTable[h][i].Key = Key) then begin Self.FTable[h][i].Value := Value; Exit(True); end; SetLength(Self.FTable[h], l+1); Self.FTable[h][l].Key := Key; Self.FTable[h][l].Value := Value; Result := True; end; function TI32Hash.Get(Key: UInt32; var Value: Int32): Boolean; Inline; var h,i,l: Int32; begin h := Key and FLen; l := Length(Self.FTable[h]) - 1; for i:=0 to l do if(self.FTable[h][i].Key = Key) then begin Value := Self.FTable[h][i].Value; Exit(True); end; Result := False; end; { <UInt32, Single> A supersimple hashmap, should be pretty decent performancewise as long as enough space is allocated, what ever size you give it it will allocate NextPowerOfTwo(size*1.25) mem, this allows us to use bitshifting instead of division (mod-operator). FTable is like an "array of buckets", where each bucket represents a hash-index. } constructor TF32Hash.Create(Size:Integer); begin inherited Create; FLen := NextPow2m1(Trunc(Size * 1.25)); SetLength(FTable, FLen+1); end; destructor TF32Hash.Destroy; begin inherited Destroy; SetLength(FTable, 0); end; function TF32Hash.Add(Key: UInt32; Value: Single): Boolean; Inline; var h,l,i: Int32; begin h := Key and FLen; l := Length(Self.FTable[h]); for i:=0 to l-1 do if(self.FTable[h][i].Key = Key) then begin Self.FTable[h][i].Value := Value; Exit(True); end; SetLength(Self.FTable[h], l+1); Self.FTable[h][l].Key := Key; Self.FTable[h][l].Value := Value; Result := True; end; function TF32Hash.Get(Key: UInt32; var Value: Single): Boolean; Inline; var h,i,l: Int32; begin h := Key and FLen; l := Length(Self.FTable[h]) - 1; for i:=0 to l do if(self.FTable[h][i].Key = Key) then begin Value := Self.FTable[h][i].Value; Exit(True); end; Result := False; end; { <Key, Value> A supersimple hashmap, should be pretty decent performancewise as long as enough space is allocated, what ever size you give it it will allocate NextPowerOfTwo(size*1.25) mem, this allows us to use bitshifting instead of division (mod-operator). FTable is like an "array of buckets", where each bucket represents a hash-index. } procedure THashMap.Create(Size:Int32; HashFunc:Pointer); type THashFunc = function(const key:K): UInt32; begin FHashFunc := THashFunc(HashFunc); FLen := NextPow2m1(Trunc(Size * 1.25)); SetLength(FTable, FLen+1); end; procedure THashMap.Destroy; begin SetLength(FTable, 0); end; function THashMap.Add(Key: K; Value: V): Boolean; Inline; var h,l,i: Int32; begin h := FHashFunc(Key) and FLen; l := Length(Self.FTable[h]); for i:=0 to l-1 do if(self.FTable[h][i].Key = Key) then begin Self.FTable[h][i].Value := Value; Exit(True); end; SetLength(Self.FTable[h], l+1); Self.FTable[h][l].Key := Key; Self.FTable[h][l].Value := Value; Result := True; end; function THashMap.Get(Key: K; var Value: V): Boolean; Inline; var h,i,l: Int32; begin h := FHashFunc(Key) and FLen; l := Length(Self.FTable[h]) - 1; for i:=0 to l do if(self.FTable[h][i].Key = Key) then begin Value := Self.FTable[h][i].Value; Exit(True); end; Result := False; end; end.
unit QRAbsDatas; //******************************************************************** // // TQRAbstractTable : TDataset with no underlying database // // (c) QBS 2003/4/5/6/10/11/12 // // 3/05/2006 Upgraded with GetRecordEvent to fix extra record bug. // 26/01/2010 improved Prior implementation // 17/01/2012 fixed MoveBy, now calling inherited // 24/04/2013 DC updates //******************************************************************** interface uses windows, classes, controls, stdctrls, sysutils, db; const MAX_STRING = 64000; type TQRAbsTable = class; TQRDataAbsSetEvent = procedure( const DataStr : string; Field : TField; buffer : pointer ) of object; TQRAbsRecordEvent = procedure( Sender:TQRAbsTable ; var Moredata : boolean ) of object; TQRAbsTable = class(TDataset) private FOnSetFieldValue : TQRDataAbsSetEvent; FOnGetRecord : TQRAbsRecordEvent; FRecBufSize: Word; FRecordSize : word; FDefFieldLen : integer; FRecordCount : longint; FCurRecord : longint; FEOF : Boolean; FBOF : Boolean; FMoredata : boolean; //FActive : boolean; FDoneFielddefs : boolean; FFieldnames : TStringlist; // prior stuff FLastGetOp : TGetMode; FCurrentGetOp : TGetMode; //FSavedBuffer : PByte; //FSwapBuffer : PByte; protected procedure ClearData; // abstracts from TDataset function AllocRecordBuffer: PByte; override; procedure FreeRecordBuffer(var Buffer: PByte); override; procedure GetBookmarkData(Buffer: PByte; Data: Pointer); override; function GetBookmarkFlag(Buffer: PByte): TBookmarkFlag; override; function GetRecord(Buffer: PByte; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; function GetRecordSize: Word; override; procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override; procedure InternalClose; override; procedure InternalDelete; override; procedure InternalFirst; override; procedure InternalGotoBookmark(Bookmark: Pointer); override; procedure InternalHandleException; override; procedure InternalInitFieldDefs; override; procedure InternalInitRecord(Buffer: PByte); override; procedure InternalLast; override; procedure InternalOpen; override; procedure InternalPost; override; procedure InternalSetToRecord(Buffer: PByte); override; function IsCursorOpen: Boolean; override; procedure SetBookmarkFlag(Buffer: PByte; Value: TBookmarkFlag); override; procedure SetBookmarkData(Buffer: PByte; Data: Pointer); override; procedure SetFieldData(Field: TField; Buffer: Pointer); overload; override; procedure SetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean); overload; override; procedure ActivateBuffers; override; procedure CreateFields; override; function GetRecordCount: Longint; override; function GetRecNo: Longint; override; public constructor Create(AOwner: TComponent);override; destructor Destroy;override; function GetFieldData(Field: TField; Buffer: Pointer): Boolean; overload; override; function GetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean): Boolean; overload; override; // added by DCA on 17/05/2013 {$IFDEF VER240} // XE3 function GetFieldData(Field: TField; Buffer: TValueBuffer): Boolean; overload; virtual; function GetFieldData(Field: TField; Buffer: TValueBuffer; NativeFormat: Boolean): Boolean; overload; override; {$ENDIF} function MoveBy(Distance: Integer): Integer;override; procedure Next; //function FieldbyName( fname : string ): TField; published property Active; property OnGetRecord : TQRAbsRecordEvent read FOnGetRecord write FOnGetRecord; property OnSetFieldValue : TQRDataAbsSetEvent read FOnSetFieldValue write FOnSetFieldValue; property RecordCount : longint read FRecordCount; property CurrentRecord : longint read FCurRecord; property DefFieldLen : integer read FDefFieldLen write FDefFieldLen default 50; property EOF : boolean read FEOF; property BOF : boolean read FBOF; property FieldDefs; property BeforeOpen; property AfterOpen; property BeforeClose; property AfterClose; property BeforeScroll; property AfterScroll; end; Function StripXChars( ss : string ) : string; implementation constructor TQRAbsTable.Create(AOwner: TComponent); begin inherited create( aOwner ); FFieldnames := TStringlist.create; FRecordSize := 5000; FLastGetOp := gmNext; end; destructor TQRAbsTable.Destroy; begin FFieldnames.free; inherited; end; function TQRAbsTable.GetRecno: Longint; begin result := FCurRecord; end; procedure TQRAbsTable.InternalOpen; begin if Active then exit; FFieldnames.Clear; FEOF := false; FBOF := true; FRecordcount := 0; InternalInitFieldDefs; Createfields; FCurRecord := 0; ActivateBuffers; end; function TQRAbsTable.Moveby( distance : integer ):integer; begin // required in post unicode versions inherited Moveby(distance); inc( FCurRecord, distance ); if FCurRecord < 0 then begin FCurRecord := 0; FBOF := true; FEOF := false; end; result := 0; end; procedure TQRAbsTable.InternalClose; begin //ClearData; DestroyFields; end; procedure TQRAbsTable.ClearData; begin FFieldnames.Clear; Fielddefs.Clear; FDoneFielddefs := false; end; procedure TQRAbsTable.CreateFields; begin inherited; end; function TQRAbsTable.AllocRecordBuffer: PByte; begin Result := AllocMem(FRecBufSize); end; procedure TQRAbsTable.FreeRecordBuffer(var Buffer: PByte); begin FreeMem( buffer ); end; procedure TQRAbsTable.GetBookmarkData(Buffer: PByte; Data: Pointer); begin end; function TQRAbsTable.GetBookmarkFlag(Buffer: PByte): TBookmarkFlag; begin result := bfBOF; end; procedure TQRAbsTable.Next; begin inc(FCurRecord); end; function TQRAbsTable.GetRecord(Buffer: PByte; GetMode: TGetMode; DoCheck: Boolean): TGetResult; begin result := grOK; FCurrentGetOp := getMode; if (FLastGetOp = gmPrior) and (FCurrentGetOp = gmNext)then begin // restore last record - don't call get data //copyMemory( buffer, FSwapBuffer, FRecBufSize); FLastGetOp := gmNext; exit; end; if getmode = gmPrior then begin dec(FCurRecord); if fcurrecord < 0 then begin fcurrecord := 0; result := grBOF; end; // back to previous data //copyMemory( FSwapBuffer, buffer, FRecBufSize); //copyMemory( buffer, FSavedBuffer, FRecBufSize); FLastGetOp := gmPrior; end else if getmode = gmNext then begin FMoredata := false; if assigned( FOnGetRecord) then FOnGetRecord( Self, FMoreData); // Here we test if the last Event has returned MoreData if Not FMoreData then begin // No more data needed => grEOF result := grEOF; exit; end; inc(FCurRecord); FLastGetOp := gmNext; end; end; function TQRAbsTable.GetRecordSize: Word; begin Result := FRecordSize; end; procedure TQRAbsTable.InternalAddRecord(Buffer: Pointer; Append: Boolean); begin // read only end; procedure TQRAbsTable.InternalDelete; begin // read only end; procedure TQRAbsTable.InternalFirst; begin FCurRecord := 0; // Two lines added here : FBOF := true; FEOF := false; end; procedure TQRAbsTable.InternalGotoBookmark(Bookmark: Pointer); begin end; procedure TQRAbsTable.InternalHandleException; begin end; procedure TQRAbsTable.InternalInitFieldDefs; begin //inherited InternalInitFieldDefs; FDoneFielddefs := true; end; procedure TQRAbsTable.InternalInitRecord(Buffer: PByte); begin end; procedure TQRAbsTable.InternalLast; begin //FCurRecord := FRecordcount; end; procedure TQRAbsTable.InternalPost; begin end; procedure TQRAbsTable.InternalSetToRecord(Buffer: PByte); begin end; function TQRAbsTable.IsCursorOpen: Boolean; begin result := FDoneFielddefs; end; procedure TQRAbsTable.SetBookmarkFlag(Buffer: PByte; Value: TBookmarkFlag); begin end; procedure TQRAbsTable.SetBookmarkData(Buffer: PByte; Data: Pointer); begin end; procedure TQRAbsTable.SetFieldData(Field: TField; Buffer: Pointer); begin end; procedure TQRAbsTable.SetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean); begin end; function TQRAbsTable.GetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean): Boolean; begin Result:=GetFieldData(Field,Buffer); end; function TQRAbsTable.GetFieldData(Field: TField; Buffer: Pointer): Boolean; var strval : string; begin try result := true; if FCurrentGetOp = gmPrior then exit; if (FLastGetOp = gmPrior) and (FCurrentGetOp = gmNext) then exit; if assigned(FOnSetFieldValue) then begin FOnSetFieldValue( strval, field, buffer ); // copy the buffer to the saved buffer //copyMemory(pchar(FSavedBuffer), PChar(buffer), FRecBufSize ); exit; end else strpcopy(pchar(Buffer), 'Unset' ); except result := false; FEOF := true; end; end; // added by DCA on 17/05/2013 {$IFDEF VER240} // XE3 function TQRAbsTable.GetFieldData(Field: TField; Buffer: TValueBuffer; NativeFormat: Boolean): Boolean; begin Result := GetFieldData(Field, Pointer(Buffer), NativeFormat); end; function TQRAbsTable.GetFieldData(Field: TField; Buffer: TValueBuffer): Boolean; begin Result := GetFieldData(Field, Pointer(Buffer)); end; {$ENDIF} // end of adding function TQRAbsTable.GetRecordCount: Longint; begin Result := FRecordCount; end; procedure TQRAbsTable.ActivateBuffers; begin inherited; end; //**************************** Utils ************************** function LastChar( ss : string ) : char; begin result := ss[ length(ss) ]; end; Function StripXChars( ss : string ) : string; begin if charInSet(lastchar( ss ), [ '+', '*', '?' ]) then result := copy( ss, 1, length(ss)-1) else result := ss; end; end.
unit udebug; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DateUtils, uLimitedStringList, Dialogs; procedure DebugLog(Usuario: string; API: string; Mensaje: string); procedure DebugLog(Usuario: string; API: string; OK: boolean); procedure InitLog; implementation var LastDebugTime: TDateTime; DebugFile: TLimitedStringList; DebugFileName: string; const LIMITE = 1000; procedure DebugLog(Usuario: string; API: string; Mensaje: string); var msBetween: int64; msNow: TDateTime; begin if not Assigned(DebugFile) then exit(); try msNow := Now; msBetween := MilliSecondsBetween(LastDebugTime, msNow); DebugFile.Append(Usuario + ' ' + DateTimeToStr(msNow) + ' ' + IntToStr(msBetween) + ' ' + API + ' ' + Mensaje); LastDebugTime := msNow; DebugFile.SaveToFile(DebugFileName); except on E: exception do begin // no hacer nada, no se pudo guardar el log end; end; end; procedure DebugLog(Usuario: string; API: string; OK: boolean); begin if (OK) then DebugLog(Usuario, API, 'OK') else DebugLog(Usuario, API, 'ERROR'); end; procedure InitLog; begin DebugFile := TLimitedStringList.Create(LIMITE); try LastDebugTime := Now; DebugFileName := GetAppConfigDir(False) + 'debug.log'; if FileExists(DebugFileName) then DebugFile.LoadFromFile(DebugFileName); DebugLog('FPC Paymo Widget', 'DEBUG_INIT', True); except on E: exception do begin // liberar DebugFile, los logs siguientes no se guardarán if Assigned(DebugFile) then DebugFile.Free; end; end; end; procedure EndLog; begin DebugLog('FPC Paymo Widget', 'DEBUG_END', True); if Assigned(DebugFile) then DebugFile.Free; end; finalization EndLog(); end.
unit Unit6; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm6 = class(TForm) Memo1: TMemo; Memo2: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form6: TForm6; implementation {$R *.dfm} uses IniFiles, System.DateUtils, System.Rtti, System.TypInfo; type { Fragmento de: System.Classes.Helper https://github.com/amarildolacerda/helpers/blob/master/System.Classes.Helper.pas } TMemberVisibilitySet = set of TMemberVisibility; // RTTI para pegar propriedades do object TObjectHelper = class helper for TObject private procedure GetPropertiesItems(AList: TStrings; const AVisibility: TMemberVisibilitySet); end; // Adiciona Uso de RTTI para o INI TCustomIniFileHelper = class Helper for TCustomIniFile private procedure WriteObject(const ASection: string; AObj: TObject); procedure ReadObject(const ASection: string; AObj: TObject); public end; // Adiciona funções ao TValue TValueHelper = record helper for TValue private function IsNumeric: Boolean; function IsFloat: Boolean; function AsFloat: Extended; function IsBoolean: Boolean; function IsDate: Boolean; function IsDateTime: Boolean; function IsDouble: Boolean; function AsDouble: Double; function IsInteger: Boolean; end; // Classe a ser gravar no INI TIniSecaoClass = class private Fbase_datetime: TDatetime; Fbase_numerico: Double; Fbase_string: string; Fbase_integer: integer; Fbase_boolean: Boolean; procedure Setbase_datetime(const Value: TDatetime); procedure Setbase_numerico(const Value: Double); procedure Setbase_string(const Value: string); procedure Setbase_integer(const Value: integer); procedure Setbase_boolean(const Value: Boolean); public // propriedades a serem gravadas ou lidas no INI property base_string: string read Fbase_string write Setbase_string; property base_datetime: TDatetime read Fbase_datetime write Setbase_datetime; property base_numerico: Double read Fbase_numerico write Setbase_numerico; property base_integer: integer read Fbase_integer write Setbase_integer; property base_boolean: Boolean read Fbase_boolean write Setbase_boolean; end; var obj: TIniSecaoClass; function TValueHelper.IsNumeric: Boolean; begin Result := Kind in [tkInteger, tkChar, tkEnumeration, tkFloat, tkWChar, tkInt64]; end; function TValueHelper.IsFloat: Boolean; begin Result := Kind = tkFloat; end; function TValueHelper.AsFloat: Extended; begin Result := AsType<Extended>; end; function TValueHelper.IsBoolean: Boolean; begin Result := TypeInfo = System.TypeInfo(Boolean); end; function TValueHelper.IsDate: Boolean; begin Result := TypeInfo = System.TypeInfo(TDate); end; function TValueHelper.IsDateTime: Boolean; begin Result := TypeInfo = System.TypeInfo(TDatetime); end; function TValueHelper.IsDouble: Boolean; begin Result := TypeInfo = System.TypeInfo(Double); end; function TValueHelper.AsDouble: Double; begin Result := AsType<Double>; end; function TValueHelper.IsInteger: Boolean; begin Result := TypeInfo = System.TypeInfo(integer); end; function ISODateTimeToString(ADateTime: TDatetime): string; var fs: TFormatSettings; begin fs.TimeSeparator := ':'; Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', ADateTime, fs); end; function ISOStrToDateTime(DateTimeAsString: string): TDatetime; begin Result := EncodeDateTime(StrToInt(Copy(DateTimeAsString, 1, 4)), StrToInt(Copy(DateTimeAsString, 6, 2)), StrToInt(Copy(DateTimeAsString, 9, 2)), StrToInt(Copy(DateTimeAsString, 12, 2)), StrToInt(Copy(DateTimeAsString, 15, 2)), StrToInt(Copy(DateTimeAsString, 18, 2)), 0); end; procedure TCustomIniFileHelper.WriteObject(const ASection: string; AObj: TObject); var aCtx: TRttiContext; AFld: TRttiProperty; AValue: TValue; begin aCtx := TRttiContext.Create; try for AFld in aCtx.GetType(AObj.ClassType).GetProperties do begin if AFld.Visibility in [mvPublic] then begin AValue := AFld.GetValue(AObj); if AValue.IsDate or AValue.IsDateTime then WriteString(ASection, AFld.Name, ISODateTimeToString(AValue.AsDouble)) else if AValue.IsBoolean then WriteBool(ASection, AFld.Name, AValue.AsBoolean) else if AValue.IsInteger then WriteInteger(ASection, AFld.Name, AValue.AsInteger) else if AValue.IsFloat or AValue.IsNumeric then WriteFloat(ASection, AFld.Name, AValue.AsFloat) else WriteString(ASection, AFld.Name, AValue.ToString); end; end; finally aCtx.free; end; end; procedure TCustomIniFileHelper.ReadObject(const ASection: string; AObj: TObject); var aCtx: TRttiContext; AFld: TRttiProperty; AValue, ABase: TValue; begin aCtx := TRttiContext.Create; try for AFld in aCtx.GetType(AObj.ClassType).GetProperties do begin if AFld.Visibility in [mvPublic] then begin ABase := AFld.GetValue(AObj); AValue := AFld.GetValue(AObj); if ABase.IsDate or ABase.IsDateTime then AValue := ISOStrToDateTime(ReadString(ASection, AFld.Name, ISODateTimeToString(ABase.AsDouble))) else if ABase.IsBoolean then AValue := ReadBool(ASection, AFld.Name, ABase.AsBoolean) else if ABase.IsInteger then AValue := ReadInteger(ASection, AFld.Name, ABase.AsInteger) else if ABase.IsFloat or ABase.IsNumeric then AValue := ReadFloat(ASection, AFld.Name, ABase.AsFloat) else AValue := ReadString(ASection, AFld.Name, ABase.asString); AFld.SetValue(AObj, AValue); end; end; finally aCtx.free; end; end; procedure TObjectHelper.GetPropertiesItems(AList: TStrings; const AVisibility: TMemberVisibilitySet); var aCtx: TRttiContext; aProperty: TRttiProperty; aRtti: TRttiType; AValue: TValue; begin AList.clear; aCtx := TRttiContext.Create; try aRtti := aCtx.GetType(self.ClassType); for aProperty in aRtti.GetProperties do begin if aProperty.Visibility in AVisibility then begin AValue := aProperty.GetValue(self); if AValue.IsDate or AValue.IsDateTime then AList.Add(aProperty.Name + '=' + ISODateTimeToString(AValue.AsDouble)) else if AValue.IsBoolean then AList.Add(aProperty.Name + '=' + ord(AValue.AsBoolean).ToString) else AList.Add(aProperty.Name + '=' + AValue.ToString); end; end; finally aCtx.free; end; end; procedure TForm6.Button1Click(Sender: TObject); begin obj.GetPropertiesItems(Memo1.lines, [mvPublic]); end; { TIniSecaoClass } procedure TIniSecaoClass.Setbase_boolean(const Value: Boolean); begin Fbase_boolean := Value; end; procedure TIniSecaoClass.Setbase_datetime(const Value: TDatetime); begin Fbase_datetime := Value; end; procedure TIniSecaoClass.Setbase_integer(const Value: integer); begin Fbase_integer := Value; end; procedure TIniSecaoClass.Setbase_numerico(const Value: Double); begin Fbase_numerico := Value; end; procedure TIniSecaoClass.Setbase_string(const Value: string); begin Fbase_string := Value; end; procedure TForm6.Button2Click(Sender: TObject); begin // grava o objeto OBJ no INI // inicializar OBJ antes de executar.... with TIniFile.Create('teste.ini') do try WriteObject('SecaoClass', obj); finally free; end; end; procedure TForm6.Button3Click(Sender: TObject); var i: integer; begin // Ler os dados gravados no INI - mostra no memo2 with TIniFile.Create('teste.ini') do try ReadSection('SecaoClass', Memo2.lines); for i := 0 to Memo2.lines.Count - 1 do Memo2.lines[i] := Memo2.lines[i] + '=' + ReadString('SecaoClass', Memo2.lines[i], ''); finally free; end; end; procedure TForm6.Button4Click(Sender: TObject); begin // Ler os dados do INI para o OBJ with TIniFile.Create('teste.ini') do try ReadObject('SecaoClass', obj); finally free; end; obj.GetPropertiesItems(Memo2.lines, [mvPublic]); end; procedure TForm6.Button5Click(Sender: TObject); var i: integer; begin // grava o memo1 no INI With TIniFile.Create('teste.ini') do try for i := 0 to Memo1.lines.Count - 1 do WriteString('SecaoClass', Memo1.lines.Names[i], Memo1.lines.ValueFromIndex[i]); finally free; end; end; initialization // Inicia o objecto a ser utilizado para gravar no INI obj := TIniSecaoClass.Create; with obj do begin base_string := 'meu teste'; base_datetime := now; base_numerico := 123.34; base_integer := 1234; end; finalization obj.free; end.
unit kwRGB2String; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwRGB2String.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::SysUtils::RGB2String // // Переводит представление R G B в шестнадцатиричное представление в виде строки: // {code} // 151 40 30 RGB2String . // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwSysUtilsWord.imp.pas} TkwRGB2String = {final} class(_tfwSysUtilsWord_) {* Переводит представление R G B в шестнадцатиричное представление в виде строки: [code] 151 40 30 RGB2String . [code] } protected // realized methods procedure DoDoIt(const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwRGB2String {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses Windows, Graphics, SysUtils, l3String, l3Base, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwRGB2String; {$Include ..\ScriptEngine\tfwSysUtilsWord.imp.pas} // start class TkwRGB2String procedure TkwRGB2String.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_503C792001BA_var* var l_SColor : AnsiString; l_Color : TColor; l_R, l_G, l_B: Byte; //#UC END# *4DAEEDE10285_503C792001BA_var* begin //#UC START# *4DAEEDE10285_503C792001BA_impl* l_B := aCtx.rEngine.PopInt; l_G := aCtx.rEngine.PopInt; l_R := aCtx.rEngine.PopInt; l_Color := TColor(RGB(l_R, l_G, l_B)); l_SColor := ColorToString(l_Color); aCtx.rEngine.PushString(l_SColor); //#UC END# *4DAEEDE10285_503C792001BA_impl* end;//TkwRGB2String.DoDoIt class function TkwRGB2String.GetWordNameForRegister: AnsiString; {-} begin Result := 'RGB2String'; end;//TkwRGB2String.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwSysUtilsWord.imp.pas} {$IfEnd} //not NoScripts end.
unit GX_CompRenameConfig; {$I GX_CondDefine.inc} interface uses Forms, StdCtrls, Classes, Controls, Messages, Grids, Menus, Dialogs, ActnList, ExtCtrls, GX_BaseForm; const UM_SHOW_CONTROL = WM_USER + 133; resourcestring SNotFound = 'not found: %s'; type TEditMode = (emRead, emEdit, emInsert); TRenameStringGrid = class(TStringGrid) private FComponents: TStringList; protected function GetEditStyle(ACol: Integer; ARow: Integer): TEditStyle; override; function CreateEditor: TInplaceEdit; override; procedure OnGetComponentList(ACol, ARow: Integer; Items: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TfmCompRenameConfig = class(TfmBaseForm) chkShowDialog: TCheckBox; chkAutoAdd: TCheckBox; pnlNames: TGroupBox; btnAdd: TButton; btnDelete: TButton; ActionList: TActionList; acAdd: TAction; acDelete: TAction; acFind: TAction; acCancel: TAction; pmGrid: TPopupMenu; mnuAdd: TMenuItem; mnuDelete: TMenuItem; mnuSep1: TMenuItem; mnuFind: TMenuItem; acOK: TAction; mnuSep2: TMenuItem; acSortByClass: TAction; acSortByRule: TAction; mnuSort: TMenuItem; mnuSortByClass: TMenuItem; mnuSortByRule: TMenuItem; FindDialog: TFindDialog; btnDefaults: TButton; pnlFooter: TPanel; pnlRules: TPanel; btnOtherProperties: TButton; acOtherProperties: TAction; mnuOtherProperties: TMenuItem; pnlButtonsRight: TPanel; btnOK: TButton; btnClose: TButton; btnHelp: TButton; procedure acOtherPropertiesExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormResize(Sender: TObject); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure acAddExecute(Sender: TObject); procedure acDeleteExecute(Sender: TObject); procedure acFindExecute(Sender: TObject); procedure acCancelExecute(Sender: TObject); procedure acOKExecute(Sender: TObject); procedure acSortByClassExecute(Sender: TObject); procedure acSortByRuleExecute(Sender: TObject); procedure GridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure GridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FindDialogFind(Sender: TObject); procedure btnDefaultsClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); private FValueList: TStringList; Grid: TRenameStringGrid; procedure CopyValuesToGrid; procedure CopyGridToValues; function IsEmptyRow(aGrid: TStringGrid; ARow: Integer): Boolean; function IsValidRule(ARow: Integer): Boolean; procedure GridDeleteRow(ARow: Integer); procedure GridAddRow; function RemoveEmptyBottomRow: Boolean; function RowHasComponent(aGrid: TStringGrid; ARow: Integer): Boolean; public property ValueList: TStringList read FValueList; function Execute: Boolean; end; implementation {$R *.dfm} uses Windows, SysUtils, GX_GenericUtils, GX_OtaUtils, GX_SharedImages, GX_GxUtils, GX_CompRenameAdvanced, Math; function CompareClassFunc(List: TStringList; Index1, Index2: Integer): Integer; var S1, S2: string; begin Assert(Assigned(List)); S1 := List.Names[Index1]; S2 := List.Names[Index2]; Result := AnsiCompareStr(S1, S2); end; function CompareRuleFunc(List: TStringList; Index1, Index2: Integer): Integer; var S1, S2: string; begin Assert(Assigned(List)); S1 := List.Values[List.Names[Index1]]; S2 := List.Values[List.Names[Index2]]; Result := AnsiCompareStr(S1, S2); end; { TfmCompRenameConfig } function TfmCompRenameConfig.Execute: Boolean; begin CopyValuesToGrid; Grid.Row := Grid.FixedRows; // Go to the bottom of grid Result := (ShowModal = mrOk); if Result then CopyGridToValues; end; procedure TfmCompRenameConfig.FormCreate(Sender: TObject); resourcestring ClassCaption = 'Class'; RenameRuleCaption = 'Rename Rule'; const GridPad = 8; begin Grid := TRenameStringGrid.Create(Self); with Grid do begin Name := 'Grid'; Parent := pnlNames; SetBounds(GridPad, GridPad * 2, pnlNames.Width - (GridPad*2) - (pnlNames.Width - btnAdd.Left), pnlNames.Height - (GridPad * 3)); Anchors := [akLeft, akTop, akRight, akBottom]; ColCount := 2; DefaultColWidth := 150; DefaultRowHeight := 17; FixedCols := 0; RowCount := 2; Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goEditing, goTabs, goAlwaysShowEditor, goThumbTracking]; PopupMenu := pmGrid; ScrollBars := ssVertical; TabOrder := 0; end; FValueList := TStringList.Create; Grid.Cells[0, 0] := ClassCaption; Grid.Cells[1, 0] := RenameRuleCaption; end; procedure TfmCompRenameConfig.FormDestroy(Sender: TObject); begin FreeAndNil(FValueList); end; procedure TfmCompRenameConfig.FormResize(Sender: TObject); begin if Assigned(Grid) then // Or Delphi 2009 crashes here... begin Grid.ColWidths[0] := (Grid.ClientWidth div 2) - 1; Grid.ColWidths[1] := Grid.ColWidths[0]; end; end; procedure TfmCompRenameConfig.CopyValuesToGrid; var i, YOffset, SavedRow: Integer; begin SavedRow := Grid.Row; YOffset := Grid.FixedRows; if Assigned(FValueList) then begin // Having only one row makes the fixed row paint wrong Grid.RowCount := Max(YOffset + FValueList.Count, 2); for i := 0 to FValueList.Count - 1 do begin Grid.Cells[0, YOffset + i] := FValueList.Names[i]; Grid.Cells[1, YOffset + i] := FValueList.Values[FValueList.Names[i]]; end; if SavedRow < Grid.RowCount then Grid.Row := SavedRow; end; FormResize(Self); end; procedure TfmCompRenameConfig.CopyGridToValues; var i: Integer; OrgValuelist: TStringList; Index: Integer; begin if Assigned(FValueList) then begin OrgValueList := FValueList; OrgValuelist.Sorted := True; FValueList := TStringList.Create; for i := Grid.FixedRows to Grid.RowCount - 1 do if Trim(Grid.Cells[0, i]) <> '' then FValueList.Add(Grid.Cells[0, i] + '=' + Grid.Cells[1, i]); for i := 0 to FValueList.Count - 1 do begin Index := OrgValuelist.IndexOfName(FValueList.Names[i]); if Index <> -1 then begin FValueList.Objects[i] := OrgValuelist.Objects[Index]; OrgValuelist.Objects[Index] := nil; end; end; for i := 0 to OrgValuelist.Count - 1 do OrgValuelist.Objects[i].Free; FreeAndNil(OrgValuelist); end; end; procedure TfmCompRenameConfig.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin acAdd.Enabled := IsValidRule(Grid.Row) and not IsEmptyRow(Grid, Grid.RowCount - 1); acDelete.Enabled := ((Grid.Row >= Grid.FixedRows) and (Grid.Row < Grid.RowCount)); acOtherProperties.Enabled := RowHasComponent(Grid, Grid.Row); end; procedure TfmCompRenameConfig.acAddExecute(Sender: TObject); begin TryFocusControl(Grid); GridAddRow; FormResize(Self); end; procedure TfmCompRenameConfig.acDeleteExecute(Sender: TObject); begin TryFocusControl(Grid); GridDeleteRow(Grid.Row); if Grid.RowCount <= Grid.FixedRows then GridAddRow; FormResize(Self); end; procedure TfmCompRenameConfig.acFindExecute(Sender: TObject); var P: TPoint; begin // Move the find dialog below the grid P := Point(pnlNames.Left, pnlNames.Top + pnlNames.Height); FindDialog.Position := pnlNames.ClientToScreen(P); FindDialog.Execute; end; procedure TfmCompRenameConfig.acCancelExecute(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfmCompRenameConfig.acOKExecute(Sender: TObject); begin ModalResult := mrOk; end; procedure TfmCompRenameConfig.acSortByClassExecute(Sender: TObject); begin CopyGridToValues; FValueList.CustomSort(CompareClassFunc); CopyValuesToGrid; end; procedure TfmCompRenameConfig.acSortByRuleExecute(Sender: TObject); begin CopyGridToValues; FValueList.CustomSort(CompareRuleFunc); CopyValuesToGrid; end; procedure TfmCompRenameConfig.GridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Shift = [] then begin case Key of VK_DOWN: begin // If we are at bottom of grid, add a new empty row if (Grid.Row = Grid.RowCount - 1) and not IsEmptyRow(Grid, Grid.Row) then Grid.RowCount := Grid.RowCount + 1; end; VK_UP: begin // If we are at the bottom of grid, and this is an empty row, remove it if RemoveEmptyBottomRow then Key := 0; end; end; { case } end; { if Shift } end; { GridKeyDown } function TfmCompRenameConfig.IsEmptyRow(aGrid: TStringGrid; ARow: Integer): Boolean; begin Result := Trim(aGrid.Rows[ARow].Text) = ''; end; function TfmCompRenameConfig.RowHasComponent(aGrid: TStringGrid; ARow: Integer): Boolean; begin Result := (Trim(Grid.Cells[0, ARow]) > ''); end; function TfmCompRenameConfig.IsValidRule(ARow: Integer): Boolean; begin Result := (Trim(Grid.Cells[0, ARow]) > '') and (Trim(Grid.Cells[1, ARow]) > ''); end; function TfmCompRenameConfig.RemoveEmptyBottomRow: Boolean; begin if IsEmptyRow(Grid, Grid.RowCount - 1) and (Grid.RowCount > Grid.FixedRows) then begin Grid.RowCount := Grid.RowCount - 1; Result := True; end else Result := False; end; procedure TfmCompRenameConfig.GridAddRow; begin Grid.RowCount := Grid.RowCount + 1; Application.ProcessMessages; Grid.Col := Grid.FixedCols; Grid.Row := Grid.RowCount - 1; end; procedure TfmCompRenameConfig.GridDeleteRow(ARow: Integer); var i, j: Integer; begin if ARow > Grid.FixedRows - 1 then begin if ARow < Grid.RowCount - 1 then begin // Move all cells one row up for i := ARow to Grid.RowCount - 2 do for j := 0 to Grid.ColCount - 1 do Grid.Cells[j, i] := Grid.Cells[j, i + 1]; end; // Delete the last row Grid.Rows[Grid.RowCount - 1].Clear; if Grid.RowCount > Grid.FixedRows + 1 then Grid.RowCount := Grid.RowCount - 1; end; end; procedure TfmCompRenameConfig.GridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if (ARow < Grid.Row) and IsEmptyRow(Grid, Grid.Row) then RemoveEmptyBottomRow; if (ACol > 0) and (Grid.Cells[0, ARow]='') then CanSelect := False; end; procedure TfmCompRenameConfig.GridMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var CellCoord: TGridCoord; begin CellCoord := Grid.MouseCoord(X, Y); if CellCoord.Y = 0 then begin case CellCoord.X of 0: acSortByClass.Execute; 1: acSortByRule.Execute; end; end; end; procedure TfmCompRenameConfig.FindDialogFind(Sender: TObject); var Index: Integer; FoundRow: Integer; FoundCol: Integer; FindMsg: string; begin Index := Grid.Row + 1; FoundRow := -1; FoundCol := 0; while (FoundRow < 0) and (Index < Grid.RowCount) do begin if CaseInsensitivePos(FindDialog.FindText, Grid.Cells[1, Index]) > 0 then begin FoundCol := 1; FoundRow := Index; end; if CaseInsensitivePos(FindDialog.FindText, Grid.Cells[0, Index]) > 0 then begin FoundCol := 0; FoundRow := Index; end; Inc(Index); end; if FoundRow >= 0 then begin Grid.Row := FoundRow; Grid.Col := FoundCol; Application.ProcessMessages; FindDialog.CloseDialog; end else begin FindMsg := Format(SNotFound, [FindDialog.FindText]); MessageDlg(FindMsg, mtInformation, [mbOK], 0); end; end; procedure TfmCompRenameConfig.btnDefaultsClick(Sender: TObject); begin with FValueList do begin Clear; Values['TAction'] := 'act'; Values['TBitBtn'] := 'btn'; Values['TButton'] := 'btn'; Values['TCheckBox'] := 'chk'; Values['TCheckListBox']:= 'lbx'; Values['TComboBox'] := 'cbx'; Values['TDrawGrid'] := 'grd'; Values['TEdit'] := 'edt'; Values['TGroupBox'] := 'gbx'; Values['TImage'] := 'img'; Values['TLabel'] := 'lbl'; Values['TListBox'] := 'lbx'; Values['TMaskEdit'] := 'edt'; Values['TMemo'] := 'mmo'; Values['TMenuItem'] := 'mnu'; Values['TPageControl'] := 'pag'; Values['TPanel'] := 'pnl'; Values['TRadioButton'] := 'rdo'; Values['TRadioGroup'] := 'rgp'; Values['TSpeedButton'] := 'btn'; Values['TStaticText'] := 'txt'; Values['TStringGrid'] := 'grd'; Values['TTabSheet'] := 'tab'; end; CopyValuesToGrid; chkShowDialog.Checked := False; chkAutoAdd.Checked := True; end; procedure TfmCompRenameConfig.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 42); end; procedure TfmCompRenameConfig.acOtherPropertiesExecute(Sender: TObject); function RemoveSpaces(const Value: string): string; begin Result := Value; Result := StringReplace(Result, ' =', '=', []); Result := StringReplace(Result, '= ', '=', []); end; var CompType: WideString; Dlg: TfmCompRenameAdvanced; Index: Integer; Additional: TStringList; i: Integer; begin CompType := Grid.Cells[0, Grid.Row]; Dlg := TfmCompRenameAdvanced.Create(Self); try Dlg.lblComponentClass.Caption := CompType; Index := FValueList.IndexOfName(CompType); if Index = -1 then Index := FValueList.Add(Grid.Cells[0, Grid.Row] + '=' + Grid.Cells[1, Grid.Row]); if Index <> -1 then begin Additional := FValueList.Objects[Index] as TStringList; if Assigned(Additional) then Dlg.mmoPropertyNames.Lines.Assign(Additional); if Dlg.ShowModal = mrOK then begin if Dlg.mmoPropertyNames.Lines.Count > 0 then begin if not Assigned(Additional) then Additional := TStringList.Create; Additional.Assign(Dlg.mmoPropertyNames.Lines); for i := 0 to Additional.Count - 1 do Additional[i] := RemoveSpaces(Additional[i]); FValueList.Objects[Index] := Additional; end else if Assigned(Additional) then begin FValueList.Objects[Index] := nil; FreeAndNil(Additional); end; end; end; finally FreeAndNil(Dlg); end; end; { TRenameStringGrid } constructor TRenameStringGrid.Create(AOwner: TComponent); begin inherited; FComponents := TStringList.Create; GxOtaGetInstalledComponentList(FComponents, False); end; destructor TRenameStringGrid.Destroy; begin FreeAndNil(FComponents); inherited; end; function TRenameStringGrid.CreateEditor: TInplaceEdit; begin Result := TInplaceEditList.Create(Self); (Result as TInplaceEditList).OnGetPickListitems := OnGetComponentList; (Result as TInplaceEditList).DropDownRows := 15; end; function TRenameStringGrid.GetEditStyle(ACol, ARow: Integer): TEditStyle; begin if ACol = 0 then Result := esPickList else Result := esSimple; end; procedure TRenameStringGrid.OnGetComponentList(ACol, ARow: Integer; Items: TStrings); begin Items.Assign(FComponents); end; end.
unit ATImage; interface uses Windows, Messages, Classes, Controls, Graphics, ExtCtrls, FBits, FTrack; //These are global flags (for all images) var FMapImagesStop: Boolean = False; //Disables drawing during dragging FMapImagesResample: Boolean = True; //Enables resampling on drawing type TATImageEx = class(TGraphicControl) private FBitmap: TBitmap; FTimer: TTimer; FBitsObject: TBitsObject; FXOffset: Integer; FYOffset: Integer; FScale: Extended; procedure TimerTimer(Sender: TOBject); procedure PaintResampled; procedure PaintBitmaps(LastOnly: Boolean = False); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; constructor CreateObj(AOwner: TComponent; ABitsObject: TBitsObject); //Creates object with Bits object attached destructor Destroy; override; procedure PaintLast; procedure LoadFromFile(const fn: string); function ImageWidth: integer; function ImageHeight: integer; property XOffset: Integer read FXOffset write FXOffset; property YOffset: Integer read FYOffset write FYOffset; property Scale: Extended read FScale write FScale; published property OnMouseDown; property OnMouseUp; property OnMouseMove; end; function IMax(N1, N2: Integer): Integer; function IMin(N1, N2: Integer): Integer; implementation uses SysUtils, Jpeg; { TATImageEx } constructor TATImageEx.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; Width := 20; Height := 20; end; constructor TATImageEx.CreateObj(AOwner: TComponent; ABitsObject: TBitsObject); begin Create(AOwner); FBitsObject := ABitsObject; FBitmap := TBitmap.Create; FBitmap.PixelFormat := pf24bit; FBitmap.Width := 20; FBitmap.Height := 20; FTimer := TTimer.Create(Self); FTimer.Interval := 500; FTimer.OnTimer := TimerTimer; FTimer.Enabled := False; FXOffset := 0; FYOffset := 0; FScale := 1.0; end; destructor TATImageEx.Destroy; begin FTimer.Enabled := False; FreeAndNil(FTimer); FreeAndNil(FBitmap); inherited; end; procedure TATImageEx.Paint; begin if FMapImagesStop then begin inherited Canvas.Brush.Color := clWhite; inherited Canvas.FillRect(ClientRect); Exit; end; with inherited Canvas do StretchDraw(ClientRect, FBitmap); PaintBitmaps; if FMapImagesResample then begin FTimer.Enabled := False; FTimer.Enabled := True; end; end; procedure TATImageEx.TimerTimer; begin FTimer.Enabled := False; PaintResampled; end; procedure TATImageEx.PaintResampled; begin with inherited Canvas do begin SetStretchBltMode(Handle, STRETCH_HALFTONE); SetBrushOrgEx(Handle, 0, 0, nil); StretchBlt( Handle, 0, 0, ClientWidth, ClientHeight, FBitmap.Canvas.Handle, 0, 0, FBitmap.Width, FBitmap.Height, SRCCOPY); end; PaintBitmaps; end; procedure TATImageEx.PaintLast; begin PaintBitmaps(True); end; //--------------------------- function IMax(N1, N2: Integer): Integer; begin if N1 >= N2 then Result := N1 else Result := N2; end; function IMin(N1, N2: Integer): Integer; begin if N1 <= N2 then Result := N1 else Result := N2; end; //--------------------------- procedure TATImageEx.PaintBitmaps; var i, iFrom, n: Integer; XX1, YY1, XX2, YY2: Integer; TextX, TextY: Integer; Bitmap: TBitmap; IL: TImageList; ACanvas: TCanvas; DestRect: TRect; begin ACanvas := inherited Canvas; DestRect := ClientRect; if LastOnly then iFrom := IMax(fBitsobject.FBitsCount - 1, 0) else iFrom := 0; //Draw tracks first for i := iFrom to fBitsobject.FBitsCount - 1 do with fBitsobject.FBits[i] do begin if Typ = bbTrack then begin Assert(Assigned(Data), 'Track not assigned'); ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := Color; ACanvas.Pen.Width := Size; ACanvas.Brush.Style := bsClear; ACanvas.Brush.Color := Color; with TTrackInfo(Data) do if FCount > 0 then begin for n := 0 to FCount - 1 do begin XX1 := -XOffset + Trunc((FData[n].X) * FScale); YY1 := -YOffset + Trunc((FData[n].Y) * FScale); //Line if n > 0 then ACanvas.LineTo(XX1, YY1); ACanvas.MoveTo(XX1, YY1); //Dot ACanvas.Pen.Width := 1; ACanvas.Pie( XX1 - Size2, YY1 - Size2, XX1 + Size2, YY1 + Size2, 0, 0, 0, 0); ACanvas.Pen.Width := Size; end; end; end; end; //Other for i := iFrom to FBitsObject.FBitsCount - 1 do with FBitsObject.FBits[i] do begin XX1 := -XOffset + Trunc((X1) * FScale); YY1 := -YOffset + Trunc((Y1) * FScale); XX2 := -XOffset + Trunc((X2) * FScale); YY2 := -YOffset + Trunc((Y2) * FScale); case Typ of bbBitmap: begin Bitmap := TBitmap(Data); Assert(Assigned(Bitmap), 'Bitmap not assigned'); ACanvas.Draw( XX1 - Bitmap.Width div 2, YY1 - Bitmap.Height div 2, TBitmap(Data)); end; bbILIcon: begin IL := TImageList(Data); Assert(Assigned(IL), 'Imagelist not assigned'); IL.Draw(ACanvas, XX1 - IL.Width div 2, YY1 - IL.Height div 2, Integer(Color)); end; bbLine: begin ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := Color; ACanvas.Pen.Width := Size; ACanvas.MoveTo(XX1, YY1); ACanvas.LineTo(XX2, YY2); end; bbOval: begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := Color; ACanvas.Pen.Width := Size; ACanvas.Ellipse(XX1, YY1, XX2, YY2); end; bbPoint: begin ACanvas.Brush.Style := bsClear; ACanvas.Brush.Color := Color; ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := Color; ACanvas.Pen.Width := 1; ACanvas.Pie( XX1 - Size, YY1 - Size, XX1 + Size, YY1 + Size, 0, 0, 0, 0); end; bbLabel: begin ACanvas.Brush.Style := bsClear; ACanvas.Brush.Color := Color2; ACanvas.Font.Color := Color; ACanvas.Font.Name := Font; ACanvas.Font.Size := Size; ACanvas.Font.Style := Style; TextX := XX1 + cBitTextOff; TextY := YY1 - ACanvas.TextHeight(Text) div 2; ACanvas.FillRect(Rect(TextX, TextY, TextX + ACanvas.TextWidth(Text), TextY + ACanvas.TextHeight(Text))); ACanvas.TextOut(TextX, TextY, Text); end; end; end; end; //--------------------------- function TATImageEx.ImageWidth: integer; begin if Assigned(FBitmap) then Result := FBitmap.Width else Result := 0; end; function TATImageEx.ImageHeight: integer; begin if Assigned(FBitmap) then Result := FBitmap.Height else Result := 0; end; //--------------------------- procedure TATImageEx.LoadFromFile(const fn: string); var j: TJpegImage; begin j := TJpegImage.Create; try try j.LoadFromFile(fn); FBitmap.Assign(j); finally j.Free; end; except raise Exception.Create('Cannot load image: "'+ fn + '"'); end; end; end.
unit SelectDateForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, frmDateSelect; type TSelectDateForm = class(TForm) frDates: TfrmRequestDate; pnlBTNS: TPanel; Panel1: TPanel; bbOk: TBitBtn; bbCancel: TBitBtn; procedure frDatessgCalendarDblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } fHOUSE: Integer; fTYPE: Integer; procedure SetHouse(Value: Integer); procedure SetType(Value: Integer); function GetSelectedDate: TDate; public property House: Integer write SetHouse; property RTYPE: Integer write SetType; property SelectedDate: TDate read GetSelectedDate; end; function SelectRequestDate(const HOUSE_ID: Integer; const TYPE_ID: Integer; var Date: TDate): Boolean; implementation {$R *.dfm} function SelectRequestDate(const HOUSE_ID: Integer; const TYPE_ID: Integer; var Date: TDate): Boolean; begin Result := False; with TSelectDateForm.Create(Application) do try House := HOUSE_ID; RTYPE := TYPE_ID; if ShowModal = mrOk then begin Date := SelectedDate; Result := True; end; finally Free; end; end; procedure TSelectDateForm.SetHouse(Value: Integer); begin fHOUSE := Value; frDates.House := Value; end; procedure TSelectDateForm.SetType(Value: Integer); begin fTYPE := Value; frDates.RTYPE := Value; end; procedure TSelectDateForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then ModalResult := mrOk; end; procedure TSelectDateForm.frDatessgCalendarDblClick(Sender: TObject); begin ModalResult := mrOk; end; function TSelectDateForm.GetSelectedDate: TDate; begin Result := frDates.SelectedDate; end; end.
unit ce_interfaces; {$I ce_defines.inc} interface uses Classes, SysUtils, actnList, menus, process, ce_synmemo, ce_project, ce_observer; type (** * An implementer declares some actions on demand. *) ICEContextualActions = interface ['ICEContextualActions'] // declares a context name for the actions function contextName: string; // action count, called before contextAction() function contextActionCount: integer; // declares actions, called in loop, from 0 to contextActionCount-1 function contextAction(index: integer): TAction; end; (** * An implementer is informed about the current file(s). *) ICEMultiDocObserver = interface ['ICEMultiDocObserver'] // aDoc has been created (empty, runnable, project source, ...). procedure docNew(aDoc: TCESynMemo); // aDoc is the document being edited. procedure docFocused(aDoc: TCESynMemo); // aDoc content has just been modified (edited, saved). procedure docChanged(aDoc: TCESynMemo); // aDoc is about to be closed. procedure docClosing(aDoc: TCESynMemo); end; (** * An implementer informs some ICEMultiDocObserver about the current file(s) *) TCEMultiDocSubject = class(TCECustomSubject) protected function acceptObserver(aObject: TObject): boolean; override; end; (** * An implementer is informed about the current project(s). *) ICEProjectObserver = interface ['ICEProjectObserver'] // aProject has been created/opened procedure projNew(aProject: TCEProject); // aProject has been modified: switches, source name, ... procedure projChanged(aProject: TCEProject); // aProject is about to be closed. procedure projClosing(aProject: TCEProject); // not called yet: aProject is always the same procedure projFocused(aProject: TCEProject); // aProject is about to be compiled procedure projCompiling(aProject: TCEProject); end; (** * An implementer informs some ICEProjectObserver about the current project(s) *) TCEProjectSubject = class(TCECustomSubject) protected function acceptObserver(aObject: TObject): boolean; override; end; (** * An implementer can add a main menu entry. *) ICEMainMenuProvider = interface ['ICEMainMenuProvider'] // item is a new mainMenu entry. item must be filled with the sub-items to be added. procedure menuDeclare(item: TMenuItem); // item is the mainMenu entry declared previously. the sub items can be updated, deleted. procedure menuUpdate(item: TMenuItem); end; (** * An implementer collects and updates its observers menus. *) TCEMainMenuSubject = class(TCECustomSubject) protected function acceptObserver(aObject: TObject): boolean; override; end; (** * An implementer declares some actions which have their own main menu entry and * whose shortcuts are automatically handled *) ICEActionProvider = interface ['ICEActionProvider'] // the action handler will clear the references to the actions collected previously and start collecting if result. function actHandlerWantRecollect: boolean; // the action handler starts to collect the actions if result. function actHandlerWantFirst: boolean; // the handler continue collecting action if result. function actHandlerWantNext(out category: string; out action: TCustomAction): boolean; // the handler update the state of a particular action. procedure actHandleUpdater(action: TCustomAction); end; (** * An implementer handles its observers actions. *) TCEActionProviderSubject = class(TCECustomSubject) protected function acceptObserver(aObject: TObject): boolean; override; end; (** * An implementer can expose some customizable shortcuts to be edited in a dedicated widget. *) ICEEditableShortCut = interface ['ICEEditableShortCut'] // a TCEEditableShortCutSubject will start to collect shortcuts if result function scedWantFirst: boolean; // a TCEEditableShortCutSubject collects the information on the shortcuts while result function scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; // a TCEEditableShortCutSubject sends the possibly modified shortcut procedure scedSendItem(const category, identifier: string; aShortcut: TShortcut); end; (** * An implementer manages its observers shortcuts. *) TCEEditableShortCutSubject = class(TCECustomSubject) protected function acceptObserver(aObject: TObject): boolean; override; end; // the option editor uses this value as a hint to cast and display an option container. TOptionEditorKind = (oekGeneric, oekForm, oekControl); // event generated by the option editor and passed to an ICEEditableOptions. // the oeeChange event only happends if the container is oekGeneric. TOptionEditorEvent = (oeeCancel, oeeAccept, oeeChange, oeeSelectCat); (** * An implementer can expose some options to be edited in a dedicated widget. *) ICEEditableOptions = interface ['ICEEditableOptions'] // the widget wants the category. function optionedWantCategory(): string; // the widget wants to know if the options will use a generic editor or a custom form. function optionedWantEditorKind: TOptionEditorKind; // the widget wants the custom option editor TCustomForm, TWinControl or the TPersistent containing the options. function optionedWantContainer: TPersistent; // the option editor informs that something has happened. procedure optionedEvent(anEvent: TOptionEditorEvent); // the option editor wants to know if an editor allows another category to be displayed (not called for oekGeneric). function optionedOptionsModified: boolean; end; (** * An implementer displays its observers editable options. *) TCEEditableOptionsSubject = class(TCECustomSubject) protected function acceptObserver(aObject: TObject): boolean; override; end; /// describes the message kind, 'amkAuto' implies that an ICELogMessageObserver guess the kind. TCEAppMessageKind = (amkAuto, amkBub, amkInf, amkHint, amkWarn, amkErr); /// describes the message context. Used by a ICELogMessageObserver to filter the messages. TCEAppMessageCtxt = (amcAll, amcEdit, amcProj, amcApp, amcMisc); (** * Single service provided by the messages widget. *) ICEMessagesDisplay = interface(ICESingleService) // displays a message procedure message(const aValue: string; aData: Pointer; aCtxt: TCEAppMessageCtxt; aKind: TCEAppMessageKind); // clears the messages related to the context aCtxt. procedure clearByContext(aCtxt: TCEAppMessageCtxt); // clears the messages related to the data aData. procedure clearByData(aData: Pointer); end; (** * Single service provided by the process-input widget. *) ICEProcInputHandler = interface(ICESingleService) // add an entry to the list of process which can receive an user input. procedure addProcess(aProcess: TProcess); // removes an entry. procedure removeProcess(aProcess: TProcess); // indicates the current process function process: TProcess; end; (** * Single service related to the documents as a collection. *) ICEMultiDocHandler = interface(ICESingleService) // returns the count of opened document function documentCount: Integer; // returns the index-th document function getDocument(index: Integer): TCESynMemo; // returns true if the document matching aFielanme is already opened. function findDocument(aFilename: string): TCESynMemo; // open or set the focus on the document matching aFilename procedure openDocument(aFilename: string); // close the index-th document function closeDocument(index: Integer): boolean; // conveniance property property document[index: integer]: TCESynMemo read getDocument; end; (** * Single service provided by the library manager * In both cases, if someAliases is empty then all the available entries are passed. *) ICELibraryInformer = interface(ICESingleService) // fills aList with the filenames of the static libraries matching to someAliases content. procedure getLibsFiles(someAliases: TStrings; aList: TStrings); // fills aList with the path to static libraries sources matching to someAliases content. procedure getLibsPaths(someAliases: TStrings; aList: TStrings); // fills aList with all the available libraries aliases. procedure getLibsAliases(aList: TStrings); end; { subject primitives: A subject cannot necessarly provides all the informations the observers expect. It can compose using the following "primitives". } (** * TCEMultiDocSubject primitives. *) procedure subjDocNew(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjDocClosing(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjDocFocused(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjDocChanged(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); {$IFDEF RELEASE}inline;{$ENDIF} (** * TCEProjectSubject primitives. *) procedure subjProjNew(aSubject: TCEProjectSubject; aProj: TCEProject); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjProjClosing(aSubject: TCEProjectSubject; aProj: TCEProject); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjProjFocused(aSubject: TCEProjectSubject; aProj: TCEProject); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjProjChanged(aSubject: TCEProjectSubject; aProj: TCEProject); {$IFDEF RELEASE}inline;{$ENDIF} procedure subjProjCompiling(aSubject: TCEProjectSubject; aProj: TCEProject);{$IFDEF RELEASE}inline;{$ENDIF} { Service getters: The first overload assign the variable only when not yet set, the second is designed for a punctual usage, for example if a widget needs the service in a single and rarely called method. } function getMessageDisplay(var obj: ICEMessagesDisplay): ICEMessagesDisplay; overload; function getMessageDisplay: ICEMessagesDisplay; overload; function getprocInputHandler(var obj: ICEProcInputHandler): ICEProcInputHandler; overload; function getprocInputHandler: ICEProcInputHandler; overload; function getMultiDocHandler(var obj: ICEMultiDocHandler): ICEMultiDocHandler; overload; function getMultiDocHandler: ICEMultiDocHandler; overload; function getLibraryInformer(var obj: ICELibraryInformer): ICELibraryInformer; overload; function getLibraryInformer: ICELibraryInformer; overload; implementation {$REGION TCEMultiDocSubject ----------------------------------------------------} function TCEMultiDocSubject.acceptObserver(aObject: TObject): boolean; begin exit(aObject is ICEMultiDocObserver); end; procedure subjDocNew(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEMultiDocObserver).docNew(aDoc); end; procedure subjDocClosing(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEMultiDocObserver).docClosing(aDoc); end; procedure subjDocFocused(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEMultiDocObserver).docFocused(aDoc); end; procedure subjDocChanged(aSubject: TCEMultiDocSubject; aDoc: TCESynMemo); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEMultiDocObserver).docChanged(aDoc); end; {$ENDREGION} {$REGION TCEProjectSubject -----------------------------------------------------} function TCEProjectSubject.acceptObserver(aObject: TObject): boolean; begin exit(aObject is ICEProjectObserver); end; procedure subjProjNew(aSubject: TCEProjectSubject; aProj: TCEProject); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEProjectObserver).ProjNew(aProj); end; procedure subjProjClosing(aSubject: TCEProjectSubject; aProj: TCEProject); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEProjectObserver).projClosing(aProj); end; procedure subjProjFocused(aSubject: TCEProjectSubject; aProj: TCEProject); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEProjectObserver).projFocused(aProj); end; procedure subjProjChanged(aSubject: TCEProjectSubject; aProj: TCEProject); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEProjectObserver).projChanged(aProj); end; procedure subjProjCompiling(aSubject: TCEProjectSubject; aProj: TCEProject); var i: Integer; begin with aSubject do for i:= 0 to fObservers.Count-1 do (fObservers.Items[i] as ICEProjectObserver).projCompiling(aProj); end; {$ENDREGION} {$REGION Misc subjects ---------------------------------------------------------} function TCEMainMenuSubject.acceptObserver(aObject: TObject): boolean; begin exit(aObject is ICEMainMenuProvider); end; function TCEEditableShortCutSubject.acceptObserver(aObject: TObject): boolean; begin exit(aObject is ICEEditableShortCut); end; function TCEEditableOptionsSubject.acceptObserver(aObject: TObject): boolean; begin exit(aObject is ICEEditableOptions); end; function TCEActionProviderSubject.acceptObserver(aObject: TObject): boolean; begin exit(aObject is ICEActionProvider); end; {$ENDREGION} {$REGION ICESingleService getters ----------------------------------------------} function getMessageDisplay(var obj: ICEMessagesDisplay): ICEMessagesDisplay; begin if obj = nil then obj := EntitiesConnector.getSingleService('ICEMessagesDisplay') as ICEMessagesDisplay; exit(obj); end; function getMessageDisplay: ICEMessagesDisplay; begin exit(EntitiesConnector.getSingleService('ICEMessagesDisplay') as ICEMessagesDisplay); end; function getprocInputHandler(var obj: ICEProcInputHandler): ICEProcInputHandler; begin if obj = nil then obj := EntitiesConnector.getSingleService('ICEProcInputHandler') as ICEProcInputHandler; exit(obj); end; function getprocInputHandler: ICEProcInputHandler; begin exit(EntitiesConnector.getSingleService('ICEProcInputHandler') as ICEProcInputHandler); end; function getMultiDocHandler(var obj: ICEMultiDocHandler): ICEMultiDocHandler; begin if obj = nil then obj := EntitiesConnector.getSingleService('ICEMultiDocHandler') as ICEMultiDocHandler; exit(obj); end; function getMultiDocHandler: ICEMultiDocHandler; begin exit(EntitiesConnector.getSingleService('ICEMultiDocHandler') as ICEMultiDocHandler); end; function getLibraryInformer(var obj: ICELibraryInformer): ICELibraryInformer; begin if obj = nil then obj := EntitiesConnector.getSingleService('ICELibraryInformer') as ICELibraryInformer; exit(obj); end; function getLibraryInformer: ICELibraryInformer; begin exit(EntitiesConnector.getSingleService('ICELibraryInformer') as ICELibraryInformer); end; {$ENDREGION} end.
{$define PROFILE} unit ItemEdit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,Planner, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CurvyControls, W7Classes, W7Bars, PAFPlanner, AdvGlassButton, AdvSmoothPanel; type TPafEditForm = class(TCustomItemeditor) W7InformationBar1: TW7InformationBar; CurvyPanel1: TCurvyPanel; CeNamn: TCurvyEdit; CurvyCombo1: TCurvyCombo; CePnr: TCurvyEdit; ButtonOK: TAdvGlassButton; CeTdbUsr: TCurvyEdit; CeUndLak: TCurvyEdit; CmAnamnes: TCurvyMemo; CeProdkod: TCurvyEdit; CeProdtext: TCurvyEdit; CEFragetext: TCurvyEdit; procedure FormCreate(Sender: TObject); procedure ButtonOKClick(Sender: TObject); private { Private declarations } FItem: TMyPAFItem; public { Public declarations } procedure CreateEditor(AOwner: TComponent); override; function Execute: Integer; override; property Item: TMyPAFItem read FItem write FItem; procedure PlannerItemToEdit(APlannerItem: TMyPAFItem); procedure EditToPlannerItem(APlannerItem: TPlannerItem); override; end; //var ItemEditForm: TPafEditForm; procedure Register; implementation {$R *.dfm} procedure Register; begin RegisterComponents('PAF-TMS', [TPafEditForm]); end; procedure TPafEditForm.ButtonOKClick(Sender: TObject); begin // FItem.Notes:= CmNotes.Lines.Text; //FItem.TdbUsr := CeTdbUsr.Text; //Close; end; procedure TPafEditForm.CreateEditor(AOwner: TComponent); begin inherited; FormCreate(AOwner); end; procedure TPafEditForm.EditToPlannerItem(APlannerItem: TPlannerItem); begin inherited; // Skriv åter det som kan editeras till planner end; function TPafEditForm.Execute: Integer; begin { CmAnamnes.Lines.Clear; CePnr.Text := LocalItem.Pafdata.pid; CeNamn.Text := LocalItem.PafData.PatNamn; // OBS namnet måste fixas !! CeProdkod.Text := LocalItem.PafData.Prodkod; CeProdtext.Text := LocalItem.PafData.Prodtext; //CEFragetext.Text := FItem.FrageText; CmAnamnes.Lines.Add(LocalItem.PafData.Anamnes); CeTdbUsr.Text := LocalItem.PafData.TdbUsr; CeUndLak.Text := LocalItem.PafData.UndLak; ItemEditForm.ShowModal; } Result:=0; end; procedure TPafEditForm.FormCreate(Sender: TObject); begin // FItem:= //CmAnamnes.Lines.Clear; end; procedure TPafEditForm.PlannerItemToEdit(APlannerItem: TMyPAFItem); begin //inherited; CmAnamnes.Lines.Clear; CePnr.Text := APlannerItem.pid; CeNamn.Text := APlannerItem.PatNamn; // OBS namnet måste fixas !! CeProdkod.Text := APlannerItem.Prodkod; CeProdtext.Text := APlannerItem.Prodtext; //CEFragetext.Text := FItem.FrageText; CmAnamnes.Lines.Add(APlannerItem.PafData.Anamnes); CeTdbUsr.Text := APlannerItem.PafData.TdbUsr; CeUndLak.Text := APlannerItem.PafData.UndLak; end; end.
{$IfNDef vcmChromeLikeTabUpdater_imp} // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Visual\ChromeLike\vcmChromeLikeTabUpdater.imp.pas" // Стереотип: "Impurity" // Элемент модели: "vcmChromeLikeTabUpdater" MUID: (53B6495D0309) // Имя типа: "_vcmChromeLikeTabUpdater_" {$Define vcmChromeLikeTabUpdater_imp} {$If NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} _vcmChromeLikeTabUpdater_ = class(_vcmChromeLikeTabUpdater_Parent_, IvcmFormSetIconProvider) private f_LastUpdatedUserType: TvcmUserType; f_WasUpdate: Boolean; f_LastUpdatedCaption: IvcmCString; protected function DoGetFormSetImageIndex: Integer; virtual; abstract; procedure UpdateChromeLikeTab; function NeedUpdateChromeLikeTab: Boolean; virtual; function NeedUpdateChromeLikeTabCaption(const aCaption: IvcmCString): Boolean; virtual; procedure UpdateChromeLikeTabCaption(const aCaption: IvcmCString); function pm_GetFormSetImageIndex: Integer; function pm_GetCanDefineFormSetIcon: Boolean; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoInit(aFromHistory: Boolean); override; {* Инициализация формы. Для перекрытия в потомках } function InsertForm(const aForm: IvcmEntityForm): Boolean; override; end;//_vcmChromeLikeTabUpdater_ {$Else NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} _vcmChromeLikeTabUpdater_ = _vcmChromeLikeTabUpdater_Parent_; {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs) {$Else vcmChromeLikeTabUpdater_imp} {$IfNDef vcmChromeLikeTabUpdater_imp_impl} {$Define vcmChromeLikeTabUpdater_imp_impl} {$If NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} procedure _vcmChromeLikeTabUpdater_.UpdateChromeLikeTab; //#UC START# *53B6800D01AC_53B6495D0309_var* //#UC END# *53B6800D01AC_53B6495D0309_var* begin //#UC START# *53B6800D01AC_53B6495D0309_impl* {$If not defined(Admin) AND not defined(Monitorings)} if NeedUpdateChromeLikeTab then begin TvcmTabbedContainerFormDispatcher.Instance.UpdateTab(As_IvcmEntityForm); f_LastUpdatedUserType := UserType; f_WasUpdate := True; end; {$IfEnd} //#UC END# *53B6800D01AC_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.UpdateChromeLikeTab function _vcmChromeLikeTabUpdater_.NeedUpdateChromeLikeTab: Boolean; //#UC START# *53B6803301BD_53B6495D0309_var* //#UC END# *53B6803301BD_53B6495D0309_var* begin //#UC START# *53B6803301BD_53B6495D0309_impl* {$If not defined(Admin) AND not defined(Monitorings)} Result := (TvcmTabbedContainerFormDispatcher.Instance.NeedUseTabs) AND ((f_LastUpdatedUserType <> UserType) OR (not f_WasUpdate)); {$Else not defined(Admin) AND not defined(Monitorings)} Result := False; {$IfEnd} //#UC END# *53B6803301BD_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.NeedUpdateChromeLikeTab function _vcmChromeLikeTabUpdater_.NeedUpdateChromeLikeTabCaption(const aCaption: IvcmCString): Boolean; //#UC START# *53BCF20B013C_53B6495D0309_var* //#UC END# *53BCF20B013C_53B6495D0309_var* begin //#UC START# *53BCF20B013C_53B6495D0309_impl* {$If not defined(Admin) AND not defined(Monitorings)} Result := (f_LastUpdatedCaption = nil) OR l3IsNil(f_LastUpdatedCaption) OR (not l3Same(f_LastUpdatedCaption, aCaption, True)); {$Else not defined(Admin) AND not defined(Monitorings)} Result := False; {$IfEnd} //#UC END# *53BCF20B013C_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.NeedUpdateChromeLikeTabCaption procedure _vcmChromeLikeTabUpdater_.UpdateChromeLikeTabCaption(const aCaption: IvcmCString); //#UC START# *53BCF25E00F4_53B6495D0309_var* //#UC END# *53BCF25E00F4_53B6495D0309_var* begin //#UC START# *53BCF25E00F4_53B6495D0309_impl* {$If not defined(Admin) AND not defined(Monitorings)} if NeedUpdateChromeLikeTabCaption(aCaption) then begin TvcmTabbedContainerFormDispatcher.Instance.UpdateTabCaption(As_IvcmEntityForm, aCaption); f_LastUpdatedCaption := aCaption; end; {$IfEnd} //#UC END# *53BCF25E00F4_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.UpdateChromeLikeTabCaption function _vcmChromeLikeTabUpdater_.pm_GetFormSetImageIndex: Integer; //#UC START# *53B649240001_53B6495D0309get_var* //#UC END# *53B649240001_53B6495D0309get_var* begin //#UC START# *53B649240001_53B6495D0309get_impl* Result := DoGetFormSetImageIndex; //#UC END# *53B649240001_53B6495D0309get_impl* end;//_vcmChromeLikeTabUpdater_.pm_GetFormSetImageIndex function _vcmChromeLikeTabUpdater_.pm_GetCanDefineFormSetIcon: Boolean; //#UC START# *54460951001B_53B6495D0309get_var* //#UC END# *54460951001B_53B6495D0309get_var* begin //#UC START# *54460951001B_53B6495D0309get_impl* Result := True; //#UC END# *54460951001B_53B6495D0309get_impl* end;//_vcmChromeLikeTabUpdater_.pm_GetCanDefineFormSetIcon procedure _vcmChromeLikeTabUpdater_.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_53B6495D0309_var* //#UC END# *479731C50290_53B6495D0309_var* begin //#UC START# *479731C50290_53B6495D0309_impl* f_LastUpdatedCaption := nil; inherited; //#UC END# *479731C50290_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.Cleanup procedure _vcmChromeLikeTabUpdater_.DoInit(aFromHistory: Boolean); {* Инициализация формы. Для перекрытия в потомках } //#UC START# *49803F5503AA_53B6495D0309_var* //#UC END# *49803F5503AA_53B6495D0309_var* begin //#UC START# *49803F5503AA_53B6495D0309_impl* inherited; f_LastUpdatedUserType := vcm_utAny; f_WasUpdate := False; f_LastUpdatedCaption := nil; //#UC END# *49803F5503AA_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.DoInit function _vcmChromeLikeTabUpdater_.InsertForm(const aForm: IvcmEntityForm): Boolean; //#UC START# *4AD44CA20001_53B6495D0309_var* //#UC END# *4AD44CA20001_53B6495D0309_var* begin //#UC START# *4AD44CA20001_53B6495D0309_impl* Result := inherited InsertForm(aForm); {$If not defined(Admin) AND not defined(Monitorings)} if Result then UpdateChromeLikeTab; {$IfEnd} //#UC END# *4AD44CA20001_53B6495D0309_impl* end;//_vcmChromeLikeTabUpdater_.InsertForm {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs) {$EndIf vcmChromeLikeTabUpdater_imp_impl} {$EndIf vcmChromeLikeTabUpdater_imp}
unit Volume; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, INIFiles, ExtCtrls; type TfrmVolume = class(TForm) chkMute: TCheckBox; lblVolume: TLabel; tbVolume: TTrackBar; imgMute: TImage; imgUnmute: TImage; line: TShape; Timer: TTimer; procedure tbVolumeKeyPress(Sender: TObject; var Key: Char); procedure chkMuteKeyPress(Sender: TObject; var Key: Char); procedure tbVolumeChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure chkMuteClick(Sender: TObject); procedure TimerTimer(Sender: TObject); private { Private declarations } public { Public declarations } protected procedure CreateParams (var Params: TCreateParams); override; end; var frmVolume: TfrmVolume; implementation uses General, uLNG, uComments, uINI; {$R *.dfm} procedure TfrmVolume.CreateParams (var Params: TCreateParams); begin inherited; with Params do begin ExStyle := (ExStyle or WS_EX_TOOLWINDOW or WS_EX_NOACTIVATE); end; end; procedure TfrmVolume.FormClose(Sender: TObject; var Action: TCloseAction); begin VolumeIsShow := False; FVolume.Destroy; end; procedure TfrmVolume.FormShow(Sender: TObject); begin Color := frmBgColor; Icon := PluginSkin.Volume.Icon; imgMute.Picture.Icon := PluginSkin.Mute.Icon; imgUnmute.Picture.Icon := PluginSkin.Unmute.Icon; { Width := 90; Height := 243; } Caption := LNG('FORM Volume', 'Caption', 'Volume'); chkMute.Caption := LNG('FORM Volume', 'Mute', 'Mute'); SetWindowPos(Handle, HWND_TOPMOST, Left,Top, Width, Height, 0{SWP_NOMOVE or SWP_NOSIZE or SWP_SHOWWINDOW}); tbVolume.Position := 100 - Player_Volume; chkMute.Checked := Player_Mute; lblVolume.Caption := IntToStr(Player_Volume) + '%'; AddComments(FVolume); tbVolume.SetFocus; VolumeIsShow := True; end; procedure TfrmVolume.tbVolumeChange(Sender: TObject); var INI : TIniFile; begin Timer.Enabled := False; Player_Volume := 100 - tbVolume.Position ; lblVolume.Caption := IntToStr(Player_Volume) + '%'; INIGetProfileConfig(INI); INIWriteInteger(INI, 'Conf', 'Volume', Player_Volume ); INIFree(INI); QIPPlugin.SetChangeVolume; Timer.Enabled := True; end; procedure TfrmVolume.tbVolumeKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then Close; end; procedure TfrmVolume.TimerTimer(Sender: TObject); begin Close; end; procedure TfrmVolume.chkMuteClick(Sender: TObject); begin Player_Mute := chkMute.Checked; QIPPlugin.SetChangeVolume; end; procedure TfrmVolume.chkMuteKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then Close; end; end.
unit LocalCacheManager; interface uses GameTypes, MapTypes, LanderTypes; type TWorldAgents = record Manager : ILocalCacheManager; Document : IGameDocument; Map : IWorldMap; end; function GetWorldAgents(out Agents : TWorldAgents) : boolean; implementation uses Classes, SysUtils, Graphics, CoreTypes, Lander, Map, IniFiles, ImageLoader, Land; type TLocalCacheManager = class(TInterfacedObject, ILocalCacheManager) public constructor Create; destructor Destroy; override; private // ILocalCacheManager function Load(const url : string) : boolean; function GetLandMap : TMapImage; function GetLandImage(const zoom : TZoomRes; id : idLand) : TGameImage; function GetSpareImage(const zoom : TZoomRes) : TGameImage; function GetShadeImage(const zoom : TZoomRes) : TGameImage; function GetRedShadeImage(const zoom : TZoomRes) : TGameImage; function GetBlackShadeImage(const zoom : TZoomRes) : TGameImage; private fWorldMapImage : TGameImage; fBaseUrl : string; fMapUrl : string; fSpareUrl : string; fShadeUrl : string; fDisabledUrl : string; fBlackShadeUrl : string; fLandFileNames : array[idLand] of string; fCacheLoaded : boolean; procedure ReloadCache(const url : string; HomeFile : TIniFile); procedure ReleaseCache; procedure LoadLandFileNames; end; function GetWorldAgents(out Agents : TWorldAgents) : boolean; var Manager : TLocalCacheManager; Map : TWorldMap; Lander : TLander; begin Manager := TLocalCacheManager.Create; Agents.Manager := Manager; Map := TWorldMap.Create(Agents.Manager); Lander := TLander.Create(Map); Agents.Document := Lander; Map.SetCoordConverter(Lander); Agents.Map := IWorldMap(Map); Result := true; end; const ServerDir = 'Client/Cache/'; // TLocalCacheManager constructor TLocalCacheManager.Create; begin inherited Create; end; destructor TLocalCacheManager.Destroy; begin assert(RefCount = 0); if fCacheLoaded then ReleaseCache; inherited; end; function TLocalCacheManager.Load(const url : string) : boolean; var HomeFile : TIniFile; MapName : string; begin HomeFile := TIniFile.Create(url + '\Default.ini'); try try MapName := HomeFile.ReadString('General', 'Map', ''); if MapName <> '' then begin if fCacheLoaded then ReleaseCache; ReloadCache(url, HomeFile); Result := true; end else Result := false; finally HomeFile.Free; end; except Result := false; end; end; function TLocalCacheManager.GetLandMap : TMapImage; begin Result := fWorldMapImage; end; function TLocalCacheManager.GetLandImage(const zoom : TZoomRes; id : idLand) : TGameImage; begin assert(zoom = zr32x64); if fLandFileNames[id] <> '' then Result := LoadGameImage(fBaseUrl + 'LandImages\' + fLandFileNames[id]) else Result := nil; end; function TLocalCacheManager.GetSpareImage(const zoom : TZoomRes) : TGameImage; // >>>> id begin assert(zoom = zr32x64); Result := LoadGameImage(fBaseUrl + fSpareUrl); end; function TLocalCacheManager.GetShadeImage(const zoom : TZoomRes) : TGameImage; begin assert(zoom = zr32x64); Result := LoadGameImage(fBaseUrl + fShadeUrl); end; function TLocalCacheManager.GetRedShadeImage(const zoom : TZoomRes) : TGameImage; begin assert(zoom = zr32x64); Result := LoadGameImage(fBaseUrl + fDisabledUrl); end; function TLocalCacheManager.GetBlackShadeImage(const zoom : TZoomRes) : TGameImage; begin assert(zoom = zr32x64); Result := LoadGameImage(fBaseUrl + fBlackShadeUrl); end; procedure TLocalCacheManager.ReloadCache(const url : string; HomeFile : TIniFile); begin assert(not fCacheLoaded); if url[length(url)] = '\' then fBaseUrl := url else fBaseUrl := url + '\'; fMapUrl := 'OtherImages\' + HomeFile.ReadString('General', 'Map', ''); assert(fMapUrl <> ''); fSpareUrl := 'OtherImages\' + HomeFile.ReadString('Images', 'Spare', 'Spare.bmp'); fShadeUrl := 'OtherImages\' + HomeFile.ReadString('Images', 'Shade', 'Shade.bmp'); fDisabledUrl := 'OtherImages\' + HomeFile.ReadString('Images', 'Disabled', 'Disabled.bmp'); fBlackShadeUrl := 'OtherImages\' + HomeFile.ReadString('Images', 'BlackShade', 'BlackShade.bmp'); fWorldMapImage := LoadGameImage(fBaseUrl + fMapUrl); LoadLandFileNames; fCacheLoaded := true; end; procedure TLocalCacheManager.ReleaseCache; var i : integer; begin assert(fCacheLoaded); fBaseUrl := ''; fWorldMapImage.Free; fWorldMapImage := nil; for i := low(fLandFileNames) to high(fLandFileNames) do fLandFileNames[i] := ''; fCacheLoaded := false; end; procedure TLocalCacheManager.LoadLandFileNames; var info : TSearchRec; ok : boolean; ini : TIniFile; path : string; id : integer; begin path := fBaseUrl + 'LandClasses\'; ok := FindFirst(path + '*.ini', faArchive, info) = 0; try while ok do begin if info.Attr and faDirectory <> faDirectory then begin ini := TIniFile.Create(path + info.Name); try id := ini.ReadInteger('General', 'Id', high(id)); assert((id >= 0) and (id < 256)); assert(fLandFileNames[id] = ''); fLandFileNames[id] := ini.ReadString('Images', '64x32', ''); assert(fLandFileNames[id] <> ''); finally ini.Free; end; end; ok := FindNext(info) = 0; end; finally FindClose(info); end; end; end.
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // author this port to delphi - Marat Shaymardanov, Tomsk 2007, 2018 // // You can freely use this code in any project // if sending any postcards with postage stamp to my address: // Frunze 131/1, 56, Russia, Tomsk, 634021 unit pbPublic; interface const WIRETYPE_VARINT = 0; WIRETYPE_FIXED64 = 1; WIRETYPE_LENGTH_DELIMITED = 2; WIRETYPE_START_GROUP = 3; WIRETYPE_END_GROUP = 4; WIRETYPE_FIXED32 = 5; TAG_TYPE_BITS = 3; TAG_TYPE_MASK = (1 shl TAG_TYPE_BITS) - 1; RecursionLimit = 64; (* Get a tag value, determines the wire type (the lower 3 bits) *) function getTagWireType(tag: Integer): Integer; (* Get a tag value, determines the field number (the upper 29 bits) *) function getTagFieldNumber(tag: Integer): Integer; (* Makes a tag value given a field number and wire type *) function makeTag(fieldNumber, wireType: Integer): Integer; implementation function getTagWireType(tag: Integer): Integer; begin Result := tag and TAG_TYPE_MASK; end; function getTagFieldNumber(tag: Integer): Integer; begin Result := tag shr TAG_TYPE_BITS; end; function makeTag(fieldNumber, wireType: Integer): Integer; begin Result := (fieldNumber shl TAG_TYPE_BITS) or wireType; end; end.
unit daSortField; // Модуль: "w:\common\components\rtl\Garant\DA\daSortField.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaSortField" MUID: (5680EF290107) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes ; type TdaSortField = class(Tl3ProtoObject, IdaSortField) private f_SelectField: IdaSelectField; f_SortOrder: TdaSortOrder; protected function Get_SelectField: IdaSelectField; function Get_SortOrder: TdaSortOrder; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending); reintroduce; class function Make(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField; reintroduce; end;//TdaSortField implementation uses l3ImplUses //#UC START# *5680EF290107impl_uses* //#UC END# *5680EF290107impl_uses* ; constructor TdaSortField.Create(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending); //#UC START# *5680EF4703D5_5680EF290107_var* //#UC END# *5680EF4703D5_5680EF290107_var* begin //#UC START# *5680EF4703D5_5680EF290107_impl* inherited Create; f_SelectField := aSelectField; f_SortOrder := aSortOrder; //#UC END# *5680EF4703D5_5680EF290107_impl* end;//TdaSortField.Create class function TdaSortField.Make(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField; var l_Inst : TdaSortField; begin l_Inst := Create(aSelectField, aSortOrder); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TdaSortField.Make function TdaSortField.Get_SelectField: IdaSelectField; //#UC START# *5680EEB20163_5680EF290107get_var* //#UC END# *5680EEB20163_5680EF290107get_var* begin //#UC START# *5680EEB20163_5680EF290107get_impl* Result := f_SelectField; //#UC END# *5680EEB20163_5680EF290107get_impl* end;//TdaSortField.Get_SelectField function TdaSortField.Get_SortOrder: TdaSortOrder; //#UC START# *5680EEDA03E3_5680EF290107get_var* //#UC END# *5680EEDA03E3_5680EF290107get_var* begin //#UC START# *5680EEDA03E3_5680EF290107get_impl* Result := f_SortOrder; //#UC END# *5680EEDA03E3_5680EF290107get_impl* end;//TdaSortField.Get_SortOrder procedure TdaSortField.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5680EF290107_var* //#UC END# *479731C50290_5680EF290107_var* begin //#UC START# *479731C50290_5680EF290107_impl* f_SelectField := nil; inherited; //#UC END# *479731C50290_5680EF290107_impl* end;//TdaSortField.Cleanup end.
unit EditImpl; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, EditXControl_TLB; type TEditX = class(TActiveXControl, IEditX) private { Private declarations } FDelphiControl: TEdit; FEvents: IEditXEvents; procedure ChangeEvent(Sender: TObject); procedure ClickEvent(Sender: TObject); procedure DblClickEvent(Sender: TObject); procedure KeyPressEvent(Sender: TObject; var Key: Char); protected { Protected declarations } procedure InitializeControl; override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; function Get_AutoSelect: WordBool; safecall; function Get_AutoSize: WordBool; safecall; function Get_BorderStyle: TxBorderStyle; safecall; function Get_CharCase: TxEditCharCase; safecall; function Get_Color: Integer; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_HideSelection: WordBool; safecall; function Get_ImeMode: TxImeMode; safecall; function Get_ImeName: WideString; safecall; function Get_MaxLength: Integer; safecall; function Get_Modified: WordBool; safecall; function Get_OEMConvert: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_PasswordChar: Smallint; safecall; function Get_ReadOnly: WordBool; safecall; function Get_SelLength: Integer; safecall; function Get_SelStart: Integer; safecall; function Get_SelText: WideString; safecall; function Get_Text: WideString; safecall; function Get_Visible: WordBool; safecall; procedure Clear; safecall; procedure ClearSelection; safecall; procedure CopyToClipboard; safecall; procedure CutToClipboard; safecall; procedure PasteFromClipboard; safecall; procedure SelectAll; safecall; procedure Set_AutoSelect(Value: WordBool); safecall; procedure Set_AutoSize(Value: WordBool); safecall; procedure Set_BorderStyle(Value: TxBorderStyle); safecall; procedure Set_CharCase(Value: TxEditCharCase); safecall; procedure Set_Color(Value: Integer); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_HideSelection(Value: WordBool); safecall; procedure Set_ImeMode(Value: TxImeMode); safecall; procedure Set_ImeName(const Value: WideString); safecall; procedure Set_MaxLength(Value: Integer); safecall; procedure Set_Modified(Value: WordBool); safecall; procedure Set_OEMConvert(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_PasswordChar(Value: Smallint); safecall; procedure Set_ReadOnly(Value: WordBool); safecall; procedure Set_SelLength(Value: Integer); safecall; procedure Set_SelStart(Value: Integer); safecall; procedure Set_SelText(const Value: WideString); safecall; procedure Set_Text(const Value: WideString); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation { TEditX } procedure TEditX.InitializeControl; begin FDelphiControl := Control as TEdit; FDelphiControl.OnChange := ChangeEvent; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnKeyPress := KeyPressEvent; end; procedure TEditX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IEditXEvents; end; procedure TEditX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_EditXPage); } end; function TEditX.Get_AutoSelect: WordBool; begin Result := FDelphiControl.AutoSelect; end; function TEditX.Get_AutoSize: WordBool; begin Result := FDelphiControl.AutoSize; end; function TEditX.Get_BorderStyle: TxBorderStyle; begin Result := Ord(FDelphiControl.BorderStyle); end; function TEditX.Get_CharCase: TxEditCharCase; begin Result := Ord(FDelphiControl.CharCase); end; function TEditX.Get_Color: Integer; begin Result := Integer(FDelphiControl.Color); end; function TEditX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TEditX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TEditX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TEditX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TEditX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TEditX.Get_HideSelection: WordBool; begin Result := FDelphiControl.HideSelection; end; function TEditX.Get_ImeMode: TxImeMode; begin Result := Ord(FDelphiControl.ImeMode); end; function TEditX.Get_ImeName: WideString; begin Result := WideString(FDelphiControl.ImeName); end; function TEditX.Get_MaxLength: Integer; begin Result := FDelphiControl.MaxLength; end; function TEditX.Get_Modified: WordBool; begin Result := FDelphiControl.Modified; end; function TEditX.Get_OEMConvert: WordBool; begin Result := FDelphiControl.OEMConvert; end; function TEditX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TEditX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TEditX.Get_PasswordChar: Smallint; begin Result := Smallint(FDelphiControl.PasswordChar); end; function TEditX.Get_ReadOnly: WordBool; begin Result := FDelphiControl.ReadOnly; end; function TEditX.Get_SelLength: Integer; begin Result := FDelphiControl.SelLength; end; function TEditX.Get_SelStart: Integer; begin Result := FDelphiControl.SelStart; end; function TEditX.Get_SelText: WideString; begin Result := WideString(FDelphiControl.SelText); end; function TEditX.Get_Text: WideString; begin Result := WideString(FDelphiControl.Text); end; function TEditX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; procedure TEditX.Clear; begin end; procedure TEditX.ClearSelection; begin end; procedure TEditX.CopyToClipboard; begin end; procedure TEditX.CutToClipboard; begin end; procedure TEditX.PasteFromClipboard; begin end; procedure TEditX.SelectAll; begin end; procedure TEditX.Set_AutoSelect(Value: WordBool); begin FDelphiControl.AutoSelect := Value; end; procedure TEditX.Set_AutoSize(Value: WordBool); begin FDelphiControl.AutoSize := Value; end; procedure TEditX.Set_BorderStyle(Value: TxBorderStyle); begin FDelphiControl.BorderStyle := TBorderStyle(Value); end; procedure TEditX.Set_CharCase(Value: TxEditCharCase); begin FDelphiControl.CharCase := TEditCharCase(Value); end; procedure TEditX.Set_Color(Value: Integer); begin FDelphiControl.Color := TColor(Value); end; procedure TEditX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TEditX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TEditX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TEditX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TEditX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TEditX.Set_HideSelection(Value: WordBool); begin FDelphiControl.HideSelection := Value; end; procedure TEditX.Set_ImeMode(Value: TxImeMode); begin FDelphiControl.ImeMode := TImeMode(Value); end; procedure TEditX.Set_ImeName(const Value: WideString); begin FDelphiControl.ImeName := TImeName(Value); end; procedure TEditX.Set_MaxLength(Value: Integer); begin FDelphiControl.MaxLength := Value; end; procedure TEditX.Set_Modified(Value: WordBool); begin FDelphiControl.Modified := Value; end; procedure TEditX.Set_OEMConvert(Value: WordBool); begin FDelphiControl.OEMConvert := Value; end; procedure TEditX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TEditX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TEditX.Set_PasswordChar(Value: Smallint); begin FDelphiControl.PasswordChar := Char(Value); end; procedure TEditX.Set_ReadOnly(Value: WordBool); begin FDelphiControl.ReadOnly := Value; end; procedure TEditX.Set_SelLength(Value: Integer); begin FDelphiControl.SelLength := Value; end; procedure TEditX.Set_SelStart(Value: Integer); begin FDelphiControl.SelStart := Value; end; procedure TEditX.Set_SelText(const Value: WideString); begin FDelphiControl.SelText := String(Value); end; procedure TEditX.Set_Text(const Value: WideString); begin FDelphiControl.Text := TCaption(Value); end; procedure TEditX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TEditX.ChangeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnChange; end; procedure TEditX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TEditX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TEditX.KeyPressEvent(Sender: TObject; var Key: Char); var TempKey: Smallint; begin TempKey := Smallint(Key); if FEvents <> nil then FEvents.OnKeyPress(TempKey); Key := Char(TempKey); end; initialization TActiveXControlFactory.Create( ComServer, TEditX, TEdit, Class_EditX, 1, '', 0); end.
unit uEditorIntf; interface uses Graphics, Dialogs; type TWordCount = record AnsiChar: Integer; MultiChar: Integer; NumChar: Integer; Other: Integer; end; IEditorIntf = interface ['{2D1EAB66-95CB-4EA9-B9B6-C271EA1DAA24}'] function GetFileName: string; function GetSaved: Boolean; function Save: Boolean; function SaveAs: Boolean; function GetSelectText: String; function CanUndo: Boolean; procedure Undo; function CanRedo: Boolean; procedure Redo; function CanCopy: Boolean; procedure Copy; function CanCut: Boolean; procedure Cut; function CanPaster: Boolean; procedure Paster; function CanDeleteSelection: Boolean; procedure DelectSelection; procedure SetFont(Font: TFont); function FindNext(Text: String; Option: TFindOptions): Boolean; function Replace(FindText, ReplaceText: String; Option: TFindOptions): Integer; function GetWordCount: TWordCount; function GetWordWarp: Boolean; // ÊÇ·ñ·ÖÐÐ procedure SetWordWarp(WordWarp: Boolean); end; implementation end.
unit tb97WordsPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tb97WordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "tb97WordsPack" MUID: (54F591820236) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoTB97)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoTB97) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoTB97)} uses l3ImplUses , tb97Ctls , tfwPropertyLike , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *54F591820236impl_uses* //#UC END# *54F591820236impl_uses* ; type TkwPopTB97ButtonDown = {final} class(TtfwPropertyLike) {* Слово скрипта pop:TB97Button:Down } private function Down(const aCtx: TtfwContext; aTB97Button: TCustomToolbarButton97): Boolean; {* Реализация слова скрипта pop:TB97Button:Down } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopTB97ButtonDown function TkwPopTB97ButtonDown.Down(const aCtx: TtfwContext; aTB97Button: TCustomToolbarButton97): Boolean; {* Реализация слова скрипта pop:TB97Button:Down } begin Result := aTB97Button.Down; end;//TkwPopTB97ButtonDown.Down class function TkwPopTB97ButtonDown.GetWordNameForRegister: AnsiString; begin Result := 'pop:TB97Button:Down'; end;//TkwPopTB97ButtonDown.GetWordNameForRegister function TkwPopTB97ButtonDown.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopTB97ButtonDown.GetResultTypeInfo function TkwPopTB97ButtonDown.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopTB97ButtonDown.GetAllParamsCount function TkwPopTB97ButtonDown.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TCustomToolbarButton97)]); end;//TkwPopTB97ButtonDown.ParamsTypes procedure TkwPopTB97ButtonDown.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Down', aCtx); end;//TkwPopTB97ButtonDown.SetValuePrim procedure TkwPopTB97ButtonDown.DoDoIt(const aCtx: TtfwContext); var l_aTB97Button: TCustomToolbarButton97; begin try l_aTB97Button := TCustomToolbarButton97(aCtx.rEngine.PopObjAs(TCustomToolbarButton97)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aTB97Button: TCustomToolbarButton97 : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(Down(aCtx, l_aTB97Button)); end;//TkwPopTB97ButtonDown.DoDoIt initialization TkwPopTB97ButtonDown.RegisterInEngine; {* Регистрация pop_TB97Button_Down } TtfwTypeRegistrator.RegisterType(TypeInfo(TCustomToolbarButton97)); {* Регистрация типа TCustomToolbarButton97 } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoTB97) end.
unit mnSynHighlighterNim; {$mode objfpc}{$H+} {** * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey https://github.com/jangko/nppnim/blob/master/nppnim.nim https://github.com/saem/vscode-nim/blob/main/snippets/nim.json *} interface uses Classes, SysUtils, SynEdit, SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc; type { TNimProcessor } TNimProcessor = class(TCommonSynProcessor) private protected function GetIdentChars: TSynIdentChars; override; function GetEndOfLineAttribute: TSynHighlighterAttributes; override; procedure Created; override; public procedure QuestionProc; procedure DirectiveProc; procedure SharpProc; procedure DQProc; procedure GreaterProc; procedure LowerProc; procedure Next; override; procedure Prepare; override; procedure MakeProcTable; override; end; { TmnSynNimSyn } TmnSynNimSyn = class(TSynMultiProcSyn) private protected function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; procedure InitProcessors; override; published end; const SYNS_LangNim = 'Nim'; SYNS_FilterNim = 'Nim Lang Files (*.Nim)|*.Nim'; cNimSample = '#defines function'#13#10+ 'func fact(n: int)'#13#10+ ' return @[10]'#13#10+ ''#13#10; {$INCLUDE 'NimKeywords.inc'} implementation uses mnUtils; procedure TNimProcessor.GreaterProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); if Parent.Peek in ['=', '>'] then Inc(Parent.Run); end; procedure TNimProcessor.LowerProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.Peek of '=': Inc(Parent.Run); '<': begin Inc(Parent.Run); if Parent.Peek = '=' then Inc(Parent.Run); end; end; end; procedure TNimProcessor.SharpProc; begin Inc(Parent.Run); case Parent.Peek of '[': CommentMLProc; '#': begin if Parent.Peek(1) = '[' then begin Inc(Parent.Run); SpecialDocumentMLProc end else DocumentSLProc end; else CommentSLProc; end; end; procedure TNimProcessor.DQProc; begin SetRange(rscStringDQ); Inc(Parent.Run); case Parent.Peek of '"': begin if Parent.Peek(1) = '"' then begin Inc(Parent.Run); SpecialStringProc end else StringProc; end; else StringProc; end; end; procedure TNimProcessor.MakeProcTable; var I: Char; begin inherited; for I := #0 to #255 do case I of '?': ProcTable[I] := @QuestionProc; '''': ProcTable[I] := @StringSQProc; '"': ProcTable[I] := @DQProc; '#': ProcTable[I] := @SharpProc; '>': ProcTable[I] := @GreaterProc; '<': ProcTable[I] := @LowerProc; '0'..'9': ProcTable[I] := @NumberProc; 'A'..'Z', 'a'..'z', '_': ProcTable[I] := @IdentProc; end; end; procedure TNimProcessor.QuestionProc; begin Inc(Parent.Run); case Parent.Peek of '>': begin Parent.Processors.Switch(Parent.Processors.MainProcessor); Inc(Parent.Run); Parent.FTokenID := tkProcessor; end else Parent.FTokenID := tkSymbol; end; end; procedure TNimProcessor.DirectiveProc; begin Parent.FTokenID := tkProcessor; WordProc; end; procedure TNimProcessor.Next; begin Parent.FTokenPos := Parent.Run; if (Parent.Peek in [#0, #10, #13]) then ProcTable[Parent.Peek] else case Range of rscComment: CommentMLProc; rscDocument: DocumentMLProc; rscSpecialComment: SpecialCommentMLProc; rscSpecialDocument: SpecialDocumentMLProc; rscStringSQ, rscStringDQ, rscStringBQ: StringProc; rscSpecialString: SpecialStringProc; else if ProcTable[Parent.Peek] = nil then UnknownProc else ProcTable[Parent.Peek]; end; end; procedure TNimProcessor.Prepare; begin inherited; EnumerateKeywords(Ord(tkKeyword), sNimKeywords, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkType), sNimTypes, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkValue), sNimValues, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkFunction), sNimFunctions, TSynValidStringChars, @DoAddKeyword); SetRange(rscUnknown); end; function TNimProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes; begin if (Range = rscDocument) or (LastRange = rscDocument) then Result := Parent.DocumentAttri else Result := inherited GetEndOfLineAttribute; end; procedure TNimProcessor.Created; begin inherited Created; CloseSpecialString := '"""'; CloseComment := ']#'; CloseSpecialDocument := ']##'; end; function TNimProcessor.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars + ['.']; end; constructor TmnSynNimSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultFilter := SYNS_FilterNim; end; procedure TmnSynNimSyn.InitProcessors; begin inherited; Processors.Add(TNimProcessor.Create(Self, 'Nim')); Processors.MainProcessor := 'Nim'; Processors.DefaultProcessor := 'Nim'; end; class function TmnSynNimSyn.GetLanguageName: string; begin Result := 'Nim'; end; function TmnSynNimSyn.GetSampleSource: string; begin Result := cNimSample; end; end.
unit ncsClientTransporter; // Модуль: "w:\common\components\rtl\Garant\cs\ncsClientTransporter.pas" // Стереотип: "SimpleClass" // Элемент модели: "TncsClientTransporter" MUID: (544A0A0D0239) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , ncsTransporter , ncsMessageInterfaces , idComponent , ncsTCPClient ; type TncsClientArray = array [TncsSocketKind] of TncsTCPClient; TncsClientTransporter = class(TncsTransporter, IncsClientTransporter) private f_TCPClients: TncsClientArray; private procedure TransportConnected; procedure SendTransportStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: AnsiString); procedure ReceiveTransportStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: AnsiString); protected procedure BeforeSendHandshake; virtual; procedure BeforeReceiveHandshake; virtual; procedure Connect(const aServerHost: AnsiString; aServerPort: Integer; const aSessionID: AnsiString); procedure Disconnect(Immidiate: Boolean = False); {* Immidiate = True - отрубить сразу Immidiate = False - дождаться завершения обмена послав ncsDisconnect и дождавшись ответа } procedure HandShake; override; function HandShakeKind: TncsSocketKind; override; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; procedure ClearFields; override; public constructor Create; reintroduce; class function Make: IncsClientTransporter; reintroduce; end;//TncsClientTransporter {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses , SysUtils , l3Base , IdException , csIdIOHandlerAdapter , csIdIOHandlerAbstractAdapter , ncsMessage //#UC START# *544A0A0D0239impl_uses* //#UC END# *544A0A0D0239impl_uses* ; const {* В миллисек } c_ClientConnectTimeout = 10 * 1000; c_ClientReadTimeout = {$IFDEF CsDebug} 1000 * 1000 {$ELSE} 10 * 1000 {$ENDIF}; procedure TncsClientTransporter.TransportConnected; //#UC START# *54522FCE0023_544A0A0D0239_var* var l_IOHandler: TcsIdIOHandlerAbstractAdapter; //#UC END# *54522FCE0023_544A0A0D0239_var* begin //#UC START# *54522FCE0023_544A0A0D0239_impl* if Get_Connected then Exit; l_IOHandler := TcsidIOHandlerAdapter.Create(f_TcpClients[ncs_skSend].IOHandler); try IOHandlers[ncs_skSend] := l_IOHandler; finally FreeAndNil(l_IOHandler) end; StartProcessing; //#UC END# *54522FCE0023_544A0A0D0239_impl* end;//TncsClientTransporter.TransportConnected procedure TncsClientTransporter.SendTransportStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: AnsiString); //#UC START# *545B400202AF_544A0A0D0239_var* //#UC END# *545B400202AF_544A0A0D0239_var* begin //#UC START# *545B400202AF_544A0A0D0239_impl* case aStatus of hsConnected: TransportConnected; hsDisconnected: StopProcessing(False); end; //#UC END# *545B400202AF_544A0A0D0239_impl* end;//TncsClientTransporter.SendTransportStatus constructor TncsClientTransporter.Create; //#UC START# *5465A71E02F2_544A0A0D0239_var* //#UC END# *5465A71E02F2_544A0A0D0239_var* begin //#UC START# *5465A71E02F2_544A0A0D0239_impl* inherited Create; //#UC END# *5465A71E02F2_544A0A0D0239_impl* end;//TncsClientTransporter.Create class function TncsClientTransporter.Make: IncsClientTransporter; var l_Inst : TncsClientTransporter; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TncsClientTransporter.Make procedure TncsClientTransporter.ReceiveTransportStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: AnsiString); //#UC START# *5491684203A6_544A0A0D0239_var* //#UC END# *5491684203A6_544A0A0D0239_var* begin //#UC START# *5491684203A6_544A0A0D0239_impl* case aStatus of hsDisconnected: StopProcessing(False); end; //#UC END# *5491684203A6_544A0A0D0239_impl* end;//TncsClientTransporter.ReceiveTransportStatus procedure TncsClientTransporter.BeforeSendHandshake; //#UC START# *549279980264_544A0A0D0239_var* //#UC END# *549279980264_544A0A0D0239_var* begin //#UC START# *549279980264_544A0A0D0239_impl* // Do nothing //#UC END# *549279980264_544A0A0D0239_impl* end;//TncsClientTransporter.BeforeSendHandshake procedure TncsClientTransporter.BeforeReceiveHandshake; //#UC START# *549279B300D5_544A0A0D0239_var* //#UC END# *549279B300D5_544A0A0D0239_var* begin //#UC START# *549279B300D5_544A0A0D0239_impl* // Do nothing //#UC END# *549279B300D5_544A0A0D0239_impl* end;//TncsClientTransporter.BeforeReceiveHandshake procedure TncsClientTransporter.Connect(const aServerHost: AnsiString; aServerPort: Integer; const aSessionID: AnsiString); //#UC START# *544A1FD802E9_544A0A0D0239_var* //#UC END# *544A1FD802E9_544A0A0D0239_var* begin //#UC START# *544A1FD802E9_544A0A0D0239_impl* if Get_Connected then Exit; IntSessionID := aSessionID; f_TcpClients[ncs_skSend].Host := aServerHost; f_TcpClients[ncs_skSend].Port := aServerPort; f_TcpClients[ncs_skReceive].Host := aServerHost; f_TcpClients[ncs_skReceive].Port := aServerPort; try f_TcpClients[ncs_skSend].Connect; except on E: EidException do l3System.Exception2Log(E); end; //#UC END# *544A1FD802E9_544A0A0D0239_impl* end;//TncsClientTransporter.Connect procedure TncsClientTransporter.Disconnect(Immidiate: Boolean = False); {* Immidiate = True - отрубить сразу Immidiate = False - дождаться завершения обмена послав ncsDisconnect и дождавшись ответа } //#UC START# *544A1FF00062_544A0A0D0239_var* var l_Message: TncsDisconnect; l_Reply: TncsMessage; //#UC END# *544A1FF00062_544A0A0D0239_var* begin //#UC START# *544A1FF00062_544A0A0D0239_impl* if not Get_Connected then Exit; if not Immidiate then begin l_Message := TncsDisconnect.Create; try Send(l_Message); l_Reply := nil; WaitForReply(l_Message, l_Reply); if not (l_Reply is TncsDisconnectReply) then l3System.Msg2Log('Invalid csDisconnectReply'); FreeAndNil(l_Reply); finally FreeAndNil(l_Message); end; end; StopProcessing(True); f_TcpClients[ncs_skSend].IOHandler.WriteBufferClose; f_TcpClients[ncs_skSend].Disconnect(True); f_TcpClients[ncs_skReceive].IOHandler.WriteBufferClose; f_TcpClients[ncs_skReceive].Disconnect(True); IntSessionID := ''; //#UC END# *544A1FF00062_544A0A0D0239_impl* end;//TncsClientTransporter.Disconnect procedure TncsClientTransporter.HandShake; //#UC START# *5477033C03D0_544A0A0D0239_var* var l_ID: Integer; l_IOHandler: TcsIdIOHandlerAbstractAdapter; //#UC END# *5477033C03D0_544A0A0D0239_var* begin //#UC START# *5477033C03D0_544A0A0D0239_impl* BeforeSendHandshake; IOHandlers[ncs_skSend].WriteInteger(Ord(ncs_skSend)); IOHandlers[ncs_skSend].WriteLn(IntSessionID); IOHandlers[ncs_skSend].WriteBufferFlush; l_ID := IOHandlers[ncs_skSend].ReadInteger; Assert(l_ID = 104); try f_TcpClients[ncs_skReceive].Connect; l_IOHandler := TcsidIOHandlerAdapter.Create(f_TcpClients[ncs_skReceive].IOHandler); try IOHandlers[ncs_skReceive] := l_IOHandler; finally FreeAndNil(l_IOHandler) end; IOHandlers[ncs_skReceive].WriteBufferOpen(-1); BeforeReceiveHandshake; IOHandlers[ncs_skReceive].WriteInteger(Ord(ncs_skReceive)); IOHandlers[ncs_skReceive].WriteLn(IntSessionID); IOHandlers[ncs_skReceive].WriteBufferFlush; l_ID := IOHandlers[ncs_skReceive].ReadInteger; Assert(l_ID = 104); IOHandlers[ncs_skSend].WriteInteger(105); IOHandlers[ncs_skSend].WriteBufferFlush; l_ID := IOHandlers[ncs_skSend].ReadInteger; Assert(l_ID = 106); IOHandlers[ncs_skReceive].WriteInteger(105); IOHandlers[ncs_skReceive].WriteBufferFlush; except on E: EidException do l3System.Exception2Log(E); end; //#UC END# *5477033C03D0_544A0A0D0239_impl* end;//TncsClientTransporter.HandShake function TncsClientTransporter.HandShakeKind: TncsSocketKind; //#UC START# *549175C4030A_544A0A0D0239_var* //#UC END# *549175C4030A_544A0A0D0239_var* begin //#UC START# *549175C4030A_544A0A0D0239_impl* Result := ncs_skSend; //#UC END# *549175C4030A_544A0A0D0239_impl* end;//TncsClientTransporter.HandShakeKind procedure TncsClientTransporter.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_544A0A0D0239_var* //#UC END# *479731C50290_544A0A0D0239_var* begin //#UC START# *479731C50290_544A0A0D0239_impl* Disconnect; FreeAndNil(f_TcpClients[ncs_skSend]); FreeAndNil(f_TcpClients[ncs_skReceive]); inherited; //#UC END# *479731C50290_544A0A0D0239_impl* end;//TncsClientTransporter.Cleanup procedure TncsClientTransporter.InitFields; //#UC START# *47A042E100E2_544A0A0D0239_var* //#UC END# *47A042E100E2_544A0A0D0239_var* begin //#UC START# *47A042E100E2_544A0A0D0239_impl* inherited; f_TcpClients[ncs_skSend] := TncsTcpClient.Create(nil); f_TcpClients[ncs_skSend].ConnectTimeout := c_ClientConnectTimeout; f_TcpClients[ncs_skSend].ReadTimeout := c_ClientReadTimeout; f_TcpClients[ncs_skSend].OnStatus := SendTransportStatus; f_TcpClients[ncs_skReceive] := TncsTcpClient.Create(nil); f_TcpClients[ncs_skReceive].ConnectTimeout := c_ClientConnectTimeout; f_TcpClients[ncs_skReceive].ReadTimeout := c_ClientReadTimeout; f_TcpClients[ncs_skReceive].OnStatus := ReceiveTransportStatus; //#UC END# *47A042E100E2_544A0A0D0239_impl* end;//TncsClientTransporter.InitFields procedure TncsClientTransporter.ClearFields; begin Finalize(f_TCPClients); inherited; end;//TncsClientTransporter.ClearFields {$IfEnd} // NOT Defined(Nemesis) end.
//Exercicio 84: Receber a temperatura média de cada mês do ano e armazenar estas informações em um vetor. Calcular e //exibir qual foi a maior e qual foi a menor temperatura do ano e em quais meses ocorreram. { Solução em Portugol Algoritmo Exercicio 84; // Esse é igual o 69. Var temperatura_media: vetor[1..12] de real; mes: vetor[1..12] de caracter; i: inteiro; maior,menor: real; Inicio exiba("Programa que determina qual mês teve a maior temperatura média e qual teve a menor."); mes[1] <- "Janeiro"; mes[2] <- "Fevereiro"; mes[3] <- "Março"; mes[4] <- "Abril"; mes[5] <- "Maio"; mes[6] <- "Junho"; mes[7] <- "Julho"; mes[8] <- "Agosto"; mes[9] <- "Setembro"; mes[10] <- "Outubro"; mes[11] <- "Novembro"; mes[12] <- "Dezembro"; para i <- 1 até 12 faça exiba("Digite a temperatura média do ",i,"º mês:"); leia(temperatura_media[i]); se(i = 1) então Inicio maior <- temperatura_media[i]; menor <- temperatura_media[i]; Fim; fimse; se(temperatura_media[i] > maior) então maior <- temperatura_media[i] senão se(temperatura_media[i] < menor) então menor <- temperatura_media[i]; fimse; fimse; fimpara; para i <- 1 até 12 faça // Estou usando um loop para o caso de acontecer empate. se(temperatura_media[i] = maior) então exiba(mes[i]," teve a maior temperatura média: ", temperatura_media[i],"ºC."); fimse; se(temperatura_media[i] = menor) então exiba(mes[i]," teve a menor temperatura média: ", temperatura_media[i],"ºC."); fimse; fimpara; Fim. } // Solução em Pascal Program Exercicio84; uses crt; var temperatura_media: array[1..12] of real; mes: array[1..12] of string; i: integer; maior,menor: real; begin clrscr; writeln('Programa que determina qual mês teve a maior temperatura média e qual teve a menor.'); mes[1] := 'Janeiro'; mes[2] := 'Fevereiro'; mes[3] := 'Março'; mes[4] := 'Abri'; mes[5] := 'Maio'; mes[6] := 'Junho'; mes[7] := 'Julho'; mes[8] := 'Agosto'; mes[9] := 'Setembro'; mes[10] := 'Outubro'; mes[11] := 'Novembro'; mes[12] := 'Dezembro'; for i := 1 to 12 do Begin writeln('Digite a temperatura média do ',i,'º mês:'); readln(temperatura_media[i]); if(i = 1) then Begin maior := temperatura_media[i]; menor := temperatura_media[i]; End; if(temperatura_media[i] > maior) then maior := temperatura_media[i] else if(temperatura_media[i] < menor) then menor := temperatura_media[i]; End; for i := 1 to 12 do Begin if(temperatura_media[i] = maior) then writeln(mes[i],' teve a maior temperatura média: ', temperatura_media[i]:0:2,'ºC.'); if(temperatura_media[i] = menor) then writeln(mes[i],' teve a menor temperatura média: ', temperatura_media[i]:0:2,'ºC.'); End; repeat until keypressed; end.
program medCabinet; uses crt, sysUtils; Type node = ^list; list = Record data : string; next : node; End; Type fnReturn = ^returnBlok; returnBlok = Record value : integer; child: node; next: fnReturn; End; Procedure nodeMakerV2 (Var el: node; data : string); Begin new(el); el^.data:=data; el^.next := Nil; End; Function listLengthCounter( start : node): integer; Var walker: node; lengthCount: integer; Begin walker := start; If (walker = Nil) Then listLengthCounter := 0 Else If (walker^.next =Nil )Then listLengthCounter := 1 Else Begin lengthCount := 1; While (walker^.next <> Nil) Do Begin walker := walker^.next; lengthCount := lengthCount+1; End; listLengthCounter := lengthCount; End; End; Function shift(Var head: node): fnReturn; Begin If (head <> Nil) Then Begin new(shift); shift^.child := head; head := head^.next; shift^.child^.next := Nil; shift^.value := listLengthCounter(head); End; End; Function push(Var head : node; el: node): fnReturn; Var tmp : node; Begin If (head = Nil) Then head := el Else Begin tmp := head; While (tmp^.next <> Nil) Do tmp := tmp^.next; tmp^.next := el; el^.next := Nil; End; new(push); push^.child := Nil; push^.value := listLengthCounter(head); End; procedure clientsArrival(var femaleQueue, maleQueue:node); var client: node; begin delay(15000); writeln('client arrival'); if(random(2)<1) then begin if(listLengthCounter(femaleQueue)<10) then begin nodeMakerV2(client, 'female'); push(femaleQueue, client); writeln('new women in the queue'); end; end else if(listLengthCounter(maleQueue) <10)then begin nodeMakerV2(client,'male'); push(maleQueue, client); writeln('new man in the queue'); end; end; Procedure medAssitence(var doctorQueue, femaleQueue, maleQueue: node); begin if(listLengthCounter(maleQueue) < listLengthCounter(femaleQueue))then begin push(doctorQueue,shift(femaleQueue)^.child); writeln('new women in the doctor office') end Else begin writeln('new man in the doctor office'); push(doctorQueue, shift(maleQueue)^.child); end; end; procedure doctorProcess(var doctorQueue,femaleQueue,maleQueue:node; var Gain, lowCost, hightCost, patientPassed,servedFemales ,servedMales: integer ); var currentPatient: node; var visitDuration: integer; begin if(listLengthCounter(doctorQueue)= 0) then medAssitence(doctorQueue,femaleQueue,maleQueue); currentPatient := shift(doctorQueue)^.child; visitDuration:=(random(26)+20); delay(visitDuration * 1000); if(visitDuration > 30) then begin Gain:=Gain+2000; hightCost:=hightCost+1; patientPassed:=patientPassed+1; if(currentPatient^.data = 'female') then servedFemales:= servedFemales+1 else servedMales:=servedMales+1; end else begin Gain:=Gain+1500; lowCost:=lowCost+1; patientPassed:=patientPassed+1; if(currentPatient^.data = 'female') then servedFemales:= servedFemales+1 else servedMales:=servedMales+1; end; end; Procedure medProcess(endOfDay : boolean); var servedFemales,servedMales, patientPassed, Gain, hightCost, lowCost: integer; var doctorQueue,maleQueue,femaleQueue:node; var counter : integer; begin counter:=0; servedFemales:=0; servedMales:=0; lowCost:=0; hightCost:=0; patientPassed:=0; Gain:=0; doctorQueue:=nil; maleQueue:=nil; femaleQueue:=nil; While(endOfDay = false) do begin clientsArrival(femaleQueue,maleQueue); medAssitence(doctorQueue,femaleQueue, maleQueue); doctorProcess(doctorQueue,femaleQueue,maleQueue,Gain, lowCost,hightCost,patientPassed,servedFemales,servedMales); if(counter =3) then endOfDay:=true; counter:=counter+1; end; writeln('***************Day sumurize***************************************************'); writeln('** the number of patient Passed is equal to ', patientPassed); writeln('** the number of male served is equal to ', servedMales); writeln('** the number of female served is equal to ', servedFemales); writeln('** the total gain this day is equal to ', Gain, 'dzd'); writeln('** the number of patient passed with a visit duration over then 30min is ', hightCost); writeln('** the number of patient passed with a visit duration less then 30min is ', lowCost ); end; begin //* This program is here to semulate how a day in the medical Cabinet happens //* Built with dynamic programing and Dynamic Data structure: queues and singleLinkedLists randomize; medProcess(false); readln; end.
(* Tg framework, FCL HTTP Daemon Broker Copyright (C) 2014 Silvio Clecio See the file LICENSE.txt, included in this distribution, for details about the copyright. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *) unit tgdaemon; {$mode objfpc}{$H+} interface uses {$IFDEF MSWINDOWS} ServiceManager, {$ENDIF} DaemonApp, Classes, SysUtils, IniFiles, tgsendertypes, tgtypes, process; type { TTgShellDaemon } TTgShellDaemon = class(TDaemon) private FBot: TTelegramSender; FChatID: Int64; FConf: TMemIniFile; FProc: TProcess; FTerminated: Boolean; procedure BotReceiveUpdate({%H-}ASender: TObject; AnUpdate: TTelegramUpdateObj); procedure BotReceiveMessage({%H-}ASender: TObject; AMessage: TTelegramMessageObj); procedure BotLogMessage({%H-}ASender: TObject; EventType: TEventType; const Msg: String); procedure OutputStd; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Install: Boolean; override; function Execute: Boolean; override; function Stop: Boolean; override; function Uninstall: Boolean; override; end; { TTgShellMapper } TTgShellMapper = class(TDaemonMapper) private published constructor Create(AOwner: TComponent); override; end; var TgShellDaemon: TTgShellDaemon; TgShellMapper: TTgShellMapper; implementation uses {$IFDEF MSWINDOWS}windows{$ENDIF} ; var AppDir: String; { TTgShellMapper } constructor TTgShellMapper.Create(AOwner: TComponent); var DmnDef: TDaemonDef; begin inherited CreateNew(AOwner); DmnDef:=DaemonDefs.Add as TDaemonDef; DmnDef.DaemonClassName:='TTgShellDaemon'; DmnDef.DisplayName:='Telegram shell bot'; DmnDef.Name:='TgShellDaemon'; end; { TTgShellDaemon } procedure TTgShellDaemon.BotReceiveUpdate(ASender: TObject; AnUpdate: TTelegramUpdateObj); begin Logger.Log(etDebug, 'Update received: '+AnUpdate.AsString); end; procedure TTgShellDaemon.BotReceiveMessage(ASender: TObject; AMessage: TTelegramMessageObj); var ExitCode: integer; InputString: String; begin InputString:=AMessage.Text; if InputString=EmptyStr then Exit; InputString+=LineEnding; if FProc.Running then begin OutputStd; FProc.Input.Write(InputString[1], Length(InputString)); sleep(100); OutputStd; end; end; procedure TTgShellDaemon.BotLogMessage(ASender: TObject; EventType: TEventType; const Msg: String); begin Logger.Log(EventType, Msg); end; procedure TTgShellDaemon.OutputStd; var CharBuffer: array [0..511] of char; ReadCount: integer; OutputString: String; begin OutputString:=EmptyStr; // read stdout and write to our stdout while FProc.Output.NumBytesAvailable > 0 do begin ReadCount := Min(512, FProc.Output.NumBytesAvailable); //Read up to buffer, not more FProc.Output.Read(CharBuffer{%H-}, ReadCount); OutputString+=Copy(CharBuffer, 0, ReadCount); Write(StdOut, OutputString); end; if OutputString<>EmptyStr then FBot.sendMessage(OutputString); // read stderr and write to our stderr { while FProc.Stderr.NumBytesAvailable > 0 do begin ReadCount := Min(512, FProc.Stderr.NumBytesAvailable); //Read up to buffer, not more FProc.Stderr.Read(CharBuffer, ReadCount); FBot.sendMessage(Copy(CharBuffer, 0, ReadCount)); // Write(StdErr, Copy(CharBuffer, 0, ReadCount)); end; } end; constructor TTgShellDaemon.Create(AOwner: TComponent); begin inherited Create(AOwner); FConf:=TMemIniFile.Create(AppDir+'telegram.ini'); TelegramAPI_URL:=FConf.ReadString('API', 'Endpoint', TelegramAPI_URL); // For Russian specific case FBot:=TTelegramSender.Create(FConf.ReadString('Bot', 'Token', EmptyStr)); if FBot.Token=EmptyStr then begin Logger.Error('Please, specify bot token in telegram.ini!'); Exit; end; FChatID:=FConf.ReadInt64('Chat', 'ID', 0); if FChatID=0 then begin Logger.Error('Please, specify chat ID in telegram.ini! See readme.md'); Exit; end; FBot.OnReceiveUpdate:=@BotReceiveUpdate; FBot.OnReceiveMessage:=@BotReceiveMessage; FBot.OnLogMessage:=@BotLogMessage; {$IFDEF MSWINDOWS} SetConsoleOutputCP(CP_UTF8);{$ENDIF} FProc:=TProcess.Create(nil); FProc.Options := [poUsePipes, poStderrToOutPut]; FProc.Executable:={$IFDEF MSWINDOWS}'cmd'{$ELSE}'sh'{$ENDIF}; FProc.Execute; sleep(100); OutputStd; FTerminated:=False; end; destructor TTgShellDaemon.Destroy; begin FreeAndNil(FProc); FreeAndNil(FConf); FreeAndNil(FBot); inherited Destroy; end; function TTgShellDaemon.Install: Boolean; {$IFDEF MSWINDOWS} var VSM: TServiceManager; {$ENDIF} begin Result := inherited Install; {$IFDEF MSWINDOWS} VSM := TServiceManager.Create(nil); try VSM.Connect; if VSM.Connected then VSM.StartService('TelegramShellBot', nil); VSM.Disconnect; finally VSM.Free; end; {$ENDIF} WriteLn('Service installed.'); WriteLn('Some help from terminal'); end; function TTgShellDaemon.Uninstall: Boolean; {$IFDEF MSWINDOWS} var VSM: TServiceManager; {$ENDIF} begin Result := inherited Uninstall; {$IFDEF MSWINDOWS} VSM := TServiceManager.Create(nil); try VSM.Connect; if VSM.Connected then VSM.StopService('TelegramShellBot', True); VSM.Disconnect; finally VSM.Free; end; {$ENDIF} WriteLn('Service uninstalled.'); end; function TTgShellDaemon.Execute: Boolean; begin while not FTerminated do FBot.getUpdatesEx(0, 10); Result:=True; end; function TTgShellDaemon.Stop: Boolean; begin Result:=inherited Stop; FTerminated:=True; end; initialization AppDir:=IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))); RegisterDaemonClass(TTgShellDaemon); RegisterDaemonMapper(TTgShellMapper); end.
unit FocusMonitorForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TfrmFocusMonitor = class(TForm) btStart: TButton; edInterval: TEdit; Memo1: TMemo; btClear: TButton; tmrFocus: TTimer; rgWinType: TRadioGroup; procedure btClearClick(Sender: TObject); procedure btStartClick(Sender: TObject); procedure tmrFocusTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmFocusMonitor: TfrmFocusMonitor; implementation {$R *.dfm} procedure TfrmFocusMonitor.btClearClick(Sender: TObject); begin Memo1.Lines.Clear; end; procedure TfrmFocusMonitor.btStartClick(Sender: TObject); begin if tmrFocus.Enabled then begin tmrFocus.Enabled := false; end else begin tmrFocus.Interval := StrToIntDef(edInterval.Text, 1000); tmrFocus.Enabled := true; end; if tmrFocus.Enabled then begin btstart.Caption := 'stop'; end else begin btstart.Caption := 'start'; end; end; procedure TfrmFocusMonitor.FormCreate(Sender: TObject); begin rgwintype.ItemIndex := 0; end; procedure TfrmFocusMonitor.tmrFocusTimer(Sender: TObject); var s: string; wnd: HWND; wnclassname: array[0..255] of Char; begin case rgwintype.ItemIndex of 1: begin wnd := Windows.GetForegroundWindow; end; 2: begin wnd := Windows.GetActiveWindow; end; 3: begin wnd := Windows.GetCapture; end; 4: begin // wnd := Windows.GetTopWindow(); end else wnd := Windows.GetFocus; end; FillChar(wnclassname, SizeOf(wnclassname), 0); GetClassName(wnd, @wnclassname[0], 255); s := IntToStr(wnd) + ' | ' + string(wnclassname) + ' | '; FillChar(wnclassname, SizeOf(wnclassname), 0); GetWindowText(wnd, @wnclassname[0], 255); s := s + string(wnclassname); Memo1.Lines.Add(s); end; end.
unit fpcorm_common_types; {< @author(Andreas Lorenzen) @created(2014-06-25) @abstract(Common types, inherited into other objects throughout the project.) This unit contains common interface declarations, that are applied in multiple other places in the project. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, FGL, fpcorm_common_interfaces; type { A list type, for containing multiple subjects } TfoObserverList = specialize TFPGList<IfoObserver>; { The procedure signature, that the subject will use to notify the observer } //TfoOnObserverSubjectChangeEvent = procedure(aSubject: IfoObserverSubject) of object; { TfoObserverSubject } TfoObserverSubject = class(TInterfacedPersistent, IfoObserverSubject) private fObserverList: TfoObserverList; protected procedure NotifyAllObservers; public constructor Create; destructor Destroy; override; procedure AttachObserver(aObserver: IfoObserver); procedure DetachObserver(aObserver: IfoObserver); end; TfoObserver = class(TfoObserverSubject, IfoObserver) //private // fOnSubjectChangeEvent: TfoOnObserverSubjectChangeEvent; public procedure ReceiveSubjectUpdate(aSubject: IfoObserverSubject); virtual; //property OnUpdate: TfoOnObserverSubjectChangeEvent read fOnSubjectChangeEvent write fOnSubjectChangeEvent; end; implementation procedure TfoObserver.ReceiveSubjectUpdate(aSubject: IfoObserverSubject); begin NotifyAllObservers; //if Assigned(OnUpdate) then // OnUpdate(aSubject); end; { TfoObserverSubject } procedure TfoObserverSubject.NotifyAllObservers; var lObserver: IfoObserver; begin for lObserver in fObserverList do if Assigned(lObserver) then lObserver.ReceiveSubjectUpdate(Self); end; constructor TfoObserverSubject.Create; begin inherited Create; fObserverList := TfoObserverList.Create; end; destructor TfoObserverSubject.Destroy; begin if Assigned(fObserverList) then fObserverList.Free; inherited Destroy; end; procedure TfoObserverSubject.AttachObserver(aObserver: IfoObserver); const lProcedureName = 'AttachObserver'; begin if not Assigned(aObserver) then raise Exception.Create(Self.ClassName + lProcedureName + ': ' + 'aObserver parameter not assigned.'); if Assigned(fObserverList) then fObserverList.Add(aObserver); end; procedure TfoObserverSubject.DetachObserver(aObserver: IfoObserver); const lProcedureName = 'DetachObserver'; begin if not Assigned(aObserver) then raise Exception.Create(Self.ClassName + lProcedureName + ': ' + 'aObserver parameter not assigned.'); if Assigned(fObserverList) then fObserverList.Remove(aObserver); end; end.
{$MODE OBJFPC} Const ginp='countmod.inp'; gout='countmod.out'; Var st:longint; a,b:array[1..7] of int64; Function Diophante(a,b,c:int64; var xx,lcm:int64):boolean; Var m,n,r,xm,xn,xr,q:int64; Begin m:=a; n:=b; xm:=1; xn:=0; while n<>0 do begin q:=m div n; r:=m-q*n; xr:=xm-q*xn; m:=n; xm:=xn; n:=r; xn:=xr; end; result:=c mod m=0; if not result then exit; lcm:=abs(a div m*b); q:=lcm div a; xx:=(c div m*xm mod q+q) mod q; End; Function Solve(a1,b1,a2,b2:int64; var x,lcm:int64):boolean; Begin result:=diophante(a1,-a2,b2-b1,x,lcm); if not result then exit; x:=(a1*x+b1) mod lcm; End; Procedure Enter; Var i:longint; Begin for i:=1 to 4 do readln(a[i],b[i]); End; Function Process:int64; Begin if not solve(a[1],b[1],a[2],b[2],b[5],a[5]) then exit(-1); if not solve(a[3],b[3],a[4],b[4],b[6],a[6]) then exit(-1); if not solve(a[5],b[5],a[6],b[6],b[7],a[7]) then exit(-1); result:=b[7]; End; Begin Assign(input,ginp); Assign(output,gout); Reset(input); Rewrite(output); readln(st); while st>0 do begin Enter; writeln(Process); dec(st); end; Close(input); Close(output); End.
unit uMainFMX; 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.FMXUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, System.Rtti, FMX.Grid.Style, Fmx.Bind.Grid, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Controls, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, FMX.Layouts, Fmx.Bind.Navigator, Data.Bind.Grid, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Grid, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.Bind.DBScope, FireDAC.Comp.UI; type TFormMain = class(TForm) FDConnectionSQLite_Demo: TFDConnection; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; BindSourceDB1: TBindSourceDB; FDQuery1: TFDQuery; StringGridBindSourceDB1: TStringGrid; LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource; NavigatorBindSourceDB1: TBindNavigator; BindingsList1: TBindingsList; private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} end.
unit vcmImageListForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Buttons, ImgList, ExtCtrls, DesignEditors; type TvcmImageList = class(TForm) ListView: TListView; BitBtn1: TBitBtn; BitBtn2: TBitBtn; procedure ListViewDblClick(Sender: TObject); procedure ListViewResize(Sender: TObject); private { Private declarations } public { Public declarations } class function Execute(anEditor : TPropertyEditor; anImages : TCustomImageList): Boolean; {-} end; implementation {$R *.dfm} // start class TvcmImageList class function TvcmImageList.Execute(anEditor : TPropertyEditor; anImages : TCustomImageList): Boolean; {-} var l_Index : Integer; begin if (anImages = nil) OR (anEditor = nil) then Result := false else with Create(nil) do try with ListView do begin LargeImages := anImages; SmallImages := anImages; with Items do begin Clear; for l_Index := 0 to Pred(anImages.Count) do with Add do begin Caption := IntToStr(l_Index); ImageIndex := l_Index; end;//with Add end;//with Items try ItemIndex := StrToInt(anEditor.GetValue); except ItemIndex := -1; end;//try..except end;//with ListView Result := (ShowModal = mrOk); if Result then anEditor.SetValue(IntToStr(ListView.ItemIndex)); finally Free; end;//try..finally end; procedure TvcmImageList.ListViewDblClick(Sender: TObject); begin if (ListView.ItemIndex >= 0) then ModalResult := mrOk; end; procedure TvcmImageList.ListViewResize(Sender: TObject); begin ListView.Arrange(arDefault); end; end.
(*==========================================================================* | unitEXGraphics | | | | Provides extended cursor and icon graphic objects that support 256 | | colors, etc. | | | | Version Date By Description | | ------- ---------- ---- --------------------------------------------- | | 2.0 23/2/2000 CPWW Original | *==========================================================================*) unit unitEXGraphics; interface uses Windows, Sysutils, Classes, Graphics, clipbrd, commctrl, controls; type //============================================================================= // TIconHeader resource structure - corresponds to NEWHEADER in MSDN and contains // the details for a Icon or Cursor group resource TIconHeader = packed record wReserved : word; wType : word; // 1 for icons wCount : word; // Number of components end; PIconHeader = ^TIconHeader; //============================================================================= // TExIconImage class - Shared image structure for icons & cursors TExIconImage = class (TSharedImage) FHandle: HICON; FMemoryImage: TCustomMemoryStream; protected procedure FreeHandle; override; public destructor Destroy; override; end; //============================================================================= // TIconCursor class - Base graphic class for TExIcon & TExCursor TIconCursor = class (TGraphic) private FIcon: TIcon; FImage: TExIconImage; fPixelFormat : TPixelFormat; fWidth, fHeight : Integer; fPalette : HPALETTE; fBitmapOffset : DWORD; // 0 for icons. 4 for cursors. fHotspot : DWORD; // Icons don't have hotspots!, but it's easier to // put it here function GetHandle: HICON; procedure NewImage(NewHandle: HICON; NewImage: TMemoryStream); procedure SetHandle(const Value: HICON); procedure SetPixelFormat(const Value: TPixelFormat); function GetPixelFormat: TPixelFormat; function GetColorCount: Integer; function GetBitsPerPixel: Integer; function GetIcon: TIcon; protected procedure HandleNeeded; virtual; abstract; procedure ImageNeeded; virtual; abstract; function GetEmpty: Boolean; override; function GetWidth : Integer; override; function GetHeight : Integer; override; procedure SetWidth (value : Integer); override; procedure SetHeight (value : Integer); override; procedure Draw(ACanvas: TCanvas; const Rect: TRect); override; function GetPalette : HPALETTE; override; public constructor Create; override; destructor Destroy; override; procedure Assign (source : TPersistent); override; procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); override; procedure LoadFromStream(Stream: TStream); override; function ReleaseHandle: HICON; procedure SaveToClipboardFormat(var Format: Word; var Data: THandle; var APalette: HPALETTE); override; procedure SaveToStream(Stream: TStream); override; property Handle: HICON read GetHandle write SetHandle; property PixelFormat : TPixelFormat read GetPixelFormat write SetPixelFormat; property ColorCount : Integer read GetColorCount; property BitsPerPixel : Integer read GetBitsPerPixel; property Icon: TIcon read GetIcon; end; //============================================================================= // TExIcon class TExIcon = class (TIconCursor) protected procedure HandleNeeded; override; procedure ImageNeeded; override; public constructor Create; override; end; //============================================================================= // TExCursor class TExCursor = class (TIconCursor) private function GetHotspot: DWORD; procedure SetHotspot(const Value: DWORD); protected procedure HandleNeeded; override; procedure ImageNeeded; override; public constructor Create; override; property Hotspot : DWORD read GetHotspot write SetHotspot; end; var SystemPalette256 : HPALETTE; SystemPalette2 : HPALETTE; type TReal = single; EColorError = exception; const HLSMAX = 240; function CreateDIBPalette (const bmi : TBitmapInfo) : HPalette; function CreateMappedBitmap (source : TBitmap; palette : HPALETTE; hiPixelFormat : TPixelFormat) : TBitmap; procedure AssignBitmapFromIconCursor (dst : TBitmap; src : TIconCursor; transparentColor : TColor); procedure AssignIconCursorFromBitmap (dst : TIconCursor; source : TBitmap; palette : HPALETTE; transparentColor : TColor); procedure iHLSToRGB (hue, lum, sat : Integer; var r, g, b : Integer); implementation resourceString rstInvalidIcon = 'Invalid Icon or Cursor'; rstInvalidBitmap = 'Invalid Bitmap'; rstInvalidPixelFormat = 'Pixel Format Not Valid for Icons or Cursors'; rstNoClipboardSupport = 'Clipboard not supported for Icons or Cursors'; rstCantResize = 'Can''t resize Icons or Cursors'; rstCantReformat = 'Can''t change PixelFormat for Icons or Cursors'; (*----------------------------------------------------------------------------* | procedure InitializeBitmapInfoHeader () | | | | Stolen from graphics.pas | *----------------------------------------------------------------------------*) procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var BI: TBitmapInfoHeader; Colors: Integer); var DS: TDIBSection; Bytes: Integer; begin DS.dsbmih.biSize := 0; Bytes := GetObject(Bitmap, SizeOf(DS), @DS); if Bytes = 0 then raise EInvalidGraphic.Create (rstInvalidBitmap) else if (Bytes >= (sizeof(DS.dsbm) + sizeof(DS.dsbmih))) and (DS.dsbmih.biSize >= DWORD(sizeof(DS.dsbmih))) then BI := DS.dsbmih else begin FillChar(BI, sizeof(BI), 0); with BI, DS.dsbm do begin biSize := SizeOf(BI); biWidth := bmWidth; biHeight := bmHeight; end; end; case Colors of 1,2: BI.biBitCount := 1; 3..16 : begin BI.biBitCount := 4; BI.biClrUsed := Colors end; 17..256 : begin BI.biBitCount := 8; BI.biClrUsed := Colors end; else BI.biBitCount := DS.dsbm.bmBitsPixel * DS.dsbm.bmPlanes; end; BI.biPlanes := 1; if BI.biClrImportant > BI.biClrUsed then BI.biClrImportant := BI.biClrUsed; if BI.biSizeImage = 0 then BI.biSizeImage := BytesPerScanLine(BI.biWidth, BI.biBitCount, 32) * Abs(BI.biHeight); end; (*----------------------------------------------------------------------------* | procedure InternalGetDIBSizes () | | | | Stolen from graphics.pas | *----------------------------------------------------------------------------*) procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: DWORD; var ImageSize: DWORD; Colors: Integer); var BI: TBitmapInfoHeader; begin InitializeBitmapInfoHeader(Bitmap, BI, Colors); if BI.biBitCount > 8 then begin InfoHeaderSize := SizeOf(TBitmapInfoHeader); if (BI.biCompression and BI_BITFIELDS) <> 0 then Inc(InfoHeaderSize, 12); end else if BI.biClrUsed = 0 then InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * (1 shl BI.biBitCount) else InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * BI.biClrUsed; ImageSize := BI.biSizeImage; end; (*----------------------------------------------------------------------------* | procedure InternalGetDIB () | | | | Stolen from graphics.pas | *----------------------------------------------------------------------------*) function InternalGetDIB(Bitmap: HBITMAP; Palette: HPALETTE; var BitmapInfo; var Bits; Colors: Integer): Boolean; var OldPal: HPALETTE; DC: HDC; begin InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo), Colors); OldPal := 0; DC := CreateCompatibleDC(0); try if Palette <> 0 then begin OldPal := SelectPalette(DC, Palette, False); RealizePalette(DC); end; Result := GetDIBits(DC, Bitmap, 0, TBitmapInfoHeader(BitmapInfo).biHeight, @Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0; finally if OldPal <> 0 then SelectPalette(DC, OldPal, False); DeleteDC(DC); end; end; (*----------------------------------------------------------------------------* | procedure CreateDIBPalette () | | | | Create the palette from bitmap resource info. | *----------------------------------------------------------------------------*) function CreateDIBPalette (const bmi : TBitmapInfo) : HPalette; var lpPal : PLogPalette; i : Integer; numColors : Integer; begin result := 0; if bmi.bmiHeader.biBitCount <= 8 then NumColors := 1 shl bmi.bmiHeader.biBitCount else NumColors := 0; // No palette needed for 24 BPP DIB if bmi.bmiHeader.biClrUsed > 0 then NumColors := bmi.bmiHeader.biClrUsed; // Use biClrUsed if NumColors > 0 then begin if NumColors = 1 then result := CopyPalette (SystemPalette2) else begin GetMem (lpPal, sizeof (TLogPalette) + sizeof (TPaletteEntry) * NumColors); try lpPal^.palVersion := $300; lpPal^.palNumEntries := NumColors; {$R-} for i := 0 to NumColors -1 do begin lpPal^.palPalEntry[i].peRed := bmi.bmiColors [i].rgbRed; lpPal^.palPalEntry[i].peGreen := bmi.bmiColors[i].rgbGreen; lpPal^.palPalEntry[i].peBlue := bmi.bmiColors[i].rgbBlue; lpPal^.palPalEntry[i].peFlags := 0 //bmi.bmiColors[i].rgbReserved; end; {$R+} result := CreatePalette (lpPal^) finally FreeMem (lpPal) end end end end; (*----------------------------------------------------------------------------* | procedure ReadIcon () | | | | Creates an HIcon and a HPalette from a icon resource stream. | *----------------------------------------------------------------------------*) procedure ReadIcon(Stream: TStream; var Icon: HICON; var palette : HPALETTE; isIcon : boolean); var buffer : PByte; info : PBitmapInfoHeader; size, offset : DWORD; begin size := stream.Size - stream.Position; if IsIcon then // Cursor resources have DWORD hotspot before the BitmapInfo offset := 0 else offset := sizeof (DWORD); if size > sizeof (TBitmapInfoHeader) + offset then begin GetMem (buffer, stream.Size - stream.Position); try stream.ReadBuffer (buffer^, stream.Size - stream.Position); info := PBitmapInfoHeader (PChar (buffer) + offset); icon := CreateIconFromResourceEx (buffer, size, isIcon, $00030000, info^.biWidth, info^.biHeight div 2, LR_DEFAULTCOLOR); (* dc := GetDC (HWND_DESKTOP); try DrawIconEx (dc, 0, 0, icon, info^.biWidth, info^.biHeight div 2, 0, 0, DI_NORMAL) finally ReleaseDC (0, dc) end; *) if icon = 0 then raise EInvalidGraphic.Create (rstInvalidIcon); palette := CreateDIBPalette (PBitmapInfo (PChar (buffer) + offset)^); finally FreeMem (buffer) end end end; (*----------------------------------------------------------------------------* | procedure WriteIcon () | | | | Write an icon to a stream. Pass in the color count, rather than getting | | it from the color bitmap - the chances are we already know it. | *----------------------------------------------------------------------------*) procedure WriteIcon(Stream: TStream; Icon: HICON; colors : Integer; isIcon : boolean); var IconInfo: TIconInfo; MonoInfoSize, ColorInfoSize: DWORD; MonoBitsSize, ColorBitsSize: DWORD; MonoInfo, MonoBits, ColorInfo, ColorBits: Pointer; cursorHotspot : DWORD; begin GetIconInfo(Icon, IconInfo); cursorHotspot := MAKELONG (IconInfo.xHotspot, IconInfo.yHotspot); try InternalGetDIBSizes(IconInfo.hbmMask, MonoInfoSize, MonoBitsSize, 2); InternalGetDIBSizes(IconInfo.hbmColor, ColorInfoSize, ColorBitsSize, colors); MonoInfo := nil; MonoBits := nil; ColorInfo := nil; ColorBits := nil; try MonoInfo := AllocMem(MonoInfoSize); MonoBits := AllocMem(MonoBitsSize); ColorInfo := AllocMem(ColorInfoSize); ColorBits := AllocMem(ColorBitsSize); InternalGetDIB(IconInfo.hbmMask, 0, MonoInfo^, MonoBits^, 2); InternalGetDIB(IconInfo.hbmColor, 0, ColorInfo^, ColorBits^, colors); with PBitmapInfoHeader(ColorInfo)^ do Inc(biHeight, biHeight); { color height includes mono bits } if not isIcon then Stream.Write (cursorHotspot, sizeof (cursorHotspot)); Stream.Write(ColorInfo^, ColorInfoSize); Stream.Write(ColorBits^, ColorBitsSize); Stream.Write(MonoBits^, MonoBitsSize); finally FreeMem(ColorInfo, ColorInfoSize); FreeMem(ColorBits, ColorBitsSize); FreeMem(MonoInfo, MonoInfoSize); FreeMem(MonoBits, MonoBitsSize); end; finally DeleteObject(IconInfo.hbmColor); DeleteObject(IconInfo.hbmMask); end end; (*----------------------------------------------------------------------------* | procedure AssignBitmapFromIconCursor | | | | Copy an icon to a bitmap. Where the icon is transparent, set the bitmap | | to 'transparentColor' | *----------------------------------------------------------------------------*) procedure AssignBitmapFromIconCursor (dst : TBitmap; src : TIconCursor; transparentColor : TColor); var r : TRect; begin dst.Assign (Nil); dst.Width := src.Width; dst.Height := src.Height; dst.PixelFormat := pfDevice; with dst.Canvas do begin brush.Color := GetNearestColor (Handle, transparentColor); r := Rect (0, 0, dst.Width, dst.Height); FillRect (r); Draw (0, 0, src) end end; (*----------------------------------------------------------------------------* | procedure MaskBitmapBits | | | | Kinda like MaskBlt - but without the bugs. | *----------------------------------------------------------------------------*) procedure MaskBitmapBits (bits : PChar; pixelFormat : TPixelFormat; mask : PChar; width, height : DWORD; palette : HPalette); var bpScanline, maskbpScanline : Integer; bitsPerPixel, i, j : Integer; maskbp, bitbp : byte; maskp, bitp : PChar; maskPixel : boolean; maskByte: dword; maskU : UINT; maskColor : byte; maskColorByte : byte; begin // Get 'black' color index. This is usually 0 // but some people play jokes... if palette <> 0 then begin maskU := GetNearestPaletteIndex (palette, RGB (0, 0, 0)); if maskU = CLR_INVALID then raiseLastWin32Error; maskColor := maskU end else maskColor := 0; case PixelFormat of // Get bits per pixel pf1Bit : bitsPerPixel := 1; pf4Bit : bitsPerPixel := 4; pf8Bit : bitsPerPixel := 8; pf15Bit, pf16Bit : bitsPerPixel := 16; pf24Bit : bitsPerPixel := 24; pf32Bit : bitsPerPixel := 32; else raise EInvalidGraphic.Create (rstInvalidPixelFormat); end; // Get byte count for mask and bitmap // scanline. Can be weird because of padding. bpScanline := BytesPerScanLine(width, bitsPerPixel, 32); maskbpScanline := BytesPerScanline (width, 1, 32); maskByte := $ffffffff; // Set constant values for 8bpp masks maskColorByte := maskColor; for i := 0 to height - 1 do // Go thru each scanline... begin maskbp := 0; // Bit offset in current mask byte bitbp := 0; // Bit offset in current bitmap byte maskp := mask; // Pointer to current mask byte bitp := bits; // Pointer to current bitmap byte; for j := 0 to width - 1 do // Go thru each pixel begin // Pixel should be masked? maskPixel := (byte (maskp^) and ($80 shr maskbp)) <> 0; if maskPixel then begin case bitsPerPixel of 1, 4, 8 : begin case bitsPerPixel of // Calculate bit mask and 'black' color bits 1 : begin maskByte := $80 shr bitbp; maskColorByte := maskColor shl (7 - bitbp); end; 4 : begin maskByte := $f0 shr bitbp; maskColorByte := maskColor shl (4 - bitbp) end end; // Apply the mask bitp^ := char ((byte (bitp^) and (not maskByte)) or maskColorByte); end; 15, 16 : PWORD (bitp)^ := 0; 24 : begin PWORD (bitp)^ := 0; PBYTE (bitp + sizeof (WORD))^ := 0 end; 32 : PDWORD (bitp)^ := 0 end end; Inc (maskbp); // Next mask bit if maskbp = 8 then begin maskbp := 0; Inc (maskp) // Next mask byte end; Inc (bitbp, bitsPerPixel); // Next bitmap bit(s) while bitbp >= 8 do begin Dec (bitbp, 8); Inc (bitp) // Next bitmap byte end end; Inc (mask, maskbpScanline); // Set mask for start of next line Inc (bits, bpScanLine) // Set bits to start of next line end end; (*----------------------------------------------------------------------------* | procedure CreateMappedBitmap | | | | Copy a bitmap and apply a palette. | *----------------------------------------------------------------------------*) function CreateMappedBitmap (source : TBitmap; palette : HPALETTE; hiPixelFormat : TPixelFormat) : TBitmap; var colorCount : word; begin result := TBitmap.Create; if palette <> 0 then begin result.Width := source.Width; result.Height := source.Height; if GetObject (palette, sizeof (colorCount), @colorCount) = 0 then RaiseLastWin32Error; case colorCount of 1..2 : result.PixelFormat := pf1Bit; 3..16 : result.PixelFormat := pf4Bit; 17..256 : result.PixelFormat := pf8Bit; else result.PixelFormat := source.PixelFormat end; result.Palette := CopyPalette (palette); result.Canvas.Draw (0, 0, source); end else begin result.PixelFormat := hiPixelFormat; result.Height := source.Height; result.Width := source.Width; result.Canvas.Draw (0, 0, source); end end; (*----------------------------------------------------------------------------* | procedure AssignIconCursorFromBitmap | | | | Copy a bitmap to an icon using the correct palette. Where the bitmap | | matches the transparent color, | | make the icon transparent. | *----------------------------------------------------------------------------*) procedure AssignIconCursorFromBitmap (dst : TIconCursor; source : TBitmap; palette : HPALETTE; transparentColor : TColor); var maskBmp : TBitmap; infoHeaderSize, imageSize : DWORD; maskInfoHeaderSize, maskImageSize : DWORD; maskInfo, maskBits : PChar; strm : TMemoryStream; offset : DWORD; src : TBitmap; begin src := Nil; maskBmp := TBitmap.Create; try src := CreateMappedBitmap (source, palette, dst.PixelFormat); maskBmp.Assign (source); // Get mask bitmap - White where the transparent color maskBmp.Mask (transparentColor); // occurs, otherwise blck. maskBmp.PixelFormat := pf1Bit; // Get size for mask bits buffer GetDibSizes (maskBmp.Handle, maskInfoHeaderSize, maskImageSize); GetMem (maskBits, maskImageSize); // Allocate mask buffers GetMem (maskInfo, maskInfoHeaderSize); try // Get mask bits GetDib (maskBmp.Handle, 0, maskInfo^, maskBits^); // Get size for color bits buffer GetDibSizes (src.Handle, infoHeaderSize, imageSize); // Create a memory stream to assemble the icon image strm := TMemoryStream.Create; try if dst is TExCursor then offset := sizeof (DWORD) else offset := 0; strm.Size := infoHeaderSize + imageSize + maskImageSize + offset; GetDib (src.Handle, src.Palette, (PChar (strm.Memory) + offset)^, (PChar (strm.Memory) + infoHeaderSize + offset)^); // Get the bitmap header, palette & bits, then try with src do MaskBitmapBits (PChar (strm.Memory) + infoHeaderSize + offset, PixelFormat, maskBits, Width, Height, Palette) except end; // Apply the mask to the bitmap bits. We can't use BitBlt (.. SrcAnd) because // of PRB Q149585 Move (maskBits^, (PChar (strm.Memory) + infoHeaderSize + imageSize + offset)^, maskImageSize); // Tag on the mask. We now have the correct icon bits with PBitmapInfo (PChar (strm.Memory) + offset)^.bmiHeader do biHeight := biHeight * 2; // Adjust height for 'funky icon height' thing if dst is TExCursor then PDWORD (strm.Memory)^ := TExCursor (dst).Hotspot; dst.LoadFromStream (strm); finally strm.Free end finally FreeMem (maskInfo); FreeMem (maskBits); end finally maskBmp.Free; src.Free; end end; (*----------------------------------------------------------------------------* | procedure StrechDrawIcon | | | | Why not use DrawIconEx?? Because it doesn't work. This is from Joe Hecht | *----------------------------------------------------------------------------*) procedure StretchDrawIcon(DC : HDC; IconHandle : HIcon; x : integer; y : integer; Width : integer; Height : integer); var IconInfo : TIconInfo; bmMaskInfo : Windows.TBitmap; maskDC : HDC; OldTextColor : TColor; OldBkColor : TColor; oldMaskBm : HBitmap; procedure DrawMonoIcon; var bmMaskInfobmHeightdiv2 : Integer; begin bmMaskInfobmHeightdiv2 := bmMaskInfo.bmHeight div 2; StretchBlt(DC, x, y, Width, Height, maskDC, 0, 0, bmMaskInfo.bmWidth, bmMaskInfobmHeightdiv2, SRCAND); StretchBlt(DC, x, y, Width, Height, maskDC, 0, bmMaskInfobmHeightdiv2, bmMaskInfo.bmWidth, bmMaskInfobmHeightdiv2, SRCINVERT) end; procedure DrawColorIcon; var bmColorInfo : Windows.TBitmap; colorDC : HDC; oldColorBm : HBITMAP; begin if (IconInfo.hbmColor <> 0) then begin GetObject(IconInfo.hbmColor, sizeof(bmColorInfo), @bmColorInfo); colorDC := CreateCompatibleDc(0); if colorDC <> 0 then try oldColorBm := SelectObject(colorDC, IconInfo.hbmColor); try TransparentStretchBlt (DC, x, y, Width, Height, colorDC, 0, 0, bmColorInfo.bmWidth, bmColorInfo.bmHeight, maskDC, 0, 0); finally SelectObject (colorDC, oldColorBm) end finally DeleteDC (colorDC) end end end; begin // StretchDrawIcon if GetIconInfo (IconHandle, IconInfo) then try if IconInfo.hbmMask <> 0 then begin OldTextColor := SetTextColor(DC, RGB (0, 0, 0)); OldBkColor := SetBkColor(DC, RGB (255, 255, 255)); GetObject(IconInfo.hbmMask, sizeof(bmMaskInfo), @bmMaskInfo); try maskDC := CreateCompatibleDC (0); if maskDC <> 0 then try oldMaskbm := SelectObject(maskDC, IconInfo.hbmMask); try if ((bmMaskInfo.bmBitsPixel * bmMaskInfo.bmPlanes = 1) and (IconInfo.hbmColor = 0)) then DrawMonoIcon else DrawColorIcon finally SelectObject (maskDC, oldMaskBm) end finally DeleteDC (maskDC) end finally SetTextColor(DC, OldTextColor); SetBkColor(DC, OldBkColor) end end finally if IconInfo.hbmMask <> 0 then DeleteObject (IconInfo.hbmMask); if IconInfo.hbmColor <> 0 then DeleteObject (IconInfo.hbmColor) end end; (*----------------------------------------------------------------------------* | function Create256ColorPalette; | | | | Does what it says on the tin.. | *----------------------------------------------------------------------------*) function Create256ColorPalette : HPALETTE; var dc : HDC; caps : Integer; logPalette : PLOGPALETTE; i : Integer; c : Integer; const palColors256 : array [0..255] of TColor = ( $000000, $000080, $008000, $008080, $800000, $800080, $808000, $C0C0C0, $5088B0, $B0C8E0, $00002C, $000056, $000087, $0000C0, $002C00, $002C2C, $002C56, $002C87, $002CC0, $002CFF, $005600, $00562C, $005656, $005687, $0056C0, $0056FF, $008700, $00872C, $008756, $008787, $0087C0, $0087FF, $00C000, $00C02C, $00C056, $00C087, $00C0C0, $00C0FF, $00FF2C, $00FF56, $00FF87, $00FFC0, $2C0000, $2C002C, $2C0056, $2C0087, $2C00C0, $2C00FF, $2C2C00, $2C2C2C, $2C2C56, $2C2C87, $2C2CC0, $2C2CFF, $2C5600, $2C562C, $2C5656, $2C5687, $2C56C0, $2C56FF, $2C8700, $2C872C, $2C8756, $2C8787, $2C87C0, $2C87FF, $2CC000, $2CC02C, $2CC056, $2CC087, $2CC0C0, $2CC0FF, $2CFF00, $2CFF2C, $2CFF56, $2CFF87, $2CFFC0, $2CFFFF, $560000, $56002C, $560056, $560087, $5600C0, $5600FF, $562C00, $562C2C, $562C56, $562C87, $562CC0, $562CFF, $565600, $56562C, $565656, $565687, $5656C0, $5656FF, $568700, $56872C, $568756, $568787, $5687C0, $5687FF, $56C000, $56C02C, $56C056, $56C087, $56C0C0, $56C0FF, $56FF00, $56FF2C, $56FF56, $56FF87, $56FFC0, $56FFFF, $870000, $87002C, $870056, $870087, $8700C0, $8700FF, $872C00, $872C2C, $872C56, $872C87, $872CC0, $872CFF, $875600, $87562C, $875656, $875687, $8756C0, $8756FF, $878700, $87872C, $878756, $878787, $8787C0, $8787FF, $87C000, $87C02C, $87C056, $87C087, $87C0C0, $87C0FF, $87FF00, $87FF2C, $87FF56, $87FF87, $87FFC0, $87FFFF, $C00000, $C0002C, $C00056, $C00087, $C000C0, $C000FF, $C02C00, $C02C2C, $C02C56, $C02C87, $C02CC0, $C02CFF, $C05600, $C0562C, $C05656, $C05687, $C056C0, $C056FF, $C08700, $C0872C, $C08756, $C08787, $C087C0, $C087FF, $C0C000, $C0C02C, $C0C056, $C0C087, $C0C0FF, $C0FF00, $C0FF2C, $C0FF56, $C0FF87, $C0FFC0, $C0FFFF, $FF002C, $FF0056, $FF0087, $FF00C0, $FF2C00, $FF2C2C, $FF2C56, $FF2C87, $FF2CC0, $FF2CFF, $FF5600, $FF562C, $FF5656, $FF5687, $FF56C0, $FF56FF, $FF8700, $FF872C, $FF8756, $FF8787, $FF87C0, $FF87FF, $FFC000, $FFC02C, $FFC056, $FFC087, $FFC0C0, $FFC0FF, $FFFF2C, $FFFF56, $FFFF87, $FFFFC0, $111111, $181818, $1E1E1E, $252525, $343434, $3C3C3C, $444444, $4D4D4D, $5F5F5F, $696969, $727272, $7D7D7D, $929292, $9D9D9D, $A8A8A8, $B4B4B4, $CCCCCC, $D8D8D8, $E5E5E5, $F2F2F2, $556DFF, $AA6DFF, $FF6DFF, $0092FF, $5592FF, $AA92FF, $FF92FF, $00B6FF, $55B6FF, $D8E4F0, $A4A0A0, $808080, $0000FF, $00FF00, $00FFFF, $FF0000, $FF00FF, $FFFF00, $FFFFFF); begin logPalette := Nil; dc := GetDC (0); try GetMem (logPalette, sizeof (logPalette) + 256 * sizeof (PALETTEENTRY)); logPalette^.palVersion := $300; logPalette^.palNumEntries := 256; caps := GetDeviceCaps (dc, RASTERCAPS); if ((caps and RC_PALETTE) <> 0) and (GetSystemPaletteEntries (dc, 0, 256, logPalette^.palPalEntry) = 256) then result := CreatePalette (logPalette^) else begin {$R-} for i := 0 to 255 do with logPalette^.palPalEntry [i] do begin c := palColors256 [i]; peRed := c and $ff; peGreen := c shr 8 and $ff; peBlue := c shr 16 and $ff end; {$R+} result := CreatePalette (logPalette^); end finally ReleaseDC (0, dc); if Assigned (logPalette) then FreeMem (logPalette) end end; (*----------------------------------------------------------------------------* | function Create2ColorPalette; | | | | Does what it says on the tin.. | *----------------------------------------------------------------------------*) function Create2ColorPalette : HPALETTE; const palColors2 : array [0..1] of TColor = ($000000, $ffffff); var logPalette : PLogPalette; i, c : Integer; begin GetMem (logPalette, sizeof (logPalette) + 2 * sizeof (PALETTEENTRY)); try logPalette^.palVersion := $300; logPalette^.palNumEntries := 2; {$R-} for i := 0 to 1 do with logPalette^.palPalEntry [i] do begin c := palColors2 [i]; peRed := c and $ff; peGreen := c shr 8 and $ff; peBlue := c shr 16 and $ff end; {$R+} result := CreatePalette (logPalette^); finally FreeMem (logPalette) end end; { TIconCursor } (*----------------------------------------------------------------------------* | procedure TIconCursor.Assign | | | | Assign one from another. | *----------------------------------------------------------------------------*) procedure TIconCursor.Assign(source: TPersistent); begin if source is TIconCursor then begin if Source <> nil then begin TIconCursor(Source).FImage.Reference; FImage.Release; FImage := TIconCursor(Source).FImage; fPixelFormat := TIconCursor (source).fPixelFormat; fWidth := TIconCursor (source).fWidth; fHeight := TIconCursor (source).fHeight; fHotspot := TIconCursor (source).fHotspot; if fPalette <> 0 then begin DeleteObject (fPalette); fPalette := 0 end end else NewImage(0, nil); Changed(Self); Exit; end; inherited Assign (source) end; (*----------------------------------------------------------------------------* | constructor TIconCursor.Create | *----------------------------------------------------------------------------*) constructor TIconCursor.Create; begin inherited Create; FImage := TExIconImage.Create; FIcon := TIcon.Create; FImage.Reference; end; (*----------------------------------------------------------------------------* | destructor TIconCursor.Destroy; | *----------------------------------------------------------------------------*) destructor TIconCursor.Destroy; begin FIcon.Free; FImage.Release; if FPalette <> 0 then DeleteObject (FPalette); inherited Destroy end; (*----------------------------------------------------------------------------* | procedure TIconCursor.Draw () | | | | Draw the icon/cursor on a canvas. Stretch it to the rect. | *----------------------------------------------------------------------------*) procedure TIconCursor.Draw(ACanvas: TCanvas; const Rect: TRect); begin with rect do if fPalette <> 0 then StretchDrawIcon (ACanvas.Handle, handle, left, top, right, bottom) else DrawIconEx (ACanvas.Handle, left, top, handle, right - left + 1, bottom - top + 1, 0, 0, DI_NORMAL) end; (*----------------------------------------------------------------------------* | function TIconCursor.GetColorCount | | | | Get the color count | *----------------------------------------------------------------------------*) function TIconCursor.GetColorCount: Integer; begin result := 1 shl BitsPerPixel end; (*----------------------------------------------------------------------------* | function TIconCursor.GetEmpty | | | | Returns true if we don't have a memory image or a handle. | *----------------------------------------------------------------------------*) function TIconCursor.GetEmpty: Boolean; begin with FImage do Result := (FHandle = 0) and (FMemoryImage = nil); end; (*----------------------------------------------------------------------------* | function TIconCursor.GetHandle | | | | Return the icons handle. Create one if necessary (ie. if we've only got | | a memory image. | *----------------------------------------------------------------------------*) function TIconCursor.GetHandle: HICON; begin HandleNeeded; Result := FImage.FHandle; end; (*----------------------------------------------------------------------------* | function TIconCursor.GetHeight | | | | Get the height. | *----------------------------------------------------------------------------*) function TIconCursor.GetHeight: Integer; begin HandleNeeded; result := fHeight; end; (*----------------------------------------------------------------------------* | procedure TIconCursor. | | | | Get the Palette. | *----------------------------------------------------------------------------*) function TIconCursor.GetPalette: HPALETTE; begin if fPalette = 0 then begin ImageNeeded; fPalette := CreateDIBPalette (PBitmapInfo (PChar (FImage.FMemoryImage.Memory) + fBitmapOffset)^); end; result := fPalette end; (*----------------------------------------------------------------------------* | function TIconCursor.GetPitsPerPixel | | | | Get bpp. | *----------------------------------------------------------------------------*) function TIconCursor.GetBitsPerPixel: Integer; begin case PixelFormat of pf1Bit : result := 1; pf4Bit : result := 4; pf8Bit : result := 8; pf15Bit, pf16Bit : result := 16; pf24Bit : result := 24; pf32Bit : result := 32; else raise EInvalidGraphic.Create (rstInvalidPixelFormat); end end; (*----------------------------------------------------------------------------* | function TIconCursor.GetPixelFormat | | | | Get the pixel format. | *----------------------------------------------------------------------------*) function TIconCursor.GetPixelFormat: TPixelFormat; begin HandleNeeded; result := fPixelFormat end; (*----------------------------------------------------------------------------* | function TIconCursor.GetWidth | | | | Get the width. | *----------------------------------------------------------------------------*) function TIconCursor.GetWidth: Integer; begin HandleNeeded; result := fWidth; end; (*----------------------------------------------------------------------------* | procedure TIconCursor.LoadFromClipboardFormat | | | | Load from clipboard format. Not supported. | *----------------------------------------------------------------------------*) procedure TIconCursor.LoadFromClipboardFormat(AFormat: Word; AData: THandle; APalette: HPALETTE); begin raise EInvalidGraphic.Create (rstNoClipboardSupport); end; (*----------------------------------------------------------------------------* | procedure TIconCursor.LoadFromStream | | | | Load the icon from a resource stream. | *----------------------------------------------------------------------------*) procedure TIconCursor.LoadFromStream(Stream: TStream); var Image: TMemoryStream; begin Image := TMemoryStream.Create; try Image.SetSize(Stream.Size - Stream.Position); Stream.ReadBuffer(Image.Memory^, Image.Size); NewImage(0, Image); except Image.Free; raise; end; Changed(Self); end; (*----------------------------------------------------------------------------* | procedure TIconCursor.NewImage | | | | Change the icon. | *----------------------------------------------------------------------------*) procedure TIconCursor.NewImage(NewHandle: HICON; NewImage: TMemoryStream); var Image: TExIconImage; begin Image := TExIconImage.Create; try Image.FHandle := NewHandle; Image.FMemoryImage := NewImage; except Image.Free; raise; end; Image.Reference; FImage.Release; FImage := Image; end; (*----------------------------------------------------------------------------* | procedure TIconCursor.ReleaseHandle | | | | Release the handle. | *----------------------------------------------------------------------------*) function TIconCursor.ReleaseHandle: HICON; begin with FImage do begin if RefCount > 1 then NewImage(CopyIcon(FHandle), nil); Result := FHandle; FHandle := 0; end; Changed(Self); end; (*----------------------------------------------------------------------------* | procedure TIconCursor.SaveToClipboardFormat | | | | Not supported. | *----------------------------------------------------------------------------*) procedure TIconCursor.SaveToClipboardFormat(var Format: Word; var Data: THandle; var APalette: HPALETTE); begin raise EInvalidGraphic.Create (rstNoClipboardSupport) end; (*----------------------------------------------------------------------------* | procedure TIconCursor.SaveToStream | | | | Save to a stream. | *----------------------------------------------------------------------------*) procedure TIconCursor.SaveToStream(Stream: TStream); begin ImageNeeded; with FImage.FMemoryImage do Stream.WriteBuffer(Memory^, Size); end; (*----------------------------------------------------------------------------* | procedure TIconCursor.SetHandle | | | | Set the image to a new icon handle. | *----------------------------------------------------------------------------*) procedure TIconCursor.SetHandle(const Value: HICON); var iconInfo : TIconInfo; BI : TBitmapInfoHeader; begin if GetIconInfo (value, iconInfo) then try InitializeBitmapInfoHeader (iconInfo.hbmColor, BI, ColorCount); fWidth := BI.biWidth; fHeight := BI.biHeight; fHotspot := MAKELONG (iconInfo.xHotspot, iconInfo.yHotspot); NewImage(Value, nil); Changed(Self) finally DeleteObject (iconInfo.hbmMask); DeleteObject (iconInfo.hbmColor) end else RaiseLastWin32Error; end; (*----------------------------------------------------------------------------* | procedure TIconCursor.SetHeight | | | | Set the icon's height. Must be empty | *----------------------------------------------------------------------------*) procedure TIconCursor.SetHeight(value: Integer); begin if GetEmpty then FHeight := value else raise EInvalidGraphic.Create (rstCantResize); end; (*----------------------------------------------------------------------------* | procedure TIconCursor.SetPixelFormat | | | | Change the pixel format. Must be empty | *----------------------------------------------------------------------------*) procedure TIconCursor.SetPixelFormat(const Value: TPixelFormat); begin if value <> fPixelFormat then begin // if not (value in [pf1Bit, pf4Bit, pf8Bit]) then if value = pfCustom then raise EInvalidGraphic.Create (rstInvalidPixelFormat); if GetEmpty then fPixelFormat := Value else raise EInvalidGraphic.Create (rstCantReformat); end end; (*----------------------------------------------------------------------------* | procedure TIconCursor.SetWidth | | | | Set the icon width. Must be empty | *----------------------------------------------------------------------------*) procedure TIconCursor.SetWidth(value: Integer); begin if GetEmpty then FWidth := value else raise EInvalidGraphic.Create (rstCantResize); end; { TExIconImage } (*----------------------------------------------------------------------------* | destructor TExIconImage.Destroy | *----------------------------------------------------------------------------*) destructor TExIconImage.Destroy; begin FMemoryImage.Free; inherited // Which calls FreeHandle if necessary end; (*----------------------------------------------------------------------------* | procedure TExIconImage.FreeHandle | | | | Free the handle. | *----------------------------------------------------------------------------*) procedure TExIconImage.FreeHandle; begin if FHandle <> 0 then DestroyIcon(FHandle); FHandle := 0; end; { TExCursor } (*----------------------------------------------------------------------------* | constructor TExCursor.Create | *----------------------------------------------------------------------------*) constructor TExCursor.Create; begin inherited Create; fBitmapOffset := sizeof (DWORD); fWidth := GetSystemMetrics (SM_CXCURSOR); fHeight := GetSystemMetrics (SM_CYCURSOR); fPixelFormat := pf1Bit; end; (*----------------------------------------------------------------------------* | function TExCursor.GetHotspot | | | | Get the cursor's hotspot. | *----------------------------------------------------------------------------*) function TExCursor.GetHotspot: DWORD; begin HandleNeeded; result := fHotspot end; (*----------------------------------------------------------------------------* | procedure TExCursor.HandleNeeded | | | | Make sure there's a handle if there's a memory image. | | If there's no handle or memory image, it's not an error. | *----------------------------------------------------------------------------*) procedure TExCursor.HandleNeeded; var info : TBitmapInfoHeader; NewHandle: HICON; begin with FImage do begin if FHandle <> 0 then Exit; if FMemoryImage = nil then Exit; FMemoryImage.Seek (sizeof (DWORD), soFromBeginning); // BitmapInfoHeader comes FMemoryImage.ReadBuffer (info, sizeof (Info)); // after the DWORD hotspot. FMemoryImage.Seek (0, soFromBeginning); if fPalette <> 0 then DeleteObject (fPalette); ReadIcon(FMemoryImage, NewHandle, fPalette, False); FWidth := info.biWidth; FHeight := info.biHeight div 2; FHotspot := PDWORD (FMemoryImage.Memory)^; case info.biBitCount of 1: FPixelFormat := pf1Bit; 4: FPixelFormat := pf4Bit; 8: FPixelFormat := pf8Bit; 16: case info.biCompression of BI_RGB : FPixelFormat := pf15Bit; BI_BITFIELDS: FPixelFormat := pf16Bit; end; 24: FPixelFormat := pf24Bit; 32: FPixelFormat := pf32Bit; else raise EInvalidGraphic.Create (rstInvalidPixelFormat); end; FHandle := NewHandle; end end; (*----------------------------------------------------------------------------* | procedure TExCursor.ImageNeeded | | | | Make sure there's an image if there's a handle. | | It's an error if there's neither... | *----------------------------------------------------------------------------*) procedure TExCursor.ImageNeeded; var Image: TMemoryStream; colorCount : Integer; begin with FImage do begin if FMemoryImage <> nil then Exit; if FHandle = 0 then raise EInvalidGraphic.Create (rstInvalidIcon); Image := TMemoryStream.Create; try case pixelFormat of pf1Bit : colorCount := 2; pf4Bit : colorCount := 16; pf8Bit : colorCount := 256; else colorCount := 0; end; Image.Seek (0, soFromBeginning); // leave space for hotspot dword WriteIcon(Image, Handle, colorCount, False); except Image.Free; raise; end; FMemoryImage := Image; end; end; (*----------------------------------------------------------------------------* | procedure TExCursor.SetHotspot | | | | Set the hotspot. *Doesn't* have to be empty. | *----------------------------------------------------------------------------*) procedure TExCursor.SetHotspot(const Value: DWORD); begin if value <> fHotspot then begin FHotspot := value; if not Empty then begin fHotspot := value; ImageNeeded; // If it's not empty there's either an image or a handle. // Make sure the image is valid // Release the handle. We want a new one with the new // hotspot. if fImage.fHandle <> 0 then DeleteObject (ReleaseHandle); PDWORD (FImage.FMemoryImage.Memory)^ := Value; end end end; { TExIcon } (*----------------------------------------------------------------------------* | constructor TExIcon.Create | *----------------------------------------------------------------------------*) constructor TExIcon.Create; begin inherited Create; fWidth := GetSystemMetrics (SM_CXICON); fHeight := GetSystemMetrics (SM_CYICON); fPixelFormat := pf4Bit; end; (*----------------------------------------------------------------------------* | procedure TExIcon.HandleNeeded | | | | Make sure there's a handle if there's a memory image. | | If there's no handle or memory image, it's not an error. | *----------------------------------------------------------------------------*) procedure TExIcon.HandleNeeded; var info : TBitmapInfoHeader; NewHandle: HICON; begin with FImage do begin if FHandle <> 0 then Exit; if FMemoryImage = nil then Exit; FMemoryImage.Seek (0, soFromBeginning); FMemoryImage.ReadBuffer (info, sizeof (Info)); FMemoryImage.Seek (0, soFromBeginning); if fPalette <> 0 then DeleteObject (fPalette); ReadIcon(FMemoryImage, NewHandle, fPalette, True); FWidth := info.biWidth; FHeight := info.biHeight div 2; case info.biBitCount of 1: FPixelFormat := pf1Bit; 4: FPixelFormat := pf4Bit; 8: FPixelFormat := pf8Bit; 16: case info.biCompression of BI_RGB : FPixelFormat := pf15Bit; BI_BITFIELDS: FPixelFormat := pf16Bit; end; 24: FPixelFormat := pf24Bit; 32: FPixelFormat := pf32Bit; else raise EInvalidGraphic.Create (rstInvalidPixelFormat); end; FHandle := NewHandle; end end; (*----------------------------------------------------------------------------* | procedure TExCursor.ImageNeeded | | | | Make sure there's an image if there's a handle. | | It's an error if there's neither... | *----------------------------------------------------------------------------*) procedure TExIcon.ImageNeeded; var Image: TMemoryStream; colorCount : Integer; begin with FImage do begin if FMemoryImage <> nil then Exit; if FHandle = 0 then raise EInvalidGraphic.Create (rstInvalidIcon); Image := TMemoryStream.Create; try case pixelFormat of pf1Bit : colorCount := 2; pf4Bit : colorCount := 16; pf8Bit : colorCount := 256; else colorCount := 0; end; WriteIcon(Image, Handle, colorCount, True); except Image.Free; raise; end; FMemoryImage := Image; end; end; const RGBMAX = 255; UNDEFINED = HLSMAX * 2 div 3; function HueToRGB(n1,n2,hue : Integer) : word; begin while hue > hlsmax do Dec (hue, HLSMAX); while hue < 0 do Inc (hue, HLSMAX); if hue < HLSMAX div 6 then result := ( n1 + (((n2-n1)*hue+(HLSMAX div 12)) div (HLSMAX div 6)) ) else if hue < HLSMAX div 2 then result := n2 else if hue < (HLSMAX*2) div 3 then result := n1 + (((n2-n1)*(((HLSMAX*2) div 3)-hue)+(HLSMAX div 12)) div (HLSMAX div 6)) else result := n1 end; procedure iHLSToRGB (hue, lum, sat : Integer; var r, g, b : Integer); var Magic1,Magic2 : Integer; // calculated magic numbers (really!) */ begin if sat = 0 then // achromatic case */ begin r := (lum * RGBMAX) div HLSMAX; g := r; b := r; // if hue <> UNDEFINED then // raise EColorError.Create ('Bad hue value') end else begin if lum <= HLSMAX div 2 then Magic2 := (lum*(HLSMAX + sat) + (HLSMAX div 2)) div HLSMAX else Magic2 := lum + sat - ((lum*sat) + (HLSMAX div 2)) div HLSMAX; Magic1 := 2*lum-Magic2; r := (HueToRGB (Magic1,Magic2,hue+(HLSMAX div 3))*RGBMAX + (HLSMAX div 2)) div HLSMAX; g := (HueToRGB (Magic1,Magic2,hue)*RGBMAX + (HLSMAX div 2)) div HLSMAX; b := (HueToRGB (Magic1,Magic2,hue-(HLSMAX div 3))*RGBMAX + (HLSMAX div 2)) div HLSMAX; end; end; function TIconCursor.GetIcon: TIcon; begin Result := FIcon; Result.Handle := Handle; end; initialization SystemPalette256 := Create256ColorPalette; SystemPalette2 := Create2ColorPalette; finalization DeleteObject (SystemPalette2); DeleteObject (SystemPalette256); end.
unit BabelForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Rio, SoapHTTPClient, InvokeRegistry; type TForm1 = class(TForm) HTTPRIO1: THTTPRIO; btnTranslate: TButton; EditSource: TEdit; EditTarget: TEdit; ComboBoxType: TComboBox; MemoRequest: TMemo; MemoResponse: TMemo; procedure btnTranslateClick(Sender: TObject); procedure btnDirectClick(Sender: TObject); procedure HTTPRIO1AfterExecute(const MethodName: String; SOAPResponse: TStream); procedure HTTPRIO1BeforeExecute(const MethodName: String; var SOAPRequest: WideString); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses BabelFishService; procedure TForm1.btnTranslateClick(Sender: TObject); begin // call via the HTTPRIO component EditTarget.Text := (HTTPRIO1 as BabelFishPortType). BabelFish(ComboBoxType.Text, EditSource.Text); end; procedure TForm1.btnDirectClick(Sender: TObject); begin ShowMessage (GetBabelFishPortType.BabelFish( 'en_it', 'Hello, world!')); end; procedure TForm1.HTTPRIO1AfterExecute(const MethodName: String; SOAPResponse: TStream); begin SOAPResponse.Position := 0; MemoResponse.Lines.LoadFromStream(SOAPResponse); end; procedure TForm1.HTTPRIO1BeforeExecute(const MethodName: String; var SOAPRequest: WideString); begin MemoRequest.Text := SoapRequest; end; end.
unit GetDataU; interface uses Classes, SysUtils; type TGetData = class(TThread) private FXMLText: string; FURL: string; FError: string; FAfterGet: TNotifyEvent; FUserAgent: string; procedure DoAfterGet; protected procedure Execute; override; public constructor Create; property XMLText: string read FXMLText; property URL: string read FURL write FURL; property Error: string read FError; property AfterGet: TNotifyEvent read FAfterGet write FAfterGet; property UserAgent: string read FUserAgent write FUserAgent; end; implementation uses IdHTTP; { GetData } constructor TGetData.Create; begin inherited Create(True); FreeOnTerminate := True; end; procedure TGetData.Execute; begin FError := ''; with TIdHTTP.Create(nil) do try Request.UserAgent := FUserAgent; Request.Referer := 'http://www.nldelphi.com/dex'; try FXMLText := Get(FURL); except on e: Exception do FError := e.Message; end; finally Free; end; Synchronize(DoAfterGet); end; procedure TGetData.DoAfterGet; begin if Assigned(FAfterGet) then FAfterGet(Self); end; end.
unit UPCSafeBoxTransaction; interface uses UOrderedAccountList, UPascalCoinSafeBox, URawBytes, UOrderedRawList, UAccount, UAccountPreviousBlockInfo, UAccountInfo, UAccountKey, UOperationBlock; type { TPCSafeBoxTransaction } TPCSafeBoxTransaction = Class private FOrderedList : TOrderedAccountList; FFreezedAccounts : TPCSafeBox; FTotalBalance: Int64; FTotalFee: Int64; FOldSafeBoxHash : TRawBytes; FAccountNames_Deleted : TOrderedRawList; FAccountNames_Added : TOrderedRawList; Function Origin_BlocksCount : Cardinal; Function Origin_SafeboxHash : TRawBytes; Function Origin_TotalBalance : Int64; Function Origin_TotalFee : Int64; Function Origin_FindAccountByName(const account_name : AnsiString) : Integer; protected Function GetInternalAccount(account_number : Cardinal) : PAccount; public Constructor Create(SafeBox : TPCSafeBox); Destructor Destroy; override; Function TransferAmount(previous : TAccountPreviousBlockInfo; sender,target : Cardinal; n_operation : Cardinal; amount, fee : UInt64; var errors : AnsiString) : Boolean; Function TransferAmounts(previous : TAccountPreviousBlockInfo; const senders, n_operations : Array of Cardinal; const sender_amounts : Array of UInt64; const receivers : Array of Cardinal; const receivers_amounts : Array of UInt64; var errors : AnsiString) : Boolean; Function UpdateAccountInfo(previous : TAccountPreviousBlockInfo; signer_account, signer_n_operation, target_account: Cardinal; accountInfo: TAccountInfo; newName : TRawBytes; newType : Word; fee: UInt64; var errors : AnsiString) : Boolean; Function BuyAccount(previous : TAccountPreviousBlockInfo; buyer,account_to_buy,seller: Cardinal; n_operation : Cardinal; amount, account_price, fee : UInt64; const new_account_key : TAccountKey; var errors : AnsiString) : Boolean; Function Commit(Const operationBlock : TOperationBlock; var errors : AnsiString) : Boolean; Function Account(account_number : Cardinal) : TAccount; Procedure Rollback; Function CheckIntegrity : Boolean; Property FreezedSafeBox : TPCSafeBox read FFreezedAccounts; Property TotalFee : Int64 read FTotalFee; Property TotalBalance : Int64 read FTotalBalance; Procedure CopyFrom(transaction : TPCSafeBoxTransaction); Procedure CleanTransaction; Function ModifiedCount : Integer; Function Modified(index : Integer) : TAccount; Function FindAccountByNameInTransaction(const findName : TRawBytes; out isAddedInThisTransaction, isDeletedInThisTransaction : Boolean) : Integer; End; implementation uses UConst, UAccountComp, SysUtils, UCrypto, UAccountState, UAccountUpdateStyle, ULog, UECDSA_Public; { TPCSafeBoxTransaction } function TPCSafeBoxTransaction.Account(account_number: Cardinal): TAccount; Var i :Integer; begin if FOrderedList.Find(account_number,i) then Result := PAccount(FOrderedList.List[i])^ else begin Result := FreezedSafeBox.Account(account_number); end; end; function TPCSafeBoxTransaction.BuyAccount(previous : TAccountPreviousBlockInfo; buyer, account_to_buy, seller: Cardinal; n_operation: Cardinal; amount, account_price, fee: UInt64; const new_account_key: TAccountKey; var errors: AnsiString): Boolean; Var PaccBuyer, PaccAccountToBuy, PaccSeller : PAccount; begin Result := false; errors := ''; if not CheckIntegrity then begin errors := 'Invalid integrity in accounts transaction'; exit; end; if (buyer<0) Or (buyer>=(Origin_BlocksCount*CT_AccountsPerBlock)) Or (account_to_buy<0) Or (account_to_buy>=(Origin_BlocksCount*CT_AccountsPerBlock)) Or (seller<0) Or (seller>=(Origin_BlocksCount*CT_AccountsPerBlock)) then begin errors := 'Invalid account number on buy'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(buyer,Origin_BlocksCount) then begin errors := 'Buyer account is blocked for protocol'; Exit; end; if TAccountComp.IsAccountBlockedByProtocol(account_to_buy,Origin_BlocksCount) then begin errors := 'Account to buy is blocked for protocol'; Exit; end; if TAccountComp.IsAccountBlockedByProtocol(seller,Origin_BlocksCount) then begin errors := 'Seller account is blocked for protocol'; Exit; end; PaccBuyer := GetInternalAccount(buyer); PaccAccountToBuy := GetInternalAccount(account_to_buy); PaccSeller := GetInternalAccount(seller); if (PaccBuyer^.n_operation+1<>n_operation) then begin errors := 'Incorrect n_operation'; Exit; end; if (PaccBuyer^.balance < (amount+fee)) then begin errors := 'Insuficient founds'; Exit; end; if (fee>CT_MaxTransactionFee) then begin errors := 'Max fee'; Exit; end; if (TAccountComp.IsAccountLocked(PaccBuyer^.accountInfo,Origin_BlocksCount)) then begin errors := 'Buyer account is locked until block '+Inttostr(PaccBuyer^.accountInfo.locked_until_block); Exit; end; If not (TAccountComp.IsAccountForSale(PaccAccountToBuy^.accountInfo)) then begin errors := 'Account is not for sale'; Exit; end; if (PaccAccountToBuy^.accountInfo.new_publicKey.EC_OpenSSL_NID<>CT_TECDSA_Public_Nul.EC_OpenSSL_NID) And (Not TAccountComp.EqualAccountKeys(PaccAccountToBuy^.accountInfo.new_publicKey,new_account_key)) then begin errors := 'New public key is not equal to allowed new public key for account'; Exit; end; // Buy an account applies when account_to_buy.amount + operation amount >= price // Then, account_to_buy.amount will be (account_to_buy.amount + amount - price) // and buyer.amount will be buyer.amount + price if (PaccAccountToBuy^.accountInfo.price > (PaccAccountToBuy^.balance+amount)) then begin errors := 'Account price '+TAccountComp.FormatMoney(PaccAccountToBuy^.accountInfo.price)+' < balance '+ TAccountComp.FormatMoney(PaccAccountToBuy^.balance)+' + amount '+TAccountComp.FormatMoney(amount); Exit; end; previous.UpdateIfLower(PaccBuyer^.account,PaccBuyer^.updated_block); previous.UpdateIfLower(PaccAccountToBuy^.account,PaccAccountToBuy^.updated_block); previous.UpdateIfLower(PaccSeller^.account,PaccSeller^.updated_block); If PaccBuyer^.updated_block<>Origin_BlocksCount then begin PaccBuyer^.previous_updated_block := PaccBuyer^.updated_block; PaccBuyer^.updated_block := Origin_BlocksCount; end; If PaccAccountToBuy^.updated_block<>Origin_BlocksCount then begin PaccAccountToBuy^.previous_updated_block := PaccAccountToBuy^.updated_block; PaccAccountToBuy^.updated_block := Origin_BlocksCount; end; If PaccSeller^.updated_block<>Origin_BlocksCount then begin PaccSeller^.previous_updated_block := PaccSeller^.updated_block; PaccSeller^.updated_block := Origin_BlocksCount; end; // Inc buyer n_operation PaccBuyer^.n_operation := n_operation; // Set new balance values PaccBuyer^.balance := PaccBuyer^.balance - (amount + fee); PaccAccountToBuy^.balance := PaccAccountToBuy^.balance + amount - PaccAccountToBuy^.accountInfo.price; PaccSeller^.balance := PaccSeller^.balance + PaccAccountToBuy^.accountInfo.price; // After buy, account will be unlocked and set to normal state and new account public key changed PaccAccountToBuy^.accountInfo := CT_AccountInfo_NUL; PaccAccountToBuy^.accountInfo.state := as_Normal; PaccAccountToBuy^.accountInfo.accountKey := new_account_key; FTotalBalance := FTotalBalance - fee; FTotalFee := FTotalFee + fee; Result := true; end; function TPCSafeBoxTransaction.CheckIntegrity: Boolean; begin Result := FOldSafeBoxHash = Origin_SafeboxHash; end; procedure TPCSafeBoxTransaction.CleanTransaction; begin FOrderedList.Clear; FOldSafeBoxHash := Origin_SafeboxHash; FTotalBalance := Origin_TotalBalance; FTotalFee := 0; FAccountNames_Added.Clear; FAccountNames_Deleted.Clear; end; function TPCSafeBoxTransaction.Commit(const operationBlock: TOperationBlock; var errors: AnsiString): Boolean; Var i : Integer; Pa : PAccount; begin Result := false; errors := ''; FFreezedAccounts.StartThreadSafe; try if not CheckIntegrity then begin errors := 'Invalid integrity in accounts transaction on commit'; exit; end; for i := 0 to FOrderedList.List.Count - 1 do begin Pa := PAccount(FOrderedList.List[i]); FFreezedAccounts.UpdateAccount(Pa^.account, Pa^.accountInfo, Pa^.name, Pa^.account_type, Pa^.balance, Pa^.n_operation, aus_transaction_commit, 0,0); end; // if (Origin_TotalBalance<>FTotalBalance) then begin TLog.NewLog(lterror,ClassName,Format('Invalid integrity balance! StrongBox:%d Transaction:%d',[Origin_TotalBalance,FTotalBalance])); end; if (Origin_TotalFee<>FTotalFee) then begin TLog.NewLog(lterror,ClassName,Format('Invalid integrity fee! StrongBox:%d Transaction:%d',[Origin_TotalFee,FTotalFee])); end; FFreezedAccounts.AddNew(operationBlock); CleanTransaction; // if (FFreezedAccounts.CurrentProtocol<CT_PROTOCOL_2) And (operationBlock.protocol_version=CT_PROTOCOL_2) then begin // First block with new protocol! if FFreezedAccounts.CanUpgradeToProtocol(CT_PROTOCOL_2) then begin TLog.NewLog(ltInfo,ClassName,'Protocol upgrade to v2'); If not FFreezedAccounts.DoUpgradeToProtocol2 then begin raise Exception.Create('Cannot upgrade to protocol v2 !'); end; end; end; if (FFreezedAccounts.CurrentProtocol<CT_PROTOCOL_3) And (operationBlock.protocol_version=CT_PROTOCOL_3) then begin // First block with V3 protocol if FFreezedAccounts.CanUpgradeToProtocol(CT_PROTOCOL_3) then begin TLog.NewLog(ltInfo,ClassName,'Protocol upgrade to v3'); If not FFreezedAccounts.DoUpgradeToProtocol3 then begin raise Exception.Create('Cannot upgrade to protocol v3 !'); end; end; end; Result := true; finally FFreezedAccounts.EndThreadSave; end; end; procedure TPCSafeBoxTransaction.CopyFrom(transaction : TPCSafeBoxTransaction); Var i : Integer; P : PAccount; begin if transaction=Self then exit; if transaction.FFreezedAccounts<>FFreezedAccounts then raise Exception.Create('Invalid Freezed accounts to copy'); CleanTransaction; for i := 0 to transaction.FOrderedList.List.Count - 1 do begin P := PAccount(transaction.FOrderedList.List[i]); FOrderedList.Add(P^); end; FOldSafeBoxHash := transaction.FOldSafeBoxHash; FTotalBalance := transaction.FTotalBalance; FTotalFee := transaction.FTotalFee; end; constructor TPCSafeBoxTransaction.Create(SafeBox : TPCSafeBox); begin FOrderedList := TOrderedAccountList.Create; FFreezedAccounts := SafeBox; FOldSafeBoxHash := SafeBox.SafeBoxHash; FTotalBalance := FFreezedAccounts.TotalBalance; FTotalFee := 0; FAccountNames_Added := TOrderedRawList.Create; FAccountNames_Deleted := TOrderedRawList.Create; end; destructor TPCSafeBoxTransaction.Destroy; begin CleanTransaction; FreeAndNil(FOrderedList); FreeAndNil(FAccountNames_Added); FreeAndNil(FAccountNames_Deleted); inherited; end; function TPCSafeBoxTransaction.Origin_BlocksCount: Cardinal; begin Result := FFreezedAccounts.BlocksCount; end; function TPCSafeBoxTransaction.Origin_SafeboxHash: TRawBytes; begin Result := FFreezedAccounts.SafeBoxHash; end; function TPCSafeBoxTransaction.Origin_TotalBalance: Int64; begin Result := FFreezedAccounts.TotalBalance; end; function TPCSafeBoxTransaction.Origin_TotalFee: Int64; begin Result := FFreezedAccounts.TotalFee; end; function TPCSafeBoxTransaction.Origin_FindAccountByName(const account_name: AnsiString): Integer; begin Result := FFreezedAccounts.FindAccountByName(account_name); end; function TPCSafeBoxTransaction.GetInternalAccount(account_number: Cardinal): PAccount; Var i :Integer; begin if FOrderedList.Find(account_number,i) then Result := PAccount(FOrderedList.List[i]) else begin i := FOrderedList.Add( FreezedSafeBox.Account(account_number) ); Result := PAccount(FOrderedList.List[i]); end; end; function TPCSafeBoxTransaction.Modified(index: Integer): TAccount; begin Result := FOrderedList.Get(index); end; function TPCSafeBoxTransaction.FindAccountByNameInTransaction(const findName: TRawBytes; out isAddedInThisTransaction, isDeletedInThisTransaction : Boolean) : Integer; Var nameLower : AnsiString; iSafeBox, iAdded, iDeleted : Integer; begin Result := -1; isAddedInThisTransaction := False; isDeletedInThisTransaction := False; nameLower := LowerCase(findName); If (nameLower)='' then begin Exit; // No name, no found end; iSafeBox := Origin_FindAccountByName(nameLower); iAdded := FAccountNames_Added.IndexOf(nameLower); iDeleted := FAccountNames_Deleted.IndexOf(nameLower); isAddedInThisTransaction := (iAdded >= 0); isDeletedInThisTransaction := (iDeleted >= 0); if (iSafeBox<0) then begin // Not found previously, check added in current trans? If iAdded>=0 then begin Result := FAccountNames_Added.GetTag(iAdded); end; end else begin // Was found previously, check if deleted if iDeleted<0 then begin // Not deleted! "iSafebox" value contains account number using name Result := iSafeBox; end; end; end; function TPCSafeBoxTransaction.ModifiedCount: Integer; begin Result := FOrderedList.Count; end; procedure TPCSafeBoxTransaction.Rollback; begin CleanTransaction; end; function TPCSafeBoxTransaction.TransferAmount(previous : TAccountPreviousBlockInfo; sender, target: Cardinal; n_operation: Cardinal; amount, fee: UInt64; var errors: AnsiString): Boolean; Var intSender, intTarget : Integer; PaccSender, PaccTarget : PAccount; begin Result := false; errors := ''; if not CheckIntegrity then begin errors := 'Invalid integrity in accounts transaction'; exit; end; if (sender<0) Or (sender>=(Origin_BlocksCount*CT_AccountsPerBlock)) Or (target<0) Or (target>=(Origin_BlocksCount*CT_AccountsPerBlock)) then begin errors := 'Invalid sender or target on transfer'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(sender,Origin_BlocksCount) then begin errors := 'Sender account is blocked for protocol'; Exit; end; if TAccountComp.IsAccountBlockedByProtocol(target,Origin_BlocksCount) then begin errors := 'Target account is blocked for protocol'; Exit; end; PaccSender := GetInternalAccount(sender); PaccTarget := GetInternalAccount(target); if (PaccSender^.n_operation+1<>n_operation) then begin errors := 'Incorrect n_operation'; Exit; end; if (PaccSender^.balance < (amount+fee)) then begin errors := 'Insuficient founds'; Exit; end; if ((PaccTarget^.balance + amount)>CT_MaxWalletAmount) then begin errors := 'Max account balance'; Exit; end; if (fee>CT_MaxTransactionFee) then begin errors := 'Max fee'; Exit; end; if (TAccountComp.IsAccountLocked(PaccSender^.accountInfo,Origin_BlocksCount)) then begin errors := 'Sender account is locked until block '+Inttostr(PaccSender^.accountInfo.locked_until_block); Exit; end; previous.UpdateIfLower(PaccSender^.account,PaccSender^.updated_block); previous.UpdateIfLower(PaccTarget^.account,PaccTarget^.updated_block); If PaccSender^.updated_block<>Origin_BlocksCount then begin PaccSender^.previous_updated_block := PaccSender^.updated_block; PaccSender^.updated_block := Origin_BlocksCount; end; If PaccTarget^.updated_block<>Origin_BlocksCount then begin PaccTarget^.previous_updated_block := PaccTarget.updated_block; PaccTarget^.updated_block := Origin_BlocksCount; end; PaccSender^.n_operation := n_operation; PaccSender^.balance := PaccSender^.balance - (amount + fee); PaccTarget^.balance := PaccTarget^.balance + (amount); FTotalBalance := FTotalBalance - fee; FTotalFee := FTotalFee + fee; Result := true; end; function TPCSafeBoxTransaction.TransferAmounts(previous : TAccountPreviousBlockInfo; const senders, n_operations: array of Cardinal; const sender_amounts: array of UInt64; const receivers: array of Cardinal; const receivers_amounts: array of UInt64; var errors: AnsiString): Boolean; Var i,j : Integer; PaccSender, PaccTarget : PAccount; nTotalAmountSent, nTotalAmountReceived, nTotalFee : Int64; begin Result := false; errors := ''; nTotalAmountReceived:=0; nTotalAmountSent:=0; if not CheckIntegrity then begin errors := 'Invalid integrity in transfer amounts transaction'; Exit; end; if (Length(senders)<>Length(n_operations)) Or (Length(senders)<>Length(sender_amounts)) Or (Length(senders)=0) then begin errors := 'Invalid senders/n_operations/amounts arrays length'; Exit; end; if (Length(receivers)<>Length(receivers_amounts)) Or (Length(receivers)=0) then begin errors := 'Invalid receivers/amounts arrays length'; Exit; end; // Check sender for i:=Low(senders) to High(senders) do begin for j:=i+1 to High(senders) do begin if (senders[i]=senders[j]) then begin errors := 'Duplicated sender'; Exit; end; end; if (senders[i]<0) Or (senders[i]>=(Origin_BlocksCount*CT_AccountsPerBlock)) then begin errors := 'Invalid sender on transfer'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(senders[i],Origin_BlocksCount) then begin errors := 'Sender account is blocked for protocol'; Exit; end; if (sender_amounts[i]<=0) then begin errors := 'Invalid amount for multiple sender'; Exit; end; PaccSender := GetInternalAccount(senders[i]); if (PaccSender^.n_operation+1<>n_operations[i]) then begin errors := 'Incorrect multisender n_operation'; Exit; end; if (PaccSender^.balance < sender_amounts[i]) then begin errors := 'Insuficient funds'; Exit; end; if (TAccountComp.IsAccountLocked(PaccSender^.accountInfo,Origin_BlocksCount)) then begin errors := 'Multi sender account is locked until block '+Inttostr(PaccSender^.accountInfo.locked_until_block); Exit; end; nTotalAmountSent := nTotalAmountSent + sender_amounts[i]; end; // for i:=Low(receivers) to High(receivers) do begin if (receivers[i]<0) Or (receivers[i]>=(Origin_BlocksCount*CT_AccountsPerBlock)) then begin errors := 'Invalid receiver on transfer'; exit; end; if TAccountComp.IsAccountBlockedByProtocol(receivers[i],Origin_BlocksCount) then begin errors := 'Receiver account is blocked for protocol'; Exit; end; if (receivers_amounts[i]<=0) then begin errors := 'Invalid amount for multiple receivers'; Exit; end; nTotalAmountReceived := nTotalAmountReceived + receivers_amounts[i]; PaccTarget := GetInternalAccount(receivers[i]); if ((PaccTarget^.balance + receivers_amounts[i])>CT_MaxWalletAmount) then begin errors := 'Max receiver balance'; Exit; end; end; // nTotalFee := nTotalAmountSent - nTotalAmountReceived; If (nTotalAmountSent<nTotalAmountReceived) then begin errors := 'Total amount sent < total amount received'; Exit; end; if (nTotalFee>CT_MaxTransactionFee) then begin errors := 'Max fee'; Exit; end; // Ok, execute! for i:=Low(senders) to High(senders) do begin PaccSender := GetInternalAccount(senders[i]); previous.UpdateIfLower(PaccSender^.account,PaccSender^.updated_block); If PaccSender^.updated_block<>Origin_BlocksCount then begin PaccSender^.previous_updated_block := PaccSender^.updated_block; PaccSender^.updated_block := Origin_BlocksCount; end; Inc(PaccSender^.n_operation); PaccSender^.balance := PaccSender^.balance - (sender_amounts[i]); end; for i:=Low(receivers) to High(receivers) do begin PaccTarget := GetInternalAccount(receivers[i]); previous.UpdateIfLower(PaccTarget^.account,PaccTarget^.updated_block); If PaccTarget^.updated_block<>Origin_BlocksCount then begin PaccTarget^.previous_updated_block := PaccTarget.updated_block; PaccTarget^.updated_block := Origin_BlocksCount; end; PaccTarget^.balance := PaccTarget^.balance + receivers_amounts[i]; end; FTotalBalance := FTotalBalance - nTotalFee; FTotalFee := FTotalFee + nTotalFee; Result := true; end; function TPCSafeBoxTransaction.UpdateAccountInfo(previous : TAccountPreviousBlockInfo; signer_account, signer_n_operation, target_account: Cardinal; accountInfo: TAccountInfo; newName: TRawBytes; newType: Word; fee: UInt64; var errors: AnsiString): Boolean; Var i : Integer; P_signer, P_target : PAccount; begin Result := false; errors := ''; if not CheckIntegrity then begin errors := 'Invalid integrity on Update account info'; Exit; end; if (signer_account<0) Or (signer_account>=(Origin_BlocksCount*CT_AccountsPerBlock)) Or (target_account<0) Or (target_account>=(Origin_BlocksCount*CT_AccountsPerBlock)) Then begin errors := 'Invalid account'; exit; end; if (TAccountComp.IsAccountBlockedByProtocol(signer_account,Origin_BlocksCount)) Or (TAccountComp.IsAccountBlockedByProtocol(target_account,Origin_BlocksCount)) then begin errors := 'account is blocked for protocol'; Exit; end; P_signer := GetInternalAccount(signer_account); P_target := GetInternalAccount(target_account); if (P_signer^.n_operation+1<>signer_n_operation) then begin errors := 'Incorrect n_operation'; Exit; end; if (P_signer^.balance < fee) then begin errors := 'Insuficient founds'; Exit; end; if (TAccountComp.IsAccountLocked(P_signer^.accountInfo,Origin_BlocksCount)) then begin errors := 'Signer account is locked until block '+Inttostr(P_signer^.accountInfo.locked_until_block); Exit; end; if (TAccountComp.IsAccountLocked(P_target^.accountInfo,Origin_BlocksCount)) then begin errors := 'Target account is locked until block '+Inttostr(P_target^.accountInfo.locked_until_block); Exit; end; if Not TAccountComp.EqualAccountKeys(P_signer^.accountInfo.accountKey,P_target^.accountInfo.accountKey) then begin errors := 'Signer and target have diff key'; Exit; end; if (newName<>P_target^.name) then begin // NEW NAME CHANGE CHECK: if (newName<>'') then begin If Not TPCSafeBox.ValidAccountName(newName,errors) then begin errors := 'Invalid account name "'+newName+'" length:'+IntToStr(length(newName))+': '+errors; Exit; end; i := Origin_FindAccountByName(newName); if (i>=0) then begin // This account name is in the safebox... check if deleted: i := FAccountNames_Deleted.IndexOf(newName); if i<0 then begin errors := 'Account name "'+newName+'" is in current use'; Exit; end; end; i := FAccountNames_Added.IndexOf(newName); if (i>=0) then begin // This account name is added in this transaction! (perhaps deleted also, but does not allow to "double add same name in same block") errors := 'Account name "'+newName+'" is in same transaction'; Exit; end; end; // Ok, include if (P_target^.name<>'') then begin // In use in the safebox, mark as deleted FAccountNames_Deleted.Add(P_target^.name,target_account); end; if (newName<>'') then begin FAccountNames_Added.Add(newName,target_account); end; end; // All Ok, can do changes previous.UpdateIfLower(P_signer^.account,P_signer^.updated_block); if P_signer^.updated_block <> Origin_BlocksCount then begin P_signer^.previous_updated_block := P_signer^.updated_block; P_signer^.updated_block := Origin_BlocksCount; end; if (signer_account<>target_account) then begin previous.UpdateIfLower(P_target^.account,P_target^.updated_block); if P_target^.updated_block <> Origin_BlocksCount then begin P_target^.previous_updated_block := P_target^.updated_block; P_target^.updated_block := Origin_BlocksCount; end; end; P_signer^.n_operation := signer_n_operation; P_target^.accountInfo := accountInfo; P_target^.name := newName; P_target^.account_type := newType; P_signer^.balance := P_signer^.balance - fee; // Signer is who pays the fee FTotalBalance := FTotalBalance - fee; FTotalFee := FTotalFee + fee; Result := true; end; end.
unit drunkWalkman_form; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Grids,Math,drunkWalkman_options, Vcl.ImgList; const halffoot = 15; const footh = 23; const footw = 12; Type TWayPoint = record x,y: integer; randval: double; procedure SetLocation(x: integer; y: integer); end; type TWay = array of TWayPoint; type TDrunkWalkmanForm = class(TForm) PnlMapCaptions: TPanel; Le_MapHeight: TLabeledEdit; Le_MapWidth: TLabeledEdit; Le_SquareLen: TLabeledEdit; Le_WayLen: TLabeledEdit; Le_X0: TLabeledEdit; Le_Y0: TLabeledEdit; Ed_pLeft: TEdit; Ed_pRight: TEdit; Ed_pDown: TEdit; Ed_pUp: TEdit; Label1: TLabel; Panel1: TPanel; Le_SessionNum: TLabeledEdit; Sg_SetNum: TStringGrid; UD_SessionNum: TUpDown; Bt_Start: TButton; Im_Map: TImage; TmDrawStep: TTimer; ImageList1: TImageList; ImageList2: TImageList; procedure Bt_StartClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DrawMap(); procedure DrawMainWay(); procedure DrawStep(); procedure FormResize(Sender: TObject); procedure TmDrawStepTimer(Sender: TObject); procedure UD_SessionNumChangingEx(Sender: TObject; var AllowChange: Boolean; NewValue: SmallInt; Direction: TUpDownDirection); private { Private declarations } public { Public declarations } end; type TProbability=array[1..4] of double; function StartExperiment(x0: integer; y0: integer; Mapheight: integer; MapWidth: integer; SquareLen: integer; Waylen: integer; p: TProbability): TWay; var DrunkWalkmanForm: TDrunkWalkmanForm; //для процедуры отрисовки MainWay: TWay; GlobalMapWidth, GlobalMapHeight: integer; StepsPerSquare: integer; StepNo,SquareNo: integer; direction: integer; //1..4 BoolRight: boolean; //true=Right footstep; false=left footstep footsteps: array[0..1,1..4] of TBitmap; PixelsPerSquare: integer; implementation {$R *.dfm} procedure TWayPoint.SetLocation(x: integer; y: integer); begin Self.x:=x; self.y:=y; end; procedure TDrunkWalkmanForm.Bt_StartClick(Sender: TObject); var i,j: integer; SquareLen, WayLen: integer; MapWidth, MapHeight: integer; p: TProbability; x0,y0: integer; //----------- SessionNum: integer;//к-во сессий SessionLen: array of integer;//к-во экспериментов в сессии //----------- Way: TWay; ResultedArray: Array of Array of integer; outshift: integer; //0 | 1 WaySquaresLen: integer; ple2,pe0: array of double; s: string; mdist: array of double; gen_ple2,gen_pe0, gen_mdist: double; gen_sessionlen: integer; begin //0. SetLength(MainWay,0); //1. загрузка данных из интерфейса try//mapwidth,mapheight MapWidth:=0; MapHeight:=0; MapWidth:=StrToInt(Le_MapWidth.Text); MapHeight:=StrToInt(Le_MapHeight.Text); if (MapWidth<=0)or(MapHeight<=0) then raise Exception.Create('Ширина и высота карты указаны неверно'); Except on E: Exception do begin ShowMessage(E.Message); exit; end; end; try//squarelen SquareLen:=0; SquareLen:=StrToInt(Le_SquareLen.Text); if SquareLen<=0 then raise Exception.Create('Размер квартала в шагах указан неверно'); Except on E: Exception do begin ShowMessage(E.Message); exit; end; end; try//waylen WayLen:=0; WayLen:=StrToInt(Le_WayLen.Text); if WayLen<=0 then raise Exception.Create('Длина пути в шагах указана неверно'); if WayLen<SquareLen then raise Exception.Create('Длина пути должна быть больше длины квартала'); Except on E: Exception do begin ShowMessage(E.Message); exit; end; end; try//x0,y0 X0:=0; Y0:=0; X0:=StrToInt(Le_X0.Text); Y0:=StrToInt(Le_Y0.Text); if (X0<0)or(Y0<0) then raise Exception.Create('Координаты начальной точки не могут быть отрицательными'); if X0>MapWidth then raise Exception.Create('Координата x0 должна быть не больше ширины карты'); if Y0>MapHeight then raise Exception.Create('Координата y0 должна быть не больше высоты карты'); Except on E: Exception do begin ShowMessage(E.Message); exit; end; end; try//p[i] p[1]:=0; p[2]:=0; p[3]:=0; p[4]:=0; try p[1]:=StrToFloat(Ed_pLeft.Text); p[2]:=StrToFloat(Ed_pUp.Text); p[3]:=StrToFloat(Ed_pRight.Text); p[4]:=StrToFloat(Ed_pDown.Text); Except on E: Exception do begin raise Exception.Create('Невозможно считать вероятности p_i'); end; end; if not IsZero(p[1]+p[2]+p[3]+p[4]-1,0.000001) then raise Exception.Create('Сумма вероятностей по 4м направлениям должна равняться единице'); if (p[1]<0)or(p[2]<0)or(p[3]<0)or(p[4]<0) then raise Exception.Create('Вероятности p_i должны быть неотрицательны'); if IsZero((p[1]+p[2]),0.000001) then raise Exception.Create('Отказ: если прохожий попадет в нижний правый угол, то он не сможет никуда сдвинуться.'+#13+#10+ ' Измените набор вероятностей.'); if IsZero((p[2]+p[3]),0.000001) then raise Exception.Create('Отказ: если прохожий попадет в нижний левый угол, то он не сможет никуда сдвинуться.'+#13+#10+ ' Измените набор вероятностей.'); if IsZero((p[3]+p[4]),0.000001) then raise Exception.Create('Отказ: если прохожий попадет в верхний левый угол, то он не сможет никуда сдвинуться.'+#13+#10+ ' Измените набор вероятностей.'); if IsZero((p[4]+p[1]),0.000001) then raise Exception.Create('Отказ: если прохожий попадет в верхний правый угол, то он не сможет никуда сдвинуться.'+#13+#10+ ' Измените набор вероятностей.'); Except on E: Exception do begin ShowMessage(E.Message); exit; end; end; //SessionNum SessionNum:=UD_SessionNum.Position; try//SessionLen setLength(SessionLen,SessionNum); for i := 1 to SessionNum do SessionLen[i-1]:=0; for i := 1 to SessionNum do begin SessionLen[i-1]:=StrToInt(Sg_SetNum.Cells[1,i]); if SessionLen[i-1]<=0 then raise Exception.Create('к-во заходов должно быть >0'); end; Except on E: Exception do begin ShowMessage('Количество заходов для каждой сессии эксперимента должно быть целым положительным числом'); exit; end; end; //2. Исходные данные прочитаны, можно запускать эксперимент GlobalMapHeight:=MapHeight; GlobalMapWidth:=MapWidth; DrawMap(); Setlength(ResultedArray,SessionNum); for i := 1 to SessionNum do SetLength(ResultedArray[i-1],MapWidth+MapHeight+1); for i := 1 to SessionNum do begin for j := 1 to SessionLen[i-1] do begin //начинаем эксперимент! SetLength(Way,0); Way:=StartExperiment(x0,y0,MapHeight,MapWidth,SquareLen,WayLen,p); ResultedArray[i-1, Abs(Way[length(Way)-1].X-x0)+ abs(way[length(way)-1].Y-y0)]:= ResultedArray[i-1, Abs(Way[length(Way)-1].X-x0)+ abs(way[length(way)-1].Y-y0)] + 1; Application.ProcessMessages; end; end; MainWay:=Way; DrawMap();//перерисовка карты вместе с финальным маршрутом DrawMainWay(); //вывод результатов for i:=0 to length(MainWay)-1 do begin DrunkWalkmanResults.Memo1.Lines.Add(FLoatToStrF(MainWay[i].randval,ffFixed,7,4)); end; DrunkWalkmanResults.Memo1.Lines.Add(''); with DrunkWalkmanResults.StringGrid1 do begin ColCount:=SessionNum+1; RowCount:=MapHeight+MapWidth+2; DefaultColWidth:=70; ColWidths[0]:=140; cells[0,0]:='длина маршрута\номер серии'; for j := 1 to SessionNum do begin cells[j,0]:=inttostr(j)+' серия'; for i := 0 to MapHeight+MapWidth do cells[j,i+1]:=floattostrF(ResultedArray[j-1,i]/SessionLen[j-1],ffGeneral,7,4); end; for i := 0 to MapHeight+MapWidth do cells[0,i+1]:=inttostr(i); end; setlength(ple2,SessionNum); setlength(pe0,SessionNum); setlength(mdist,SessionNum); for i := 0 to SessionNum-1 do begin ple2[i]:=(ResultedArray[i,2]+ResultedArray[i,1]+ResultedArray[i,0])/SessionLen[i]; pe0[i]:=(ResultedArray[i,0])/SessionLen[i]; mdist[i]:=0; for j := 0 to length(ResultedArray[i])-1 do mdist[i]:=mdist[i]+j*ResultedArray[i,j]; mdist[i]:=mdist[i]/SessionLen[i]; end; gen_sessionlen:=0; for i := 0 to SessionNum-1 do begin gen_sessionlen:=gen_sessionlen+SessionLen[i]; end; for i := 0 to SessionNum-1 do begin gen_ple2:=gen_ple2+ple2[i]*sessionLen[i]; gen_pe0:=gen_pe0+pe0[i]*sessionLen[i]; gen_mdist:=gen_mdist+mdist[i]*sessionLen[i]; end; gen_ple2:=gen_ple2/gen_sessionlen; gen_pe0:=gen_pe0/gen_sessionlen; gen_mdist:=gen_mdist/gen_sessionlen; with DrunkWalkmanResults.StringGrid2 do begin ColCount:=4; RowCount:=SessionNum+2; DefaultColWidth:=70; ColWidths[0]:=80; // cells[0,0]:='длина маршрута\номер серии'; cells[1,0]:='P(dist<=2)'; cells[2,0]:='P(dist=0)'; cells[3,0]:='M[dist]'; for i := 0 to SessionNum-1 do begin cells[0,i+1]:=inttostr(i+1)+' серия'; cells[1,i+1]:=floattostrf(ple2[i],ffGeneral,7,4); cells[2,i+1]:=floattostrf(pe0[i],ffGeneral,7,4); cells[3,i+1]:=floattostrf(mdist[i],ffGeneral,7,4); end; cells[0,SessionNum+1]:='усредненное значение'; cells[1,SessionNum+1]:=floattostrf(gen_ple2,ffGeneral,7,4); cells[2,SessionNum+1]:=floattostrf(gen_pe0,ffGeneral,7,4); cells[3,SessionNum+1]:=floattostrf(gen_mdist,ffGeneral,7,4); end;//with sg2 DrunkWalkmanResults.Lb_Mdist.Caption:=OutLabelStrings[1]+FloatToStr(gen_mdist); DrunkWalkmanResults.Lb_Ple2.Caption:=OutLabelStrings[2]+FloatToStr(gen_ple2); DrunkWalkmanResults.Lb_Pe0.Caption:=OutLabelStrings[3]+FloatToStr(gen_pe0); DrunkWalkmanResults.Visible:=true; end; procedure TDrunkWalkmanForm.DrawMap(); var i,j: integer; Bmp: TBitmap; begin if GlobalMapWidth*GlobalMapHeight <1 then exit; PixelsPerSquare:=Min(floor((Im_Map.Height-2*footw)/GlobalMapHeight), floor((Im_Map.Width-2*footw)/GlobalMapWidth)); StepsPerSquare:=round((PixelsPerSquare - footh) / halffoot +1);//15 - чуть больше, чем полступни Bmp:=TBitMap.Create; bmp.SetSize(Im_Map.Width,Im_Map.Height); With bmp.Canvas do begin Brush.Color:=clNavy; Brush.Style:=bsSolid; FillRect(Rect(0,0,PixelsPerSquare*GlobalMapWidth+2*footw,PixelsPerSquare*GlobalMapHeight+2*footw));//фон Pen.Color:=clGray; Pen.Width:=2; for i := 0 to GlobalMapHeight do begin MoveTo(footw,PixelsPerSquare*i+footw); LineTo(PixelsPerSquare*GlobalMapWidth+footw,PixelsPerSquare*i+footw); end; for i := 0 to GlobalMapWidth do begin MoveTo(PixelsPerSquare*i+footw,footw); LineTo(PixelsPerSquare*i+footw,PixelsPerSquare*GlobalMapHeight+footw); end; end; Im_Map.Picture.Bitmap:=bmp; Im_Map.Refresh; end; procedure TDrunkWalkmanForm.DrawMainWay(); begin StepNo:=1; SquareNo:=0; if length(Mainway)<2 then exit;//по идее, такого не должно быть if MainWay[1].X<MainWay[0].X then direction:=1;//left; if MainWay[1].Y>MainWay[0].Y then direction:=2;//up; if MainWay[1].X>MainWay[0].X then direction:=3;//right if MainWay[1].Y<MainWay[0].Y then direction:=4;//down; TmDrawStep.Enabled:=true; end; procedure TDrunkWalkmanForm.DrawStep(); var i: integer; xshift,yshift: integer;//in pixels x0pix, y0pix: integer; boolRightAsInteger: integer; //0..1 bmp: TBitmap; randomShiftW,randomShiftH: integer; begin randomize; randomShiftW:=RandomRange(-1,1);//сдвиг влево-вправо от маршрута randomShiftH:=RandomRange(-2,2);//сдвиг вперед/назад //1. определить сдвиг от x0,y0 в зависимости от direction,ноги,номера шага if BoolRight then begin case direction of 1: begin//left xshift:=-halffoot*(StepNo-1)-footh; yshift:=-footw; end; 2: begin //up xshift:=0; yshift:=-halffoot*(StepNo-1)-footh; end; 3: begin //right xshift:=halffoot*(stepNo-1); yshift:=0; end; 4: begin //down xshift:=-footw; yshift:=halffoot*(stepNo-1); end; end; end else begin case direction of 1: begin//left xshift:=-halffoot*(StepNo-1)-footh; yshift:=0; end; 2: begin //up xshift:=-footw; yshift:=-halffoot*(StepNo-1)-footh; end; 3: begin //right xshift:=halffoot*(stepNo-1); yshift:=-footw; end; 4: begin //down xshift:=0; yshift:=halffoot*(stepNo-1); end; end; end; if (direction mod 2)=0 then//влево-вправо begin xshift:=xshift+randomShiftH; yshift:=yshift+randomShiftW; end else begin xshift:=xshift+randomShiftW; yshift:=yshift+randomShiftH; end; //2. расчет координат x0,y0 в пикселях x0pix:=PixelsPerSquare*mainway[SquareNo].X+footw; y0pix:=PixelsPerSquare*(GlobalMapHeight-mainway[SquareNo].Y)+footw; //3. отрисовка if BoolRight then boolRightAsInteger:=1 else boolRightAsInteger:=0; Bmp:=TBitMap.Create; bmp.SetSize(Im_Map.Width,Im_Map.Height); bmp:=Im_Map.Picture.Bitmap; bmp.Canvas.Draw(x0pix+xshift,y0pix+yshift,footsteps[boolRightAsInteger,direction]); Im_Map.Picture.Bitmap:=bmp; //4. расчет для следующего шага if StepNo=StepsPerSquare then begin StepNo:=1; SquareNo:=SquareNo+1; if SquareNo<length(mainway)-1 then begin if MainWay[SquareNo+1].X<MainWay[SquareNo].X then direction:=1;//left; if MainWay[SquareNo+1].Y>MainWay[SquareNo].Y then direction:=2;//up; if MainWay[SquareNo+1].X>MainWay[SquareNo].X then direction:=3;//right if MainWay[SquareNo+1].Y<MainWay[SquareNo].Y then direction:=4;//down; end; end else StepNo:=StepNo+1; BoolRight:=not boolRight; end; procedure TDrunkWalkmanForm.TmDrawStepTimer(Sender: TObject); begin DrawStep(); Im_Map.Refresh; if (SquareNo=length(MainWay)-1) then TmDrawStep.Enabled:=false;//Дошли до конца маршрута, отключаем рисовалку end; function StartExperiment(x0: integer; y0: integer; Mapheight: integer; MapWidth: integer; SquareLen: integer; Waylen: integer; p: TProbability): TWay; var overhead: integer; //остаток пути в шагах p1: TProbability; //пересчитываемая вероятность сделать шаг в одну из сторон psum: double; x,y: integer; randomvalue: double; i: Integer; begin overhead:=WayLen; SetLength(result,1); result[0].setLocation(x0,y0); x:=x0; y:=y0; while overhead>=SquareLen do begin randomize; randomvalue:=Random(); SetLength(result,length(result)+1); //пересчет вероятностей psum:=1; for i := 1 to 4 do p1[i]:=p[i]; if x=0 then begin psum:=psum-p[1]; p1[1]:=0; end; if y=Mapheight then begin psum:=psum-p[2]; p1[2]:=0; end; if x=MapWidth then begin psum:=psum-p[3]; p1[3]:=0; end; if y=0 then begin psum:=psum-p[4]; p1[4]:=0; end; for i := 1 to 4 do p1[i]:=p1[i]/psum; p1[4]:=p1[1]+p1[2]+p1[3]; p1[3]:=p1[1]+p1[2]; p1[2]:=p1[1]; p1[1]:=0; if randomvalue>p1[4] then begin //вниз x:=x; y:=y-1; end else if randomvalue>p1[3] then begin //вправо x:=x+1; y:=y; end else if randomvalue>p1[2] then begin //вверх x:=x; y:=y+1; end else begin //влево x:=x-1; y:=y; end; Result[length(result)-1].SetLocation(x,y); result[length(result)-1].randval:=randomvalue; overhead:=overhead-SquareLen; end; end; //############################################################### //раздел инициализации и служебных интерфейсных процедур procedure TDrunkWalkmanForm.FormCreate(Sender: TObject); var i,j: integer; begin //1. инициализация количества заходов в стринггриде Sg_SetNum.Cells[0,0]:='№ серии'; Sg_SetNum.Cells[1,0]:='к-во заходов'; for i := 1 to UD_SessionNum.Position do begin Sg_SetNum.Cells[0,i]:=inttostr(i)+' серия'; Sg_SetNum.Cells[1,i]:='1'; end; for i := 0 to 1 do for j := 1 to 4 do begin footsteps[i,j]:=TBitmap.Create; with footsteps[i,j] do begin PixelFormat:=pf32bit; AlphaFormat:=afDefined; end; ImageList2.GetBitmap(0,footsteps[0,1]); ImageList1.GetBitmap(0,footsteps[0,2]); ImageList2.GetBitmap(1,footsteps[0,3]); ImageList1.GetBitmap(1,footsteps[0,4]); ImageList2.GetBitmap(2,footsteps[1,1]); ImageList1.GetBitmap(2,footsteps[1,2]); ImageList2.GetBitmap(3,footsteps[1,3]); ImageList1.GetBitmap(3,footsteps[1,4]); end; StepNo:=1; SquareNo:=0; end; procedure TDrunkWalkmanForm.FormResize(Sender: TObject); var oldStepNo,oldSquareNo: integer; i,j: integer; begin DrawMap(); if length(Mainway)<2 then exit; oldStepNo:=StepNo; oldSquareNo:=SquareNo; StepNo:=1; SquareNo:=0; if MainWay[1].X<MainWay[0].X then direction:=1;//left; if MainWay[1].Y>MainWay[0].Y then direction:=2;//up; if MainWay[1].X>MainWay[0].X then direction:=3;//right if MainWay[1].Y<MainWay[0].Y then direction:=4;//down; while (not ((StepNo=OldStepNo)and(SquareNo=OldSquareNo))) do begin DrawStep(); end; Im_Map.Refresh; end; procedure TDrunkWalkmanForm.UD_SessionNumChangingEx(Sender: TObject; var AllowChange: Boolean; NewValue: SmallInt; Direction: TUpDownDirection); var i,j: integer; oldsessionNum: integer; begin oldsessionNum:=Sg_SetNum.RowCount-1; Sg_SetNum.RowCount:=NewValue+1; if oldsessionNum<NewValue then begin for i := oldsessionNum+1 to NewValue do begin Sg_SetNum.Cells[0,i]:=inttostr(i)+' серия'; Sg_SetNum.Cells[1,i]:='1'; end; end; end; end.
{*****************************************************} { } { EldoS Themes Support Library } { } { (C) 2002-2003 EldoS Corporation } { http://www.eldos.com/ } { } {*****************************************************} {$include elpack2.inc} {$IFDEF ELPACK_SINGLECOMP} {$I ElPack.inc} {$ELSE} {$IFDEF LINUX} {$I ../ElPack.inc} {$ELSE} {$I ..\ElPack.inc} {$ENDIF} {$ENDIF} unit ElThemesWindowsXPTypes; interface {$IFDEF ELPACK_THEME_ENGINE} uses Windows, Classes, Graphics; type TXPBgType = (bgNone, bgBorderFill, bgImageFile); TXPBorderType = (btNone, btRect, btRoundRect, btEllipse); TXPContentAlignment = (caLeft, caCenter, caRight); TXPFillType = (ftNone, ftSolid, ftVertGradient, ftHorzGradient, ftRadialGradient, ftTileImage); TXPFont = packed record Name: string[33]; Size: integer; Style: TFontStyles; end; TXPGlyphType = (gtNone, gtImageGlyph, gtFontGlyph); TXPHAlign = (haLeft, haCenter, haRight); TXPIconEffect = (ieNone, ieGlow, ieShadow, iePulse, ieAlpha); TXPImageLayout = (ilVertical, ilHorizontal); TXPImageSelect = (isNone, isDPI, isSize); TXPMargins = packed record Left: integer; Right: integer; Top: integer; Bottom: integer; end; TXPSize = packed record Width: integer; Height: integer; end; TXPOffsetType = (otTopLeft, otTopRight, otTopMiddle, otBottomLeft, otBottomRight, otBottomMiddle, otMiddleLeft, otMiddleRight, otLeftOfCaption, otRightOfCaption, otLeftOfLastButton, otRightOfLastButton, otAboveLastButton, otBelowLastButton); TXPShadowType = (stNone, stSingle, stContinuous); TXPSizingType = (stStretch, stTrueSize, stTile, stTileHorz, stTileVert, stTileCenter); TXPVAlign = (vaTop, vaCenter, vaBottom); TXPRectArray = array of TRect; PXPRectArray = ^TXPRectArray; {$ENDIF} implementation end.
program imgprocess1; {$mode objfpc}{$H+} {$linklib cvtutils} { Raspberry Pi 3 Application } { Add your program code below, add additional units to the "uses" section if } { required and create new units by selecting File, New Unit from the menu. } { } { To compile your program select Run, Compile (or Run, Build) from the menu. } {_$define UseFile} uses RaspberryPi3, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, Console, SysUtils, UltiboUtils, {Include Ultibo utils for some command line manipulation} HTTP, {Include HTTP and WebStatus so we can see from a web browser what is happening} WebStatus, Classes, Ultibo, FPImage, FPWriteXPM, FPWritePNG, FPWriteBMP, FPReadXPM, FPReadPNG, FPReadBMP, fpreadjpeg, fpwritejpeg, fpreadtga, fpwritetga, fpreadpnm, fpwritepnm, uTFTP, Winsock2, { needed to use ultibo-tftp } { needed for telnet } Shell, ShellFilesystem, ShellUpdate, RemoteShell, { needed for telnet } Logging, Syscalls, {Include the Syscalls unit to provide C library support} Crypto, APICrypto, FileSystem, FATFS, uFromC { Add additional units here }; function asciiValueToBinary(x0:LongWord):LongWord; cdecl; external 'libcvtutils' name 'asciiValueToBinary'; procedure processstr(s:String); cdecl; external 'libcvtutils' name 'processstr'; //procedure ReturnFromProcessStr(Value: PChar); cdecl; public name 'returnfromprocessstr'; //binaryToText(formattedBinary, strlen(formattedBinary), text, symbolCount); procedure processbinascstr(SBIN:String); cdecl; external 'libcvtutils' name 'processbinascstr'; type MODR = array[0..255,0..255] of word; MODRPtr = ^MODR; XORR = array[0..255,0..255] of word; XORRPtr = ^XORR; TLSB = array[0..255,0..255] of word; TLSBPtr = ^TLSB; Lsb = array[0..255] of byte; lsbPtr = ^Lsb; Buffer = array[0..255] of Char; //String[255]; BufPtr = ^Buffer; BufferH = array[0..255] of Char; //String[255]; BufPtrH = ^BufferH; CBC = record {0123456789abcdef0123456789abcdef} StrKeyAsc:String[32]; {0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef} StrKeyHex:String[80]; {0123456789abcdef} Strplaintext:array [1..1024] of String[16]; StrIV:array [1..1024] of String[32]; StrEnc:array [1..1024] of String[32]; StrDec:array [1..1024] of String[32]; end; GCM = record {128Bit Key} {Now we are engag} StrKeyAsc:array [1..32] of String[16]; {01234567890123456789012345678901 4e6f772077652061726520656e676167} StrKeyHex:array [1..32] of String[32]; Strplaintext:array [1..32] of String[16]; StrData:array [1..32] of String[32]; StrEnc:array [1..32] of String[32]; StrDec:array [1..32] of String[32]; StrIV:String[32]; StrAAD: String[32]; Actual:array [1..32] of String[80]; Expected:array [1..32] of String[80]; ActualTag:array [1..32] of String[80]; ExpectedTag:array [1..32] of String[80]; end; var Filename:String; img: TFPMemoryImage; reader : TFPCustomImageReader; Writer : TFPCustomimageWriter; ReadFile, WriteFile, WriteOptions : string; INPUTFILETYPE,OUTPUTFILETYPE: String; INPUTFILE,OUTPUTFILE: String; WindowHandle:TWindowHandle; MyPLoggingDevice : ^TLoggingDevice; HTTPListener:THTTPListener; { needed to use ultibo-tftp } TCP : TWinsock2TCPClient; IPAddress : string; h, w, bitcount,xorbit : Integer; clr: TFPColor; i, j: Integer; Red, Blue, Green : word; MyKey: AnsiString = '1234567890123456'; {Must be 16, 24 or 32 bytes} MyIV: AnsiString = 'My Secret IV'; MyAAD: AnsiString = 'My Extra Secret AAD'; MyData: AnsiString = 'The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.'; MyResult: AnsiString; Key: PByte; IV: PByte; AAD: PByte; Plain: PByte; Crypt: PByte; Tag: PByte; PCBC:^CBC; PGCM:^GCM; CBC1:CBC; GCM1:GCM; AESECBKey:PByte; AESECBData:PByte; AESECBAESKey:TAESKey; AESCBCKey:PByte; AESCBCData:PByte; AESCBCVector:PByte; AESGCMKey:PByte; AESGCMIV:PByte; AESGCMAAD:PByte; AESGCMData:PByte; AESGCMTag:PByte; Cipher:PCipherContext; Actual:String; PStrIV64:^Char; InKey:LongWord; InKeyStr:String; InDataStr:String; InIVStr:String; EncryptDecrypt:LongWord; StringList:TStringList; FileStream:TFileStream; S1,S2,SBIN:String; xx,yy : LongWord; databuffer :PChar; B : Buffer; BP : BufPtr; PP : Pointer; BH : Buffer; BPH : BufPtr; PPH : Pointer; bb : Lsb; bbp : LsbPtr; modbuf : MODR; xorbuf : XORR; tlsbbuf : TLSB; Count,ERRCount:Integer; function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1500); Result := TCP.LocalAddress; end; end; TCP.Free; end; procedure Msg (Sender : TObject; s : string); begin ConsoleWindowWriteLn (WindowHandle, s); end; procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; procedure Init; var t : char; begin if paramcount = 4 then begin T := upcase (paramstr(1)[1]); if T = 'X' then Reader := TFPReaderXPM.Create else if T = 'B' then Reader := TFPReaderBMP.Create else if T = 'J' then Reader := TFPReaderJPEG.Create else if T = 'P' then Reader := TFPReaderPNG.Create else if T = 'T' then Reader := TFPReaderTarga.Create else if T = 'N' then Reader := TFPReaderPNM.Create else begin Writeln('Unknown file format : ',T); //Halt(1); end; ReadFile := paramstr(2); WriteOptions := paramstr(3); WriteFile := paramstr(4); end else begin Reader := nil; ReadFile := paramstr(1); WriteOptions := paramstr(2); WriteFile := paramstr(3); end; WriteOptions := uppercase (writeoptions); T := WriteOptions[1]; if T = 'X' then Writer := TFPWriterXPM.Create else if T = 'B' then begin Writer := TFPWriterBMP.Create; TFPWriterBMP(Writer).BitsPerPixel:=32; end else if T = 'J' then Writer := TFPWriterJPEG.Create else if T = 'P' then Writer := TFPWriterPNG.Create else if T = 'T' then Writer := TFPWriterTARGA.Create else if T = 'N' then Writer := TFPWriterPNM.Create else begin Writeln('Unknown file format : ',T); //Halt(1); end; img := TFPMemoryImage.Create(0,0); img.UsePalette:=false; end; procedure ReadImage; {$ifndef UseFile}var str : TStream;{$endif} begin if assigned (reader) then img.LoadFromFile (ReadFile, Reader) else {$ifdef UseFile} img.LoadFromFile (ReadFile); {$else} if fileexists (ReadFile) then begin str := TFileStream.create (ReadFile,fmOpenRead); try img.loadFromStream (str); finally str.Free; end; end else writeln ('File ',readfile,' doesn''t exists!'); {$endif} end; procedure WriteImage; var t : string; begin t := WriteOptions; writeln (' WriteImage, options=',t); if (t[1] = 'P') then with (Writer as TFPWriterPNG) do begin Grayscale := pos ('G', t) > 0; Indexed := pos ('I', t) > 0; WordSized := pos('W', t) > 0; UseAlpha := pos ('A', t) > 0; writeln ('Grayscale ',Grayscale, ' - Indexed ',Indexed, ' - WordSized ',WordSized,' - UseAlpha ',UseAlpha); end else if (t[1] = 'X') then begin if length(t) > 1 then with (Writer as TFPWriterXPM) do begin ColorCharSize := ord(t[2]) - ord('0'); end; end; writeln ('Options checked, now writing...'); img.SaveToFile (WriteFile, Writer); end; procedure Clean; begin Reader.Free; Writer.Free; Img.Free; end; begin { Add your program code here LoggingDeviceSetTarget(LoggingDeviceFindByType(LOGGING_TYPE_FILE),'c:\ultibologging.log'); LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_FILE)); MyPLoggingDevice:=LoggingDeviceGetDefault; LoggingDeviceRedirectOutput(MyPLoggingDevice);} {Create a console window as usual} WindowHandle:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_FULL,True); ConsoleWindowWriteLn(WindowHandle,'Starting FPImage imgprocess1'); // Prompt for file type {ConsoleWindowWrite(WindowHandle,'Enter Input file type (X for XPM, P for PNG, B for BMP, J for JPEG, T for TGA): '); ConsoleWindowReadLn(WindowHandle,INPUTFILEType); ConsoleWindowWrite(WindowHandle,'Enter Output file type (X for XPM, P for PNG, B for BMP, J for JPEG, T for TGA): '); ConsoleWindowReadLn(WindowHandle,OUTPUTFILEType); ConsoleWindowWrite(WindowHandle,'Enter Input file '); ConsoleWindowReadLn(WindowHandle,INPUTFILE); ConsoleWindowWrite(WindowHandle,'Enter Output file '); ConsoleWindowReadLn(WindowHandle,OUTPUTFILE); ConsoleWindowWriteln(WindowHandle, INPUTFILEType+' '+INPUTFILE); ConsoleWindowWriteln(WindowHandle, OUTPUTFILEType+' '+OUTPUTFILE);} {Wait a couple of seconds for C:\ drive to be ready} ConsoleWindowWriteLn(WindowHandle,'Waiting for drive C:\'); while not DirectoryExists('C:\') do begin {Sleep for a second} Sleep(1000); end; // wait for IP address and SD Card to be initialised. WaitForSDDrive; IPAddress := WaitForIPComplete; {Wait a few seconds for all initialization (like filesystem and network) to be done} Sleep(5000); ConsoleWindowWriteLn(WindowHandle,'C:\ drive is ready'); ConsoleWindowWriteLn(WindowHandle,''); Filename:='C:\debug.txt'; if FileExists(Filename) then begin {If it does exist we can delete it} ConsoleWindowWriteLn(WindowHandle,'Deleting the file ' + Filename); DeleteFile('C:\debug.txt'); end; {Now create the file, let's use a TFileStream class to do this. We pass both the filename and the mode to TFileStream. fmCreate tells it to create a new file.} ConsoleWindowWriteLn(WindowHandle,'Creating a new file ' + Filename); {TFileStream will raise an exception if creating the file fails} {If you remove the SD card and put in back in your computer, you should see the file "Example 08 File Handling.txt" on it. If you open it in a notepad you should see the contents exactly as they appeared on screen.} ConsoleWindowWriteLn (WindowHandle, 'Local Address ' + IPAddress); SetOnMsg (@Msg); {Create and start the HTTP Listener for our web status page} {HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True);} ConsoleWindowWriteLn(WindowHandle,'Completed setting up WebStatus & IP'); HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True); ConsoleWindowWriteLn(WindowHandle,'Initing'); Reader := TFPReaderPNG.create; ConsoleWindowWriteLn(WindowHandle,'Reader png'); Writer := TFPWriterPNG.Create; ConsoleWindowWriteLn(WindowHandle,'Writer png'); ReadFile := 'input.png'; WriteFile := 'GrayScale.png'; //WriteOptions := 'P GrayScale'; WriteOptions := 'P'; img := TFPMemoryImage.Create(0,0); img.UsePalette:=false; //img.UsePalette:=true; hangs at reader is assigned. ConsoleWindowWriteLn(WindowHandle,' img create & UsePalette false'); ConsoleWindowWriteLn(WindowHandle,'Calling ReadImage ReadFile '+ReadFile); if assigned (reader) then ConsoleWindowWriteLn(WindowHandle,'img reader is assigned') else ConsoleWindowWriteLn(WindowHandle,'img reader is not assigned'); ReadImage; CBC1.StrKeyAsc:='abcdefghijklmnopqrstuvwxyz012345'; //CBC1.StrKeyAsc:='23AE14F4A7B2DC7F1DD89CF6F07E4048'; S1:=CBC1.StrKeyAsc; S2:=BytesToString(PByte(S1),Length(S1) * SizeOf(Char)); ConsoleWindowWriteLn (WindowHandle, 'CBC1.StrKeyAsc ' + CBC1.StrKeyAsc); ConsoleWindowWriteLn (WindowHandle, 'CBC1.StrKeyHex ' + CBC1.StrKeyHex); ConsoleWindowWriteLn (WindowHandle,S2); B:=S1; BP:=@B; //ConsoleWindowWriteLn (WindowHandle,'checking that BP points to string '+BP^[1]+BP^[2]+BP^[3]); ConsoleWindowWriteLn (WindowHandle,'This is the data in the buffer B '+B); ConsoleWindowWriteLn (WindowHandle,'Setting PP to the value of BP the BufPtr '); PP:=BP; ConsoleWindowWriteLn (WindowHandle,'PP is the pointer passed to returnfromprocessstr '); try FileStream:=TFileStream.Create(Filename,fmCreate); {We've created the file, now we need to write some content to it, we can use a TStringList for that but there are many other ways as well.} StringList:=TStringList.Create; {Add some text to our string list} //processstr('Now we are engaged in a great ci'); processstr('abcdefghijklmnopqrstuvwxyz012345'); //processstr('Now is the time for all good men'); //ConsoleWindowWriteLn(WindowHandle,'ProcessStrResult = ' + ProcessStrResult); StringList.Add(ProcessStrResult); i:=length(ProcessStrResult); B:=ProcessStrResult; BP:=@B; bbp:=@bb; i:=0; //i:=1; //Updated j:=0; while(i<256) do begin S1:=BP^[i]; bbp^[j]:=strToInt(S1) and $0f; ConsoleWindowWrite(WindowHandle,S1); //ConsoleWindowWrite(WindowHandle,intToStr(i)+' '+intToStr(j)+' '+S1+' '+intToStr(bbp^[j]) +' '); StringList.Add( intToStr(i)+' '+intToStr(j)+' '+S1+' '+intToStr(bbp^[j]) +' '); i:=i+1; j:=j+1; end; ConsoleWindowWriteLn(WindowHandle,' '); i:=0; while(i<256) do begin //S1:=BP^[i]; //bbp^[i-8]:=strToInt(S1); ConsoleWindowWrite(WindowHandle,intToStr(i)+ ' '+intToStr(bbp^[i]) +' '); i:=i+1; end; ConsoleWindowWriteLn(WindowHandle,' '); h:=img.Height; w:=img.Width; bitcount:=0; StringList.Add( 'Height ' + intToStr(h)+' Width '+intToStr(w)); ConsoleWindowWriteLn(WindowHandle,' '); ConsoleWindowWriteLn(WindowHandle,'Height ' + intToStr(h)+' Width '+intToStr(w)+' This will take some time!'); for j := 0 to img.Height - 1 do begin for i := 0 to img.Width - 1 do begin //if(i=0) then //bitcount:=0; clr := img.Colors[i, j]; //R*0.29900 + Line[x].G*0.58700 + Line[x].B*0.11400 clr.red:=round(clr.red*0.29900); clr.blue:=round(clr.blue*0.11400); clr.green:=round(clr.green*0.58700); clr.green:=clr.red+clr.blue+clr.green; clr.red:=clr.green; clr.blue:=clr.green; modbuf[i,j] := clr.red mod 2; //bitcount:= i + 8; {xorbit := bbp^[bitcount]; ConsoleWindowWriteLn(WindowHandle,intToStr(i)+' bitcount '+intToStr(bitcount)+' xorbit '+intToStr(xorbit)); } xx := modbuf[i,j] xor bbp^[i]; clr.red:=clr.red+xx; {x mod y 42668 (0) even 0 odd 1 40859 (1) ModRed 0 XORRed 1 temp 1 ModRed 1 XORRed 1 temp 0 ModRed 0 XORRed 0 temp 0 ModRed 1 XORRed 0 temp 1} //ConsoleWindowWriteLn(WindowHandle,intToStr(i)+' '+intToStr(j)+' '+intToStr(modbuf[i,j])+' '+intToStr(xx)+' '+intToStr(clr.red)+' '+intToStr(clr.green)); StringList.Add(intToStr(i)+' '+intToStr(j)+' '+intToStr(modbuf[i,j])+' '+intToStr(xx)+' '+intToStr(clr.red)+' '+intToStr(clr.green)+' '+intToStr(clr.blue)); clr.green:=clr.red; clr.blue:=clr.red; //ConsoleWindowWriteLn(WindowHandle,intToStr(i)+' '+intToStr(j)+' '+intToStr(clr.red)+' '+intToStr(clr.green)+' '+intToStr(clr.blue)); img.Colors[i, j] := clr; end; end; ConsoleWindowWriteLn(WindowHandle,' '); ConsoleWindowWriteLn(WindowHandle,'Decrypt Intial Steps. These are the bits we need to find!'); ConsoleWindowWriteLn(WindowHandle,'The String hidden will not be known'); ConsoleWindowWriteLn(WindowHandle,'Using the String hidden to test the hidden string'); B:=ProcessStrResult; BP:=@B; PP:=BP; BH:=''; BPH:=@BH; PPH:=BPH; //Pointer to hidden string ConsoleWindowWriteLn(WindowHandle,ProcessStrResult); ConsoleWindowWriteLn(WindowHandle,' '); ERRCount:=0; S2:=''; //for j := 0 to img.Height - 1 do begin //for i := 0 to 1 do for i := 0 to img.Width - 1 do begin clr := img.Colors[i, j]; modbuf[i,j] := clr.red mod 2 ; S1:=intToStr(modbuf[i,j]); S2:=S2+S1; BPH^[i]:=S1[1]; ConsoleWindowWrite(WindowHandle,BPH^[i] + '=' + BP^[i]+','); if(BPH^[i] <> BP^[i]) then begin ERRCount:=ERRCount+1; end; //BP^[i]:=S1; //ConsoleWindowWrite(WindowHandle,intToStr(modbuf[i,j])+' '); //ConsoleWindowWrite(WindowHandle,intToStr(i)+' '+S1+' '); //ConsoleWindowWrite(WindowHandle,S1 ); StringList.add(S1); //BP^[i]:=intToStr(modbuf[i,j]); //B[i]:=intToStr(modbuf[i,j]); img.Colors[i, j] := clr; end; ConsoleWindowWriteLn(WindowHandle,' '); ConsoleWindowWriteln(WindowHandle,'ERRORS '+intToStr(ERRCount)); ConsoleWindowWriteLn(WindowHandle,S2); //StringList.Add(' '); end; ConsoleWindowWriteLn(WindowHandle,' '); { S2 is the hidden string that is sent C code to convert to ASCII Now we are engaged in a great ci should be Now we are engaged in a great ch abcdefghijklmnopqrstuvwxyz012344 should be abcdefghijklmnopqrstuvwxyz012345 Now is the time for all good men is Now is the time for all good men even with errors of 1 } processbinascstr(S2); ConsoleWindowWriteLn(WindowHandle,'Return Ascii string ' + ProcessBinStrResult); StringList.Add(ProcessBinStrResult); StringList.SaveToStream(FileStream); FileStream.Free; StringList.Free; finally end; ConsoleWindowWriteLn(WindowHandle,'Calling WriteImage WriteFile '+WriteFile +' ' + WriteOptions); WriteImage; Clean; ThreadHalt(0); end.
unit ddCodexDataHolder; { $Id: ddCodexDataHolder.pas,v 1.2 2016/07/18 10:49:49 fireton Exp $ } interface uses l3Types, l3ProtoObject, l3StringList, dt_Types, ddAutolinkInterfaces; type TCodexDataHolder = class(Tl3ProtoObject, ICodexDataHolder) private f_ActualEdition: TddALDocRec; f_Abbreviations: Tl3StringList; {---} function Get_Abbreviations: Tl3StringList; function Get_ActualEdition: TddALDocRec; protected procedure Cleanup; override; public constructor Create(const aActualEdition: TDocID); class function Make(const aActualEdition: TDocID): ICodexDataHolder; end; implementation uses SysUtils, ddAutolinkUtils; constructor TCodexDataHolder.Create(const aActualEdition: TDocID); begin inherited Create; f_Abbreviations := Tl3StringList.MakeSorted; f_Abbreviations.SortIndex := l3_siCaseUnsensitive; f_ActualEdition := ddFillALDocRecFromExtDocID(aActualEdition); end; procedure TCodexDataHolder.Cleanup; begin FreeAndNil(f_Abbreviations); inherited; end; function TCodexDataHolder.Get_Abbreviations: Tl3StringList; begin Result := f_Abbreviations; end; class function TCodexDataHolder.Make(const aActualEdition: TDocID): ICodexDataHolder; var l_Holder : TCodexDataHolder; begin l_Holder := TCodexDataHolder.Create(aActualEdition); try Result := l_Holder; finally FreeAndNil(l_Holder); end; end; function TCodexDataHolder.Get_ActualEdition: TddALDocRec; begin Result := f_ActualEdition; end; end.
unit Modules; interface uses Data, Common, System.IOUtils, System.Generics.Collections; type /// <summary> /// A module is a set of functions and types in a common namespace. /// </summary> TModule = class protected FSourceFile : string; FContext : TContext; FRuntime : TRuntime; FName : string; public constructor Create(moduleFile : string); destructor Destroy(); override; property Context : TContext read FContext; property Name : string read FName; function Load(runtime : TRuntime) : Boolean; end; TModuleManager = class protected FModules : TObjectDictionary<string,TModule>; FRuntime : TRuntime; public constructor Create(runtime : TRuntime); destructor Destroy(); override; property Modules : TObjectDictionary<string,TModule> read FModules; function Load(filename : string) : TModule; end; implementation { TModule } constructor TModule.Create(moduleFile: string); begin FContext := TContext.Create(Nil); FSourceFile := moduleFile; FName := TPath.GetFileNameWithoutExtension(moduleFile); end; destructor TModule.Destroy; begin FContext.Free; FRuntime := nil; inherited; end; function TModule.Load(runtime: TRuntime): Boolean; begin runtime.Eval('(load "' + FSourceFile + '")', FContext); Result := True; end; { TModuleManager } constructor TModuleManager.Create(runtime : TRuntime); begin FModules := TObjectDictionary<string, TModule>.Create([doOwnsValues]); FRuntime := runtime; end; destructor TModuleManager.Destroy; begin FModules.Free; FRuntime := Nil; inherited; end; function TModuleManager.Load(filename: string) : TModule; var module : TModule; begin // TODO: Extract proper module name from filename // Check if the module already has been loaded if FModules.ContainsKey(filename) then Exit(FModules[filename]); // Otherwise load the module module := TModule.Create(filename); module.Load(FRuntime); FModules.Add(filename, module); Result := module; end; initialization finalization end.
unit GMIntServer; interface uses GMKernel, Collection; {$M+} type TCustomerInfo = class public constructor Create( ObjId : integer; aCustomerId : TCustomerId ); private fGMCustumer : IGMCustomer; fCustomerId : TCustomerId; function custIdToGMCustumer( aObjId : integer ) : IGMCustomer; public property GMCustumer : IGMCustomer read fGMCustumer; property CustomerId : TCustomerId read fCustomerId; end; TGMInterfaceServer = class(TInterfacedObject, IInterfaceServer, IIServerConnection ) public constructor Create; destructor Destroy; override; public procedure setGMServer( aGMServer : IGMServer ); procedure RegisterCustomer( ObjId : integer; aCostumerId : TCustomerId ); procedure UnregisterCustomer( aCostumerId : TCustomerId ); published //IInterfaceServer function ConnectToGameMaster( ClientId : TCustomerId; ClientInfo: widestring; GameMasters : widestring; out GMName : OleVariant; out PendingRequest : OleVariant; out GameMaster : OleVariant ) : OleVariant; function SendGMMessage( ClientId : TCustomerId; GMId : TGameMasterId; Msg : WideString ) : OleVariant; procedure DisconnectUser( ClientId : TCustomerId; GMId : TGameMasterId ); published //IIServerConnection function GameMasterMsg( ClientId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant; procedure GMNotify( ClientId : TCustomerId; notID : integer; Info : WideString ); private fCustomers : TLockableCollection; fGMServer : IGMServer; fId : TIServerId; fIdOnServer : TIServerId; function getCustomer( custId : TCustomerId ) : TCustomerInfo; end; {$M-} implementation uses GMIServerRDOMger; // TCustomerInfo constructor TCustomerInfo.Create( ObjId : integer; aCustomerId : TCustomerId ); begin inherited Create; fCustomerId := aCustomerId; fGMCustumer := custIdToGMCustumer( ObjId ); end; function TCustomerInfo.custIdToGMCustumer( aObjId : integer ) : IGMCustomer; begin result := IGMCustomer(aObjId); end; // TGMInterfaceServer constructor TGMInterfaceServer.Create; begin inherited Create; fCustomers := TLockableCollection.Create( 100, rkBelonguer ); fId := integer(self); end; destructor TGMInterfaceServer.Destroy; begin fCustomers.Free; inherited; end; procedure TGMInterfaceServer.setGMServer( aGMServer : IGMServer ); var Addr : widestring; port : integer; Id : OleVariant; begin try fGMServer := aGMServer; TheIServerRDOMger.getClientInfo( Addr, port ); fGMServer.RegisterInterfaceServer( fId, Addr, port, '', Id ); fIdOnServer := Id; except end; end; procedure TGMInterfaceServer.RegisterCustomer( ObjId : integer; aCostumerId : TCustomerId ); begin try fCustomers.Lock; try fCustomers.Insert( TCustomerInfo.Create( ObjId, aCostumerId ) ); finally fCustomers.Unlock; end; except end; end; procedure TGMInterfaceServer.UnregisterCustomer( aCostumerId : TCustomerId ); var Customer : TCustomerInfo; begin try fCustomers.Lock; try fGMServer.UnRegisterCustomer( fIdOnServer, aCostumerId ); Customer := getCustomer( aCostumerId ); fCustomers.Delete( Customer ); finally fCustomers.Unlock; end; except end; end; function TGMInterfaceServer.ConnectToGameMaster( ClientId : TCustomerId; ClientInfo: widestring; GameMasters : widestring; out GMName : OleVariant; out PendingRequest : OleVariant; out GameMaster : OleVariant ) : OleVariant; begin try result := fGMServer.ConnectToGameMaster( fIdOnServer, ClientId, ClientInfo, GameMasters, GMName, PendingRequest, GameMaster ); except result := GM_ERR_UNEXPECTED; end; end; function TGMInterfaceServer.SendGMMessage( ClientId : TCustomerId; GMId : TGameMasterId; Msg : WideString ) : OleVariant; begin try result := fGMServer.SendGMMessage( fIdOnServer, ClientId, GMId, Msg ); except result := GM_ERR_UNEXPECTED; end; end; procedure TGMInterfaceServer.DisconnectUser( ClientId : TCustomerId; GMId : TGameMasterId ); begin try fGMServer.DisconnectUser( fIdOnServer, ClientId, GMId ); except end; end; function TGMInterfaceServer.GameMasterMsg( ClientId : TCustomerId; Msg : WideString; Info : integer ) : OleVariant; var Customer : TCustomerInfo; begin try result := GM_ERR_NOERROR; Customer := getCustomer( ClientId ); if Customer <> nil then Customer.GMCustumer.GameMasterMsg( Msg, Info ) else result := GM_ERR_UNKNOWMCUST; except result := GM_ERR_UNEXPECTED; end; end; procedure TGMInterfaceServer.GMNotify( ClientId : TCustomerId; notID : integer; Info : WideString ); var Customer : TCustomerInfo; begin try Customer := getCustomer( ClientId ); if Customer <> nil then Customer.GMCustumer.GMNotify( notId, Info ); except end; end; function TGMInterfaceServer.getCustomer( custId : TCustomerId ) : TCustomerInfo; var i : integer; found : boolean; begin try fCustomers.Lock; try i := 0; found := false; while (i < fCustomers.Count) and not found do begin found := TCustomerInfo(fCustomers[i]).CustomerId = custId; inc( i ); end; if found then result := TCustomerInfo(fCustomers[pred(i)]) else result := nil; finally fCustomers.Unlock; end; except result := nil; end; end; end.
Unit H2ListBox; Interface Uses Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32,gr32_layers,Graphics; Type TH2ListBox = Class(TControl) Private fx, fy, fwidth, fheight, fcount, findent, ffirst, findex, fitemheight:Integer; fvisible:Boolean; ftitle:String; ffont: tfont; fbitmap:tbitmaplayer; fselect:tbitmap32; fdrawmode:tdrawmode; falpha:Cardinal; fitems:tstringlist; Procedure SetFont(value:tfont); Procedure SetItems(value:tstringlist); Procedure Setvisible(value:Boolean); Procedure SetItemindex(value:Integer); Procedure Setx(value:Integer); Procedure Sety(value:Integer); Procedure SetWidth(value:Integer); Procedure SetHeight(value:Integer); Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Procedure MouseDown(Sender: TObject; Buttons: TMouseButton; Shift: TShiftState; X, Y: Integer); Published Procedure LoadSelection(Filename:String); Procedure ScrollDown; Procedure ScrollUp; Procedure Clear; Procedure UpdateLV; Property Font:tfont Read ffont Write setfont; Property Alpha:Cardinal Read falpha Write falpha; Property DrawMode:tdrawmode Read fdrawmode Write fdrawmode; Property X:Integer Read fx Write setx; Property Y:Integer Read fy Write sety; Property Width:Integer Read fwidth Write setwidth; Property Title:String Read ftitle Write ftitle; Property Height:Integer Read fheight Write setheight; Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap; Property Items:tstringlist Read fitems Write Setitems; Property Visible:Boolean Read fvisible Write setvisible; Property ItemIndex:Integer Read findex Write setitemindex; Property Indent:Integer Read findent Write findent; Property ItemHeight:Integer Read fitemheight Write fitemheight; Property MaxItems:Integer Read fcount Write fcount; Property OnMouseDown; Property OnMouseMove; Property OnMouseUp; Property OnClick; Property OnDblClick; End; Implementation Uses unit1; { TH2ListBox } Procedure TH2ListBox.Clear; Begin fitems.Clear; ffirst:=0; findex:=-1; updatelv; End; Constructor TH2ListBox.Create(AOwner: TComponent); Var L: TFloatRect; alayer:tbitmaplayer; Begin Inherited Create(AOwner); fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers); fbitmap.OnMouseUp:=mousedown; ffont:=tfont.Create; fdrawmode:=dmblend; falpha:=255; fvisible:=True; fitems:=tstringlist.Create; ftitle:=''; fx:=0; fy:=0; fwidth:=100; fheight:=100; fbitmap.Bitmap.Width:=fwidth; fbitmap.Bitmap.Height:=fheight; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Tag:=0; fbitmap.Bitmap.DrawMode:=fdrawmode; fbitmap.Bitmap.MasterAlpha:=falpha; fselect:=tbitmap32.Create; fselect.DrawMode:=fdrawmode; fselect.MasterAlpha:=falpha; fcount:=5; findent:=0; ffirst:=0; findex:=-1; fitemheight:=20; End; Destructor TH2ListBox.Destroy; Begin //here ffont.Free; fbitmap.Free; fitems.Destroy; fselect.Free; Inherited Destroy; End; Procedure TH2ListBox.LoadSelection(Filename: String); Var au:Boolean; L: TFloatRect; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fselect,filename,au); Except End; End; End; Procedure TH2ListBox.MouseDown(Sender: TObject; Buttons: TMouseButton; Shift: TShiftState; X, Y: Integer); Var i,c:Integer; Begin If ffirst+fcount>fitems.Count-1 Then c:=fitems.Count-1 Else c:=ffirst+fcount; For i:=ffirst To c Do Begin If (x>=fx+findent) And (x<=fx+fwidth-findent) And (y>=fitemheight+fy+(fitemheight*(i-ffirst))) And (y<=fitemheight+fy+(fitemheight*(i-ffirst)+fitemheight)) Then findex:=i; End; updatelv; End; Procedure TH2ListBox.ScrollDown; Begin If ffirst+fcount>fitems.Count-1 Then exit; ffirst:=ffirst+fcount; updatelv; End; Procedure TH2ListBox.ScrollUp; Begin If ffirst-fcount<=0 Then ffirst:=0 Else ffirst:=ffirst-fcount; updatelv; End; Procedure TH2ListBox.SetFont(value: tfont); Var Color: Longint; r, g, b: Byte; Begin ffont.Assign(value); Color := ColorToRGB(ffont.Color); r := Color; g := Color Shr 8; b := Color Shr 16; fbitmap.Bitmap.Font.assign(ffont); End; Procedure TH2ListBox.SetHeight(value: Integer); Var L: TFloatRect; Begin fheight:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Bitmap.Height:=fheight; End; Procedure TH2ListBox.SetItemindex(value: Integer); Begin findex:=value; updatelv; End; Procedure TH2ListBox.SetItems(value: tstringlist); Begin fitems.Assign(value); findex:=fitems.Count-1; updatelv; End; Procedure TH2ListBox.Setvisible(value: Boolean); Begin fbitmap.Visible:=value; End; Procedure TH2ListBox.SetWidth(value: Integer); Var L: TFloatRect; Begin fwidth:=value; l.Left:=fx; l.Top :=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Bitmap.Width:=fwidth; End; Procedure TH2ListBox.Setx(value: Integer); Var L: TFloatRect; Begin fx:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; End; Procedure TH2ListBox.Sety(value: Integer); Var L: TFloatRect; Begin fy:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; End; Procedure TH2ListBox.UpdateLV; Var i,c,h:Integer; Color: Longint; r, g, b: Byte; Begin fbitmap.Bitmap.Clear($000000); Color := ColorToRGB(ffont.Color); r := Color; g := Color Shr 8; b := Color Shr 16; fbitmap.Bitmap.Font.Assign(ffont); h:=(fitemheight Div 2)-(fbitmap.bitmap.TextHeight(ftitle) Div 2); fbitmap.Bitmap.Rendertext(findent,h,ftitle,0,color32(r,g,b,falpha)); h:=(fitemheight Div 2)-(fbitmap.bitmap.TextHeight(inttostr(findex+1)+'/'+inttostr(fitems.Count)) Div 2); c:=fbitmap.bitmap.Textwidth(inttostr(findex+1)+'/'+inttostr(fitems.Count)); fbitmap.Bitmap.Rendertext(fwidth-c,h,inttostr(findex+1)+'/'+inttostr(fitems.Count),0,color32(r,g,b,falpha)); If fitems.Count=0 Then exit; If ffirst+fcount>fitems.Count-1 Then c:=fitems.Count-1 Else c:=ffirst+fcount; For i:=ffirst To c Do Begin If i=findex Then Begin fselect.DrawTo(fbitmap.Bitmap,0,fitemheight+fitemheight*(i-ffirst)); End; h:=(fitemheight Div 2)-(fbitmap.bitmap.TextHeight(fitems[i]) Div 2); fbitmap.Bitmap.Rendertext(findent,(fitemheight*(i-ffirst))+h+fitemheight,fitems[i],0,color32(r,g,b,falpha)); End; End; End.
unit k053260; interface uses {$IFDEF WINDOWS}windows,{$ENDIF}sound_engine,misc_functions,timer_engine; type tKDSC_Voice=class constructor create(adpcm_rom:pbyte;size:dword); destructor free; public procedure play; function voice_playing:boolean; function read_rom:byte; private // live state position:dword; pan_volume:array[0..1] of word; counter:word; output:shortint; out1,out2:integer; is_playing:boolean; // per voice registers start:dword; length:word; pitch:word; volume:byte; // bit packed registers pan:byte; loop:boolean; kadpcm:boolean; rom:pbyte; rom_size:dword; procedure voice_reset; procedure set_register(offset:word;data:byte); procedure set_loop_kadpcm(data:byte); procedure set_pan(data:byte); procedure update_pan_volume; procedure key_on; procedure key_off; end; tk053260_chip=class(snd_chip_class) constructor create(clock:dword;rom:pbyte;size:dword;amp:single); destructor free; public procedure update; procedure reset; function main_read(direccion:byte):byte; procedure main_write(direccion,valor:byte); function read(direccion:byte):byte; procedure write(direccion,valor:byte); private // configuration rgnoverride:byte; // live state portdata:array[0..3] of byte; keyon:byte; mode:byte; voice:array[0..3] of tKDSC_Voice; ntimer,tsample_num2:byte; buffer:array[0..1,0..4] of integer; posicion:byte; procedure internal_update; end; var k053260_0:tk053260_chip; procedure internal_update_k053260; implementation const CLOCKS_PER_SAMPLE=32; constructor tk053260_chip.create(clock:dword;rom:pbyte;size:dword;amp:single); var f:byte; begin for f:=0 to 3 do self.voice[f]:=tKDSC_Voice.create(rom,size); self.ntimer:=timers.init(sound_status.cpu_num,sound_status.cpu_clock/(clock/CLOCKS_PER_SAMPLE),internal_update_k053260,nil,true); self.tsample_num:=init_channel; self.tsample_num2:=init_channel; self.amp:=amp; end; destructor tk053260_chip.free; var f:byte; begin for f:=0 to 3 do self.voice[f].free; end; procedure tk053260_chip.reset; var f:byte; begin for f:=0 to 3 do self.voice[f].voice_reset; self.posicion:=0; for f:=0 to 4 do begin self.buffer[0,f]:=0; self.buffer[1,f]:=0; end; end; function tk053260_chip.main_read(direccion:byte):byte; begin main_read:=self.portdata[2+(direccion and 1)]; end; procedure tk053260_chip.main_write(direccion,valor:byte); begin self.portdata[direccion and 1]:=valor; end; function tk053260_chip.read(direccion:byte):byte; var ret,f:byte; begin direccion:=direccion and $3f; ret:=0; case direccion of $00,$01:ret:=self.portdata[direccion]; // main-to-sub ports $29:for f:=0 to 3 do ret:=ret or (byte(self.voice[f].voice_playing) shl f); // voice status $2e:if (self.mode and 1)<>0 then ret:=self.voice[0].read_rom; // read ROM end; read:=ret; end; procedure tk053260_chip.write(direccion,valor:byte); var f,rising_edge:byte; begin direccion:=direccion and $3f; // per voice registers if ((direccion>=$08) and (direccion<=$27)) then begin self.voice[(direccion-8) div 8].set_register(direccion,valor); exit; end; case direccion of // 0x00 and 0x01 are read registers $02,$03:self.portdata[direccion]:=valor; // sub-to-main ports // 0x04 through 0x07 seem to be unused $28:begin // key on/off rising_edge:=valor and not(self.keyon); for f:=0 to 3 do begin if ((rising_edge and (1 shl f))<>0) then self.voice[f].key_on else if ((valor and (1 shl f))=0) then self.voice[f].key_off; end; self.keyon:=valor; end; // 0x29 is a read register $2a:begin // loop and pcm/adpcm select for f:=0 to 3 do begin self.voice[f].set_loop_kadpcm(valor); valor:=valor shr 1; end; end; // 0x2b seems to be unused $2c:begin // pan, voices 0 and 1 self.voice[0].set_pan(valor); self.voice[1].set_pan(valor shr 3); end; $2d:begin // pan, voices 2 and 3 self.voice[2].set_pan(valor); self.voice[3].set_pan(valor shr 3); end; // 0x2e is a read register $2f:begin // control self.mode:=valor; // bit 0 = enable ROM read from register 0x2e // bit 1 = enable sound output // bit 2 = enable aux input? // (set by all games except Golfing Greats and Rollergames, both of which // don't have a YM2151. Over Drive only sets it on one of the two chips) // bit 3 = aux input or ROM sharing related? // (only set by Over Drive, and only on the same chip that bit 2 is set on) end; end; end; procedure tk053260_chip.update; var out1,out2:integer; f:byte; begin out1:=0; out2:=0; if self.posicion<>0 then begin for f:=0 to (self.posicion-1) do begin out1:=out1+self.buffer[0,f]; out2:=out2+self.buffer[1,f]; end; out1:=round(out1/self.posicion); out2:=round(out2/self.posicion); if out1<-32767 then out1:=-32767 else if out1>32767 then out1:=32767; if out2<-32767 then out2:=-32767 else if out2>32767 then out2:=32767; end; if sound_status.stereo then begin tsample[self.tsample_num,sound_status.posicion_sonido]:=round(out1*self.amp); tsample[self.tsample_num,sound_status.posicion_sonido+1]:=round(out2*self.amp); end else begin //Channel 1 tsample[self.tsample_num,sound_status.posicion_sonido]:=round(out1*self.amp); //Channel 2 tsample[self.tsample_num2,sound_status.posicion_sonido]:=round(out2*self.amp); end; self.posicion:=0; for f:=0 to 4 do begin self.buffer[0,f]:=0; self.buffer[1,f]:=0; end; end; procedure internal_update_k053260; begin k053260_0.internal_update; end; function sshr(num:int64;fac:byte):int64; begin if num<0 then sshr:=-(abs(num) shr fac) else sshr:=num shr fac; end; procedure tk053260_chip.internal_update; var f:byte; begin if (self.mode and 2)<>0 then begin for f:=0 to 3 do begin if (self.voice[f].voice_playing) then self.voice[f].play; self.buffer[0,self.posicion]:=self.buffer[0,self.posicion]+sshr(self.voice[f].out1,1); self.buffer[1,self.posicion]:=self.buffer[1,self.posicion]+sshr(self.voice[f].out2,1); end; end; self.posicion:=self.posicion+1; end; //KDSC Voice constructor tKDSC_Voice.create(adpcm_rom:pbyte;size:dword); begin self.rom:=adpcm_rom; self.rom_size:=size; end; destructor tKDSC_Voice.free; begin end; function tKDSC_Voice.voice_playing:boolean; begin voice_playing:=self.is_playing; end; procedure tKDSC_Voice.voice_reset; begin self.position:=0; self.counter:=0; self.output:=0; self.is_playing:=false; self.start:=0; self.length:=0; self.pitch:=0; self.volume:=0; self.pan:=0; self.loop:=false; self.kadpcm:=false; self.update_pan_volume; end; procedure tKDSC_Voice.set_register(offset:word;data:byte); begin case offset and $7 of 0:self.pitch:=(self.pitch and $0f00) or data; // pitch, lower 8 bits 1:self.pitch:=(self.pitch and $00ff) or ((data shl 8) and $0f00); // pitch, upper 4 bits 2:self.length:=(self.length and $ff00) or data; // length, lower 8 bits 3:self.length:=(self.length and $00ff) or (data shl 8); // length, upper 8 bits 4:self.start:=(self.start and $1fff00) or data; // start, lower 8 bits 5:self.start:=(self.start and $1f00ff) or (data shl 8); // start, middle 8 bits 6:self.start:=(self.start and $00ffff) or ((data shl 16) and $1f0000); // start, upper 5 bits 7:begin // volume, 7 bits self.volume:=data and $7f; self.update_pan_volume; end; end; end; procedure tKDSC_Voice.set_loop_kadpcm(data:byte); begin self.loop:=BIT(data,0); self.kadpcm:=BIT(data,4); end; procedure tKDSC_Voice.set_pan(data:byte); begin self.pan:=data and $7; self.update_pan_volume; end; procedure tKDSC_Voice.update_pan_volume; begin self.pan_volume[0]:=self.volume*(8-self.pan); self.pan_volume[1]:=self.volume*self.pan; end; procedure tKDSC_Voice.key_on; begin { if (self.start >= m_device->m_rom_size) logerror("K053260: Attempting to start playing past the end of the ROM ( start = %06x, length = %06x )\n", m_start, m_length); else if (m_start + m_length >= m_device->m_rom_size) logerror("K053260: Attempting to play past the end of the ROM ( start = %06x, length = %06x )\n", m_start, m_length); else } self.position:=byte(self.kadpcm); // for kadpcm low bit is nybble offset, so must start at 1 due to preincrement self.counter:=$1000-CLOCKS_PER_SAMPLE; // force update on next sound_stream_update self.output:=0; self.is_playing:=true; end; procedure tKDSC_Voice.key_off; begin self.position:=0; self.output:=0; self.is_playing:=false; end; procedure tKDSC_Voice.play; const kadpcm_table:array[0..15] of shortint=(0,1,2,4,8,16,32,64,-128,-64,-32,-16,-8,-4,-2,-1); var bytepos:dword; romdata:byte; begin self.counter:=self.counter+CLOCKS_PER_SAMPLE; while (self.counter>=$1000) do begin self.counter:=self.counter-$1000+self.pitch; self.position:=self.position+1; bytepos:=self.position shr byte(self.kadpcm); {Yes, _pre_increment. Playback must start 1 byte position after the start address written to the register, or else ADPCM sounds will have DC offsets (e.g. TMNT2 theme song) or will overflow and be distorted (e.g. various Vendetta sound effects) The "headers" in the Simpsons and Vendetta sound ROMs provide further evidence of this quirk (the start addresses listed in the ROM header are all 1 greater than the addresses the CPU writes into the register) } if (bytepos>self.length) then begin if (self.loop) then begin self.position:=0; self.output:=0; bytepos:=0; end else begin self.is_playing:=false; exit; end; end; romdata:=self.rom[self.start+bytepos]; if self.kadpcm then begin if (self.position and 1)<>0 then romdata:=romdata shr 4; // decode low nybble, then high nybble self.output:=self.output+kadpcm_table[romdata and $f]; end else begin self.output:=romdata; end; self.out1:=self.output*self.pan_volume[0]; self.out2:=self.output*self.pan_volume[1]; end; end; function tKDSC_Voice.read_rom:byte; var offs:dword; begin offs:=self.start+self.position; self.position:=(self.position+1) and $ffff; if (offs>=self.rom_size) then read_rom:=0 else read_rom:=self.rom[offs]; end; end.
unit BasicAccounts; interface const accIdx_None = -1; accIdx_Master = 0; accIdx_Roads = 1; accIdx_Commerce = 3; accIdx_Industries = 4; accIdx_Public = 5; accIdx_Firms = 7; accIdx_RoadConstruction = 8; accIdx_RoadDemolition = 9; accIdx_RoadMaintenance = 90; accIdx_Construction = 11; accIdx_Loans = 12; accIdx_TransfersIn = 13; accIdx_TransfersOut = 14; // Residentials accIdx_Residentials = 2; accIdx_Residentials_Rents = 15; accIdx_Residentials_Maintenance = 16; accIdx_Residentials_Repairs = 17; // Offices sub-accounts accIdx_Offices = 6; accIdx_Offices_Rents = 18; accIdx_Offices_Maintenance = 19; accIdx_Offices_Repairs = 20; // Public Facilities accIdx_PF_Salaries = 22; accIdx_PublicBudget = 23; accIdx_PF_PublicOperation = 24; // Research Centers accIdx_ResearchCenter = 30; accIdx_ResearchCenter_Research = 31; accIdx_ResearchCenter_Salaries = 32; accIdx_ResearchCenter_Equipment = 33; accIdx_ResearchCenter_Supplies = 34; accIdx_ResearchCenter_ImpCosts = 35; // General accIdx_RentalProperties = 40; accIdx_Special = 41; accIdx_Compensations = 42; // Banks accIdx_Bank = 45; accIdx_Bank_LoanIncome = 46; accIdx_Bank_IssuedLoans = 47; accIdx_Bank_Loans = 48; accIdx_Bank_LoanPayments = 49; accIdx_Bank_Salaries = 50; procedure RegisterAccounts; implementation uses Accounts; procedure RegisterAccounts; begin with TMetaAccount.Create( accIdx_Master, accIdx_None, 'Net Profit (losses)', '', TAccount ) do begin Rankeable := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Construction, accIdx_Master, 'Construction', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Roads, accIdx_Construction, 'Roads', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_RentalProperties, accIdx_Master, 'Rental properties', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Residentials, accIdx_RentalProperties, 'Residentials', '', TAccount ) do begin Taxable := true; Rankeable := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Commerce, accIdx_Master, 'Commerce', '', TAccount ) do begin Rankeable := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Industries, accIdx_Master, 'Industries', '', TAccount ) do begin Rankeable := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Offices, accIdx_RentalProperties, 'Offices', '', TAccount ) do begin Taxable := true; Rankeable := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Firms, accIdx_Master, 'Firms', '', TAccount ) do begin Rankeable := true; Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_RoadConstruction, accIdx_Roads, 'Road Construction', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_RoadDemolition, accIdx_Roads, 'Road Demolition', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_RoadMaintenance, accIdx_Roads, 'Road Maintenance', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Loans, accIdx_Master, 'Loans', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_TransfersIn, accIdx_Master, 'Money Recieved', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_TransfersOut, accIdx_Master, 'Money Sent', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Special, accIdx_Master, 'Special', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_PublicBudget, accIdx_Special, 'State Budget', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Public, accIdx_Special, 'Public Facilities', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Compensations, accIdx_Special, 'Compensations', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; // Residential sub-accounts with TMetaAccount.Create( accIdx_Residentials_Rents, accIdx_Residentials, 'Rents', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Residentials_Maintenance, accIdx_Residentials, 'Maintenance', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Residentials_Repairs, accIdx_Residentials, 'Repairs', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; // Offices sub-accounts with TMetaAccount.Create( accIdx_Offices_Rents, accIdx_Offices, 'Rents', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Offices_Maintenance, accIdx_Offices, 'Maintenance', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Offices_Repairs, accIdx_Offices, 'Repairs', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; // Public Facilities with TMetaAccount.Create( accIdx_PF_Salaries, accIdx_Public, 'Salaries', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; // Public Facilities Operating costs with TMetaAccount.Create( accIdx_PF_PublicOperation, accIdx_Public, 'Operating costs', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; // Research Centers with TMetaAccount.Create( accIdx_ResearchCenter, accIdx_Special, 'Headquarters', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_ResearchCenter_Research, accIdx_ResearchCenter, 'Researchs', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_ResearchCenter_Salaries, accIdx_ResearchCenter, 'Salaries', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_ResearchCenter_Equipment, accIdx_ResearchCenter, 'Equipment', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_ResearchCenter_Supplies, accIdx_ResearchCenter, 'Services', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_ResearchCenter_ImpCosts, accIdx_ResearchCenter, 'Implementation Costs', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Bank, accIdx_Special, 'Bank', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Bank_LoanIncome, accIdx_Bank, 'Debtors payments', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Bank_IssuedLoans, accIdx_Bank, 'Issued loans', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Bank_Loans, accIdx_Bank, 'Loan', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Bank_LoanPayments, accIdx_Bank, 'Loan payments', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; with TMetaAccount.Create( accIdx_Bank_Salaries, accIdx_Bank, 'Salaries', '', TAccount ) do begin Register( tidClassFamily_Accounts ); end; end; end.
(*==========================================================================; * * Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved. * * File: d3drm.h * Content: Direct3DRM include file * * DirectX 6 Delphi adaptation by Erik Unger * * Modyfied: 16.Jul.98 * * Download: http://www.bigfoot.com/~ungerik/ * E-Mail: ungerik@bigfoot.com * ***************************************************************************) unit D3DRMWin; interface uses {$IFDEF D2COM} OLE2, {$ENDIF} Windows, D3DRM, DirectDraw, Direct3D, D3DRMObj; (* * GUIDS used by Direct3DRM Windows interface *) const IID_IDirect3DRMWinDevice: TGUID = (D1:$c5016cc0;D2:$d273;D3:$11ce;D4:($ac,$48,$00,$00,$c0,$38,$25,$a1)); type {$IFDEF D2COM} IDirect3DRMWinDevice = class (IDirect3DRMObject) {$ELSE} IDirect3DRMWinDevice = interface (IDirect3DRMObject) ['{c5016cc0-d273-11ce-ac48-0000c03825a1}'] {$ENDIF} (* * IDirect3DRMWinDevice methods *) (* Repaint the window with the last frame which was rendered. *) function HandlePaint (hDC: HDC) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} (* Respond to a WM_ACTIVATE message. *) function HandleActivate (wparam: WORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; implementation end.
unit Control.Cadastro; interface uses Model.Cadastro, System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Classes; type TCadastroControl = class private FCadastro : TCadastro; public constructor Create; destructor Destroy; override; function Gravar: Boolean; function Localizar(aParam: array of variant): Boolean; function GetId(): Integer; function GetField(sField: String; sKey: String; sKeyValue: String): String; // function ValidaCampos(): Boolean; function SetupModel(FDCadastro: TFDQuery): Boolean; property Cadastro: TCadastro read FCadastro write FCadastro; end; implementation uses Global.Parametros; { TCadastroControl } constructor TCadastroControl.Create; begin FCadastro := TCadastro.Create; end; destructor TCadastroControl.Destroy; begin FCadastro.Free; inherited; end; function TCadastroControl.GetField(sField, sKey, sKeyValue: String): String; begin Result := FCadastro.GetField(sField, sKey, sKeyValue); end; function TCadastroControl.GetId: Integer; begin Result := FCadastro.GetID; end; function TCadastroControl.Gravar: Boolean; begin Result := False; // if not ValidaCampos() then Exit; Result := Fcadastro.Gravar; end; function TCadastroControl.Localizar(aParam: array of variant): Boolean; begin Result := Fcadastro.Localizar(aParam); end; function TCadastroControl.SetupModel(FDCadastro: TFDQuery): Boolean; begin Result := FCadastro.SetupModel(FDCadastro); end; end.
unit FileOpUtils; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, ShellApi; function CopyFile( const SourceName, DestName : string; Flags : dword ) : boolean; function MoveFile( const SourceName, DestName : string; Flags : dword ) : boolean; function RenameFile( const SourceName, DestName : string; Flags : dword ) : boolean; function DeleteFile( const SourceName : string; Flags : dword ) : boolean; // Use these in case you have more than one file to process (The format is file1#0file2#0...filen#0#0) // You should use the function JoinStringList( List : TStringList ), // or JoinStrings( Strings : array of string ), both in the unit StrUtils function CopyFiles( SourceName : pchar; const DestName : string; Flags : dword ) : boolean; function MoveFiles( SourceName : pchar; const DestName : string; Flags : dword ) : boolean; function RenameFiles( SourceName : pchar; const DestName : string; Flags : dword ) : boolean; function DeleteFiles( SourceName : pchar; Flags : dword ) : boolean; // In case you need to specify a Parent: function CopyFileEx( ParentHandle : HWND; const SourceName, DestName : string; Flags : dword ) : boolean; function MoveFileEx( ParentHandle : HWND; const SourceName, DestName : string; Flags : dword ) : boolean; function RenameFileEx( ParentHandle : HWND; const SourceName, DestName : string; Flags : dword ) : boolean; function DeleteFileEx( ParentHandle : HWND; const SourceName : string; Flags : dword ) : boolean; function CopyFilesEx( ParentHandle : HWND; SourceName : pchar; const DestName : string; Flags : dword ) : boolean; function MoveFilesEx( ParentHandle : HWND; SourceName : pchar; const DestName : string; Flags : dword ) : boolean; function RenameFilesEx( ParentHandle : HWND; SourceName : pchar; const DestName : string; Flags : dword ) : boolean; function DeleteFilesEx( ParentHandle : HWND; SourceName : pchar; Flags : dword ) : boolean; implementation uses Forms; function CopyFile( const SourceName, DestName : string; Flags : dword ) : boolean; begin Result := CopyFileEx( Screen.ActiveForm.Handle, SourceName, DestName, Flags ); end; function MoveFile( const SourceName, DestName : string; Flags : dword ) : boolean; begin Result := MoveFileEx( Screen.ActiveForm.Handle, SourceName, DestName, Flags ); end; function RenameFile( const SourceName, DestName : string; Flags : dword ) : boolean; begin Result := RenameFileEx( Screen.ActiveForm.Handle, SourceName, DestName, Flags ); end; function DeleteFile( const SourceName : string; Flags : dword ) : boolean; begin Result := DeleteFileEx( Screen.ActiveForm.Handle, SourceName, Flags ); end; function CopyFiles( SourceName : pchar; const DestName : string; Flags : dword ) : boolean; begin Result := CopyFilesEx( Screen.ActiveForm.Handle, SourceName, DestName, Flags ); end; function MoveFiles( SourceName : pchar; const DestName : string; Flags : dword ) : boolean; begin Result := MoveFilesEx( Screen.ActiveForm.Handle, SourceName, DestName, Flags ); end; function RenameFiles( SourceName : pchar; const DestName : string; Flags : dword ) : boolean; begin Result := RenameFilesEx( Screen.ActiveForm.Handle, SourceName, DestName, Flags ); end; function DeleteFiles( SourceName : pchar; Flags : dword ) : boolean; begin Result := DeleteFilesEx( Screen.ActiveForm.Handle, SourceName, Flags ); end; function CopyFileEx( ParentHandle : HWND; const SourceName, DestName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; Filename : string; begin SetString( Filename, pchar(SourceName), length( SourceName ) + 1 ); pchar(Filename)[length(SourceName) + 1] := #0; with fos do begin Wnd := ParentHandle; wFunc := FO_COPY; pFrom := pchar( Filename ); pTo := pchar( DestName ); if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; function MoveFileEx( ParentHandle : HWND; const SourceName, DestName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; Filename : string; begin SetString( Filename, pchar(SourceName), length( SourceName ) + 1 ); pchar(Filename)[length(SourceName) + 1] := #0; with fos do begin Wnd := ParentHandle; wFunc := FO_MOVE; pFrom := pchar( Filename ); pTo := pchar( DestName ); if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; function RenameFileEx( ParentHandle : HWND; const SourceName, DestName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; Filename : string; begin SetString( Filename, pchar(SourceName), length( SourceName ) + 1 ); pchar(Filename)[length(SourceName) + 1] := #0; with fos do begin Wnd := ParentHandle; wFunc := FO_MOVE; pFrom := pchar( Filename ); pTo := pchar( DestName ); if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; function DeleteFileEx( ParentHandle : HWND; const SourceName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; Filename : string; begin SetString( Filename, pchar(SourceName), length( SourceName ) + 1 ); pchar(Filename)[length(SourceName) + 1] := #0; with fos do begin Wnd := ParentHandle; wFunc := FO_DELETE; pFrom := pchar( Filename ); pTo := nil; if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; // Multiple files function CopyFilesEx( ParentHandle : HWND; SourceName : pchar; const DestName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; begin with fos do begin Wnd := ParentHandle; wFunc := FO_COPY; pFrom := SourceName; pTo := pchar( DestName ); if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; function MoveFilesEx( ParentHandle : HWND; SourceName : pchar; const DestName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; begin with fos do begin Wnd := ParentHandle; wFunc := FO_MOVE; pFrom := SourceName; pTo := pchar( DestName ); if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; function RenameFilesEx( ParentHandle : HWND; SourceName : pchar; const DestName : string; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; begin with fos do begin Wnd := ParentHandle; wFunc := FO_MOVE; pFrom := SourceName; pTo := pchar( DestName ); if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; function DeleteFilesEx( ParentHandle : HWND; SourceName : pchar; Flags : dword ) : boolean; var fos : TSHFILEOPSTRUCT; begin with fos do begin Wnd := ParentHandle; wFunc := FO_DELETE; pFrom := SourceName; pTo := nil; if Flags = 0 then fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_SILENT else fFlags := Flags; hNameMappings := nil; lpszProgressTitle := nil; end; Result := SHFileOperation( fos ) = 0; end; end.
unit UConfiguracao; interface uses FireDAC.Comp.Client, SysUtils, Vcl.Forms, Windows, Vcl.Controls, Data.DB, System.Classes, Vcl.CheckLst, UFuncoesFaciliteXE8, uConstantes; type TConfiguracao = class(TObject) private FConexao : TFDConnection; vloFuncoes : TFuncoesGerais; FCONFAI_PRESIRPJ: Double; FCONFAI_EMPRESA: String; FCONFAI_ALIQCSLL: Double; FCONFAI_ALIQIRPJ: Double; FCONFAI_ALIQPIS: Double; FCONFAI_ALIQCOFINS: Double; FCONFAI_PRESCSLL: Double; FCONFAI_TIPOSNF: String; procedure SetCONFAI_ALIQCOFINS(const Value: Double); procedure SetCONFAI_ALIQCSLL(const Value: Double); procedure SetCONFAI_ALIQIRPJ(const Value: Double); procedure SetCONFAI_ALIQPIS(const Value: Double); procedure SetCONFAI_EMPRESA(const Value: String); procedure SetCONFAI_PRESCSLL(const Value: Double); procedure SetCONFAI_PRESIRPJ(const Value: Double); procedure SetCONFAI_TIPOSNF(const Value: String); public constructor Create(poConexao: TFDConnection); destructor Destroy; override; function fncRetornaTipoNF(psEmpresa: String) : TFDQuery; procedure pcdGravaConfiguracao; function fncCarregaDadosExistentes(psEmpresa: String) : TFDQuery; published property CONFAI_EMPRESA : String read FCONFAI_EMPRESA write SetCONFAI_EMPRESA; property CONFAI_TIPOSNF : String read FCONFAI_TIPOSNF write SetCONFAI_TIPOSNF; property CONFAI_ALIQPIS : Double read FCONFAI_ALIQPIS write SetCONFAI_ALIQPIS; property CONFAI_ALIQCOFINS : Double read FCONFAI_ALIQCOFINS write SetCONFAI_ALIQCOFINS; property CONFAI_ALIQIRPJ : Double read FCONFAI_ALIQIRPJ write SetCONFAI_ALIQIRPJ; property CONFAI_ALIQCSLL : Double read FCONFAI_ALIQCSLL write SetCONFAI_ALIQCSLL; property CONFAI_PRESIRPJ : Double read FCONFAI_PRESIRPJ write SetCONFAI_PRESIRPJ; property CONFAI_PRESCSLL : Double read FCONFAI_PRESCSLL write SetCONFAI_PRESCSLL; end; implementation { TConfiguracao } constructor TConfiguracao.Create(poConexao: TFDConnection); begin inherited Create; FConexao := poConexao; vloFuncoes := TFuncoesGerais.Create(FConexao); end; destructor TConfiguracao.Destroy; begin if Assigned(vloFuncoes) then FreeAndNil(vloFuncoes); inherited; end; function TConfiguracao.fncCarregaDadosExistentes(psEmpresa: String) : TFDQuery; var FDConsulta : TFDQuery; begin vloFuncoes.pcdCriaFDQueryExecucao(FDConsulta, FConexao); Result := nil; FDConsulta.SQL.Clear; FDConsulta.SQL.Add('SELECT * FROM APURAIMPOSTOCONFIG WHERE CONFAI_EMPRESA = :EMPRESA'); FDConsulta.ParamByName('EMPRESA').AsString := psEmpresa; FDConsulta.Open; if not FDConsulta.IsEmpty then Result := FDConsulta; end; function TConfiguracao.fncRetornaTipoNF(psEmpresa: String) : TFDQuery; var FDConsulta : TFDQuery; begin vloFuncoes.pcdCriaFDQueryExecucao(FDConsulta, FConexao); Result := nil; FDConsulta.SQL.Clear; FDConsulta.SQL.Add('SELECT DISTINCT(UPPER(NF_TIPO)) AS NF_TIPO FROM NFISCAL WHERE NF_EMPRESA = :EMPRESA ORDER BY NF_TIPO'); FDConsulta.ParamByName('EMPRESA').AsString := psEmpresa; FDConsulta.Open; if not FDConsulta.IsEmpty then Result := FDConsulta; end; procedure TConfiguracao.pcdGravaConfiguracao; var FDConfig : TFDQuery; begin vloFuncoes.pcdCriaFDQueryExecucao(FDConfig, FConexao); try FDConfig.SQL.Clear; FDConfig.SQL.Add('SELECT * FROM APURAIMPOSTOCONFIG WHERE CONFAI_EMPRESA = :EMPRESA'); FDConfig.ParamByName('EMPRESA').AsString := FCONFAI_EMPRESA; FDConfig.Open; if FDConfig.IsEmpty then begin FDConfig.SQL.Clear; FDConfig.SQL.Add('INSERT INTO APURAIMPOSTOCONFIG (CONFAI_EMPRESA, CONFAI_TIPOSNF, CONFAI_ALIQPIS, CONFAI_ALIQCOFINS,'); FDConfig.SQL.Add(' CONFAI_ALIQIRPJ, CONFAI_ALIQCSLL, CONFAI_PRESIRPJ, CONFAI_PRESCSLL)'); FDConfig.SQL.Add('VALUES (:CONFAI_EMPRESA, :CONFAI_TIPOSNF, :CONFAI_ALIQPIS, :CONFAI_ALIQCOFINS,'); FDConfig.SQL.Add(' :CONFAI_ALIQIRPJ, :CONFAI_ALIQCSLL, :CONFAI_PRESIRPJ, :CONFAI_PRESCSLL);'); FDConfig.ParamByName('CONFAI_EMPRESA').AsString := FCONFAI_EMPRESA; FDConfig.ParamByName('CONFAI_TIPOSNF').AsString := FCONFAI_TIPOSNF; FDConfig.ParamByName('CONFAI_ALIQPIS').AsFloat := FCONFAI_ALIQPIS; FDConfig.ParamByName('CONFAI_ALIQCOFINS').AsFloat := FCONFAI_ALIQCOFINS; FDConfig.ParamByName('CONFAI_ALIQIRPJ').AsFloat := FCONFAI_ALIQIRPJ; FDConfig.ParamByName('CONFAI_ALIQCSLL').AsFloat := FCONFAI_ALIQCSLL; FDConfig.ParamByName('CONFAI_PRESIRPJ').AsFloat := FCONFAI_PRESIRPJ; FDConfig.ParamByName('CONFAI_PRESCSLL').AsFloat := FCONFAI_PRESCSLL; FDConfig.ExecSQL; vloFuncoes.fncLogOperacao(FCONFAI_EMPRESA, '', '', 'Configuração de Imposto Gravada com as opções: '+ 'Tipos: (' + Trim(Copy(FCONFAI_TIPOSNF, 1 , 90)) + ')'+ 'Aliq PIS: ' + FormatFloat(',0.00', FCONFAI_ALIQPIS) + 'Aliq COFINS: ' + FormatFloat(',0.00', FCONFAI_ALIQCOFINS) + 'Aliq IRPJ: ' + FormatFloat(',0.00', FCONFAI_ALIQIRPJ) + 'Aliq CSLL: ' + FormatFloat(',0.00', FCONFAI_ALIQCSLL) + 'Pres IRPJ: ' + FormatFloat(',0.00', FCONFAI_PRESIRPJ) + 'Pres CSLL: ' + FormatFloat(',0.00', FCONFAI_PRESCSLL), '', OrigemLOG_ApuraImposta); end else begin FDConfig.SQL.Clear; FDConfig.SQL.Add('UPDATE APURAIMPOSTOCONFIG'); FDConfig.SQL.Add('SET CONFAI_TIPOSNF = :CONFAI_TIPOSNF,'); FDConfig.SQL.Add(' CONFAI_ALIQPIS = :CONFAI_ALIQPIS,'); FDConfig.SQL.Add(' CONFAI_ALIQCOFINS = :CONFAI_ALIQCOFINS,'); FDConfig.SQL.Add(' CONFAI_ALIQIRPJ = :CONFAI_ALIQIRPJ,'); FDConfig.SQL.Add(' CONFAI_ALIQCSLL = :CONFAI_ALIQCSLL,'); FDConfig.SQL.Add(' CONFAI_PRESIRPJ = :CONFAI_PRESIRPJ,'); FDConfig.SQL.Add(' CONFAI_PRESCSLL = :CONFAI_PRESCSLL'); FDConfig.SQL.Add('WHERE (CONFAI_EMPRESA = :CONFAI_EMPRESA);'); FDConfig.ParamByName('CONFAI_EMPRESA').AsString := FCONFAI_EMPRESA; FDConfig.ParamByName('CONFAI_TIPOSNF').AsString := FCONFAI_TIPOSNF; FDConfig.ParamByName('CONFAI_ALIQPIS').AsFloat := FCONFAI_ALIQPIS; FDConfig.ParamByName('CONFAI_ALIQCOFINS').AsFloat := FCONFAI_ALIQCOFINS; FDConfig.ParamByName('CONFAI_ALIQIRPJ').AsFloat := FCONFAI_ALIQIRPJ; FDConfig.ParamByName('CONFAI_ALIQCSLL').AsFloat := FCONFAI_ALIQCSLL; FDConfig.ParamByName('CONFAI_PRESIRPJ').AsFloat := FCONFAI_PRESIRPJ; FDConfig.ParamByName('CONFAI_PRESCSLL').AsFloat := FCONFAI_PRESCSLL; FDConfig.ExecSQL; vloFuncoes.fncLogOperacao(FCONFAI_EMPRESA, '', '', 'Configuração de Imposto Alteradas com as opções: '+ 'Tipos: (' + Trim(Copy(FCONFAI_TIPOSNF, 1 , 90)) + ')'+ 'Aliq PIS: ' + FormatFloat(',0.00', FCONFAI_ALIQPIS) + 'Aliq COFINS: ' + FormatFloat(',0.00', FCONFAI_ALIQCOFINS) + 'Aliq IRPJ: ' + FormatFloat(',0.00', FCONFAI_ALIQIRPJ) + 'Aliq CSLL: ' + FormatFloat(',0.00', FCONFAI_ALIQCSLL) + 'Pres IRPJ: ' + FormatFloat(',0.00', FCONFAI_PRESIRPJ) + 'Pres CSLL: ' + FormatFloat(',0.00', FCONFAI_PRESCSLL), '', OrigemLOG_ApuraImposta); end; finally FreeAndNil(FDConfig); end; end; procedure TConfiguracao.SetCONFAI_ALIQCOFINS(const Value: Double); begin FCONFAI_ALIQCOFINS := Value; end; procedure TConfiguracao.SetCONFAI_ALIQCSLL(const Value: Double); begin FCONFAI_ALIQCSLL := Value; end; procedure TConfiguracao.SetCONFAI_ALIQIRPJ(const Value: Double); begin FCONFAI_ALIQIRPJ := Value; end; procedure TConfiguracao.SetCONFAI_ALIQPIS(const Value: Double); begin FCONFAI_ALIQPIS := Value; end; procedure TConfiguracao.SetCONFAI_EMPRESA(const Value: String); begin FCONFAI_EMPRESA := Value; end; procedure TConfiguracao.SetCONFAI_PRESCSLL(const Value: Double); begin FCONFAI_PRESCSLL := Value; end; procedure TConfiguracao.SetCONFAI_PRESIRPJ(const Value: Double); begin FCONFAI_PRESIRPJ := Value; end; procedure TConfiguracao.SetCONFAI_TIPOSNF(const Value: String); begin FCONFAI_TIPOSNF := Value; end; end.
unit iOSapi.AVFoundation.Helper; interface uses iOSapi.Foundation, iOSapi.AVFoundation; function AVEncoderAudioQualityKey: NSString; function AVAudioSessionCategoryPlayAndRecord: NSString; implementation function AVEncoderAudioQualityKey: NSString; begin Result := CocoaNSStringConst(libAVFoundation, 'AVEncoderAudioQualityKey'); end; function AVAudioSessionCategoryPlayAndRecord: NSString; begin result := CocoaNSStringConst( libAVFoundation, 'AVAudioSessionCategoryPlayAndRecord' ); end; end.
unit uXPMenu; interface uses SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, Qt, uGraphics, iniFiles, QExtCtrls, uCommon, uXPImageList; type TXPMenuItems=class; TXPMenuItem=class(TObject) private FCaption: string; FItems: TXPMenuItems; FImageIndex: integer; FPath: string; FIsFolder: boolean; FItemIndex: integer; procedure SetCaption(const Value: string); procedure SetImageIndex(const Value: integer); procedure SetPath(const Value: string); procedure SetIsFolder(const Value: boolean); procedure SetItemIndex(const Value: integer); public constructor Create;virtual; destructor Destroy;override; property Caption: string read FCaption write SetCaption; property ImageIndex: integer read FImageIndex write SetImageIndex; property Items: TXPMenuItems read FItems; property ItemIndex: integer read FItemIndex write SetItemIndex; property Path: string read FPath write SetPath; property IsFolder: boolean read FIsFolder write SetIsFolder; end; TXPMenuItems=class(TList) private FImageList: TXPImageList; FInUpdate:boolean; FOnItemsChanged: TNotifyEvent; FItemsDirectory: string; procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure SetOnItemsChanged(const Value: TNotifyEvent); procedure SetItemsDirectory(const Value: string); procedure populateItems; public procedure beginupdate; procedure endupdate; function additem(const caption:string;const ImageIndex:integer=-1): TXPMenuItem; constructor Create;virtual; destructor Destroy;override; property OnItemsChanged: TNotifyEvent read FOnItemsChanged write SetOnItemsChanged; property ItemsDirectory: string read FItemsDirectory write SetItemsDirectory; end; TXPMenu = class(TForm) procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormShow(Sender: TObject); private FTextOffset: integer; FBackBitmap: TBitmap; FItems: TXPMenuItems; FItemHeight: integer; FBackground: TBitmap; FChild: TXPMenu; FSelectedItem: TXPMenuItem; FTimer: TTimer; FCloseTimer: TTimer; FDelayedPath: string; allowshowmenu:boolean; procedure paintItem(const itemindex:integer); procedure SetItemHeight(const Value: integer); procedure ItemsChanged(sender:TObject); procedure SetDirectory(const Value: string); function getDirectory: string; procedure createChild; procedure SetSelectedItem(const Value: TXPMenuItem); procedure OnShowTimer(sender:TObject); procedure OnCloseTimer(sender:TObject); { Private declarations } public { Public declarations } procedure MouseMove(Shift: TShiftState; X, Y: Integer);override; procedure mouseenter(AControl:TControl);override; procedure mouseleave(AControl:TControl);override; function itemAtPos(const pt: TPoint):TXPMenuItem; procedure showmenu; procedure hidemenu; procedure popup(const x,y:integer;const inmediate:boolean=true;const delayedpath:string=''); procedure closepopup(const inmediate:boolean=true); constructor Create(AOwner:TComponent);override; destructor Destroy;override; property Items:TXPMenuItems read FItems; property ItemHeight: integer read FItemHeight write SetItemHeight; property SelectedItem: TXPMenuItem read FSelectedItem write SetSelectedItem; property Directory: string read getDirectory write SetDirectory; end; var XPMenu: TXPMenu; implementation uses uWindowManager, uXPStartMenu; {$R *.xfm} { TXPMenuItem } constructor TXPMenuItem.Create; begin inherited; FItemIndex:=-1; FIsFolder:=false; FPath:=''; FItems:=TXPMenuItems.create; FImageIndex:=-1; end; destructor TXPMenuItem.Destroy; begin FItems.free; inherited; end; procedure TXPMenuItem.SetCaption(const Value: string); begin FCaption := Value; end; procedure TXPMenuItem.SetImageIndex(const Value: integer); begin FImageIndex := Value; end; procedure TXPMenuItem.SetIsFolder(const Value: boolean); begin FIsFolder := Value; end; procedure TXPMenuItem.SetItemIndex(const Value: integer); begin FItemIndex := Value; end; procedure TXPMenuItem.SetPath(const Value: string); begin FPath := Value; end; { TXPMenu } constructor TXPMenu.Create(AOwner: TComponent); begin inherited; FDelayedPath:=''; FTimer:=TTimer.create(nil); FTimer.enabled:=false; FTimer.Interval:=500; FCloseTimer:=TTimer.create(nil); FCloseTimer.enabled:=false; FCloseTimer.Interval:=500; FTimer.OnTimer:=OnShowTimer; FCloseTimer.OnTimer:=OnCloseTimer; FTextOffset:=0; FBackBitmap:=TBitmap.create; FChild:=nil; FSelectedItem:=nil; FBackground:=TBitmap.create; FItems:=TXPMenuItems.create; FItems.OnItemsChanged:=ItemsChanged; FItemHeight:=24; FBackground.LoadFromFile(getSystemInfo(XP_START_MENU_THEME_DIR)+'/startmenu_options_background.png'); ResizeBitmap(FBackground,Bitmap,Width,height,4); end; destructor TXPMenu.Destroy; begin FBackBitmap.free; FBackground.free; FItems.free; if (assigned(FChild)) then FChild.free; inherited; end; function TXPMenu.getDirectory: string; begin result:=FItems.ItemsDirectory; end; procedure TXPMenu.ItemsChanged(sender: TObject); var new_width: integer; i: integer; item: TXPMenuItem; toadd: integer; begin if (not (csDestroying in ComponentState)) then begin FTextOffset:=6; new_width:=50; for i:=0 to FItems.count-1 do begin toadd:=0; item:=FItems[I]; //If it's a folder if (item.isfolder) then begin toadd:=24; end; if (item.imageindex<>-1) then begin toadd:=toadd+24; FTextOffset:=30; end; new_width:=max(new_width,bitmap.canvas.TextWidth(item.Caption)+16+FTextOffset+toadd); end; width:=new_width; height:=FItemHeight*FItems.Count; ResizeBitmap(FBackground,Bitmap,Width,height,4); fbackbitmap.assign(bitmap); bitmap.Canvas.Font.Color:=clWhite; for i:=0 to FItems.count-1 do begin paintItem(i); end; end; end; procedure TXPMenu.popup(const x, y: integer;const inmediate:boolean=true;const delayedpath:string=''); begin left:=x; top:=y; if (inmediate) then showmenu else begin allowshowmenu:=false; FTimer.Enabled:=false; FDelayedPath:=delayedpath; FCloseTimer.Enabled:=false; FTimer.Enabled:=true; end; end; procedure TXPMenu.SetDirectory(const Value: string); begin FItems.ItemsDirectory:=value; end; procedure TXPMenu.SetItemHeight(const Value: integer); begin FItemHeight := Value; end; function TXPMenu.itemAtPos(const pt: TPoint): TXPMenuItem; var it_index: integer; begin result:=nil; it_index:=pt.y div FItemHeight; if (it_index>=0) and (it_index<FItems.count) then result:=FItems[it_index]; end; procedure TXPMenu.createChild; begin if not (assigned(FChild)) then begin FChild:=TXPMenu.create(nil); end; end; procedure TXPMenu.SetSelectedItem(const Value: TXPMenuItem); var oldindex: integer; begin if (value<>FSelectedItem) then begin oldindex:=-1; if assigned(FSelectedItem) then begin oldindex:=FSelectedItem.ItemIndex; end; FSelectedItem := Value; if (oldindex<>-1) then begin paintItem(oldindex); end; if assigned(FSelectedItem) then begin paintItem(FSelectedItem.itemindex); end; end; end; procedure TXPMenu.paintItem(const itemindex:integer); var y:integer; item: TXPMenuItem; d:integer; cRect: TRect; begin //Draw here the bitmap y:=itemindex*FItemHeight; FItems.FImageList.Background:=fbackbitmap; item:=FItems[itemindex]; cRect:=Rect(2,y+2,width-2,y+FItemHeight-2); if (item=FSelectedItem) then begin bitmap.Canvas.Brush.Color:=clHighLight; bitmap.Canvas.pen.Color:=clHighLight; bitmap.canvas.Rectangle(cRect); FItems.FImageList.Background:=bitmap; end else begin bitmap.Canvas.CopyRect(cRect,fbackbitmap.canvas,cRect); end; d:=(fitemheight-bitmap.Canvas.textheight(item.caption)) div 2; bitmap.Canvas.TextOut(FTextOffset,y+d,item.caption); if (item.ImageIndex<>-1) then begin FItems.FImageList.Draw(bitmap.canvas,8,y+4,item.ImageIndex,false,0,false); if (item.isFolder) then begin FItems.FImageList.Draw(bitmap.canvas,width-12,y+8,item.imageindex+1,false,0,false); end; end; end; procedure TXPMenu.OnShowTimer(sender: TObject); begin allowshowmenu:=true; FTimer.enabled:=false; Directory:=FDelayedPath; if (top+height) > screen.height then top:=screen.height-height; if (allowshowmenu) then showmenu; end; procedure TXPMenu.showmenu; begin if (not visible) then begin SelectedItem:=nil; ItemsChanged(nil); show; end; end; procedure TXPMenu.hidemenu; begin if (assigned(FChild)) then FChild.closepopup(true); FTimer.enabled:=false; FCloseTimer.enabled:=false; hide; end; procedure TXPMenu.closepopup(const inmediate: boolean); begin if (inmediate) then hidemenu else begin FTimer.enabled:=false; FCloseTimer.enabled:=true; end; end; procedure TXPMenu.OnCloseTimer(sender: TObject); begin hidemenu; FCloseTimer.enabled:=false; end; procedure TXPMenu.mouseenter(AControl: TControl); begin inherited; end; procedure TXPMenu.mouseleave(AControl: TControl); begin inherited; end; procedure TXPMenu.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; end; { TXPMenuItems } function TXPMenuItems.additem(const caption: string; const ImageIndex: integer=-1): TXPMenuItem; begin result:=TXPMenuItem.create; result.caption:=caption; result.imageindex:=imageindex; result.ItemIndex:=add(result); end; procedure TXPMenuItems.beginupdate; begin FInUpdate:=true; end; constructor TXPMenuItems.Create; begin inherited; FImageList:=TXPImageList.create(nil); FImageList.DefaultSystemDir:=XP_SMALL_SIZE_ICON_DIR; FImageList.add('programs_folder.png'); FImageList.add('menu_subitems.png'); FItemsDirectory:=''; FOnItemsChanged:=nil; FInUpdate:=false; end; destructor TXPMenuItems.Destroy; begin FImageList.free; inherited; end; procedure TXPMenuItems.endupdate; begin FInUpdate:=false; if assigned(FOnItemsChanged) then FOnItemsChanged(self); end; procedure TXPMenuItems.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; if (assigned(FOnItemsChanged) and (not FInUpdate)) then FOnItemsChanged(self); end; procedure TXPMenuItems.populateItems; var searchRec: TSearchRec; item: TXPMenuItem; ini: TIniFile; image: string; files: TStringList; folders: TStringList; i: integer; path: string; begin if (FItemsDirectory<>'') then begin if (DirectoryExists(FItemsDirectory)) then begin Clear; beginupdate; files:=TStringList.create; files.sorted:=true; folders:=TStringList.create; folders.Sorted:=true; try if FindFirst(IncludeTrailingPathDelimiter(FItemsDirectory) + '*', faAnyFile, SearchRec) = 0 then begin { TODO : Sort items alphabetically } repeat if ((SearchRec.Name <> '..') and (SearchRec.Name <> '.')) then begin { TODO : Process .lnk files to get caption and icon } { TODO : Sort these items alphabetically } { TODO : Get the real item caption } if ((searchRec.Attr and faDirectory)=faDirectory) then begin folders.add(searchrec.PathOnly+searchrec.name); end else begin files.add(searchrec.PathOnly+searchrec.name); end; end; application.processmessages; until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; if (files.count=0) and (folders.count=0) then begin clear; additem('(empty)'); end else begin for i:=0 to folders.count-1 do begin path:=folders[i]; item:=additem(extractfilename(changefileext(path,''))); item.Path:=path; item.isfolder:=true; item.imageindex:=0; end; for i:=0 to files.count-1 do begin path:=files[i]; item:=additem(extractfilename(changefileext(path,''))); if (ansilowercase(ExtractFileExt(path))='.lnk') then begin ini:=TIniFile.create(path); try image:=ini.ReadString('Shortcut','Icon',''); if (image<>'') then item.imageindex:=FImageList.Add(image); finally ini.free; end; end; item.Path:=path; item.isfolder:=false; end; end; finally folders.free; files.free; endupdate; end; end; end; end; procedure TXPMenuItems.SetItemsDirectory(const Value: string); begin if (FItemsDirectory<>Value) then begin FItemsDirectory := Value; populateItems; end; end; procedure TXPMenuItems.SetOnItemsChanged(const Value: TNotifyEvent); begin FOnItemsChanged := Value; end; procedure TXPMenu.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var item: TXPMenuItem; pt: TPoint; begin FCloseTimer.enabled:=false; pt:=point(x,y); item:=itematpos(pt); selecteditem:=item; pt.y:=(pt.Y div fitemheight)*fitemheight; pt.x:=width; pt:=ClientToScreen(pt); if (assigned(item)) then begin if (item.IsFolder) then begin createChild; FChild.FSelectedItem:=nil; FChild.Directory:=item.Path; if (pt.y+fchild.height) > screen.height then pt.y:=screen.height-fchild.height; FChild.popup(pt.x,pt.y,true); end else begin ShellExecute(item.Path); getstartmenu.close; end; end; end; procedure TXPMenu.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var pt: TPoint; old_sel: TXPMenuItem; begin FCloseTimer.enabled:=false; pt:=point(x,y); old_sel:=selecteditem; selecteditem:=itematpos(pt); pt.y:=(pt.Y div fitemheight)*fitemheight; pt.x:=width; pt:=ClientToScreen(pt); if (selecteditem<>old_sel) then begin if (assigned(FChild)) then begin FChild.closepopup(true); FChild.FTimer.Enabled:=false; FChild.FCloseTimer.Enabled:=false; end; end; if (assigned(selecteditem)) then begin if (selecteditem.isFolder) then begin createChild; FChild.FSelectedItem:=nil; if (selecteditem<>old_sel) then begin FChild.closepopup(true); FChild.popup(pt.x,pt.y, false, selecteditem.path); end; end else begin //Do nothing end; end; end; procedure TXPMenu.FormShow(Sender: TObject); begin { TODO : Fix this and find the right handle to bypass } XPWindowManager.bypasswindow(qwidget_winid(self.handle)-1); end; end.
unit GetAllConfigValuesUnit; interface uses SysUtils, BaseExampleUnit, EnumsUnit; type TGetAllConfigValues = class(TBaseExample) public procedure Execute; end; implementation uses CommonTypesUnit; procedure TGetAllConfigValues.Execute; var ErrorString: String; Values: TListStringPair; i: Integer; begin Values := Route4MeManager.User.GetAllConfigValues(ErrorString); try WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('GetAllConfigValues successfully.'); for i := 0 to Values.Count - 1 do WriteLn(Format('Key="%s", Value="%s"', [Values[i].Key, Values[i].Value])); WriteLn(''); end else WriteLn(Format('GetAllConfigValues error: "%s"', [ErrorString])); finally FreeAndNil(Values); end; end; end.
unit PaymentSourcesForma; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GridForma, ToolCtrlsEh, DBGridEhToolCtrls, Data.DB, FIBDataSet, System.UITypes, pFIBDataSet, CnErrorProvider, Vcl.Menus, System.Actions, Vcl.ActnList, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ToolWin, GridsEh, DBAxisGridsEh, DBGridEh, PrjConst, Vcl.Mask, DBCtrlsEh, EhLibVCL, DBGridEhGrouping, DynVarsEh; type TPaymentSourcesForm = class(TGridForm) dsPaymentSource: TpFIBDataSet; lbl2: TLabel; lbl3: TLabel; edtName: TDBEditEh; edtLEAK_PRC: TDBNumberEditEh; edtTAX_PRC: TDBNumberEditEh; edtCODE: TDBEditEh; Label1: TLabel; Label2: TLabel; procedure FormShow(Sender: TObject); procedure dsPaymentSourceNewRecord(DataSet: TDataSet); procedure actNewExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure btnSaveLinkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure srcDataSourceDataChange(Sender: TObject; Field: TField); private { Private declarations } public { Public declarations } end; var PaymentSourcesForm: TPaymentSourcesForm; implementation uses DM; {$R *.dfm} procedure TPaymentSourcesForm.FormShow(Sender: TObject); begin inherited; FCanEdit := (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_PaySources)); FCanCreate := (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_PaySources)); dsPaymentSource.Open; // права пользователей actNew.Visible := FCanCreate; actDelete.Visible := FCanEdit; actEdit.Visible := FCanEdit; end; procedure TPaymentSourcesForm.dsPaymentSourceNewRecord(DataSet: TDataSet); begin inherited; DataSet['LEAK_PRC'] := 0; DataSet['TAX_PRC'] := 0; end; procedure TPaymentSourcesForm.actNewExecute(Sender: TObject); begin inherited; if FCanEdit then StartEdit(True); end; procedure TPaymentSourcesForm.actEditExecute(Sender: TObject); begin inherited; if FCanEdit then StartEdit(False); end; procedure TPaymentSourcesForm.actDeleteExecute(Sender: TObject); begin inherited; if FCanEdit then if (MessageDlg( Format(rsDeleteWithName, [srcDataSource.DataSet['PAYSOURCE_DESCR']]), mtConfirmation, [mbYes, mbNo], 0) = mrYes) then srcDataSource.DataSet.Delete; end; procedure TPaymentSourcesForm.btnSaveLinkClick(Sender: TObject); var errors: Boolean; begin errors := False; if (edtName.Text = '') then begin errors := True; CnErrors.SetError(edtName, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtName); if (edtLEAK_PRC.Text = '') then begin errors := True; CnErrors.SetError(edtLEAK_PRC, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtLEAK_PRC); if (edtTAX_PRC.Text = '') then begin errors := True; CnErrors.SetError(edtTAX_PRC, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtTAX_PRC); if not errors then inherited; end; procedure TPaymentSourcesForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; dsPaymentSource.Close; PaymentSourcesForm := nil; end; procedure TPaymentSourcesForm.srcDataSourceDataChange(Sender: TObject; Field: TField); begin inherited; actEdit.Enabled := ((Sender as TDataSource).DataSet.RecordCount > 0) and fCanEdit; actDelete.Enabled := ((Sender as TDataSource).DataSet.RecordCount > 0) and fCanEdit; end; end.
unit SearchInterfaces; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Search\SearchInterfaces.pas" // Стереотип: "ControllerInterfaces" // Элемент модели: "SearchInterfaces" MUID: (491DAF4202EE) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , BaseTypesUnit , DynamicDocListUnit , DynamicTreeUnit , SearchUnit , l3Interfaces , l3TreeInterfaces {$If NOT Defined(NoVCM)} , vcmInterfaces {$IfEnd} // NOT Defined(NoVCM) , TreeInterfaces , SimpleListInterfaces , SearchDomainInterfaces , l3InternalInterfaces {$If NOT Defined(NoVCM)} , vcmControllers {$IfEnd} // NOT Defined(NoVCM) ; (* CurrentChangedListener = interface {* Слушатель изменения текущей ноды } procedure Process(const aNode: Il3SimpleNode); {* обработать событие } end;//CurrentChangedListener *) type IbsCurrentChangedListener = interface(Il3Notify) {* Слушатель события смены текущего в дереве } ['{DFE81B68-ECAE-4E53-A037-41657C8FA8E9}'] procedure Process(const aNode: Il3SimpleNode); {* обработать событие } end;//IbsCurrentChangedListener IdeSearch = interface ['{D976EB3D-D8B6-4FBB-82D1-7FEAD44D0BDC}'] function pm_GetTag: Il3CString; function pm_GetQuery: IQuery; property Tag: Il3CString read pm_GetTag; property Query: IQuery read pm_GetQuery; end;//IdeSearch (* SelectedAttributes = interface {* Выделенные атрибуты } procedure UpdateSelectedAttributes; {* обновить данные в форме выбранных атрибутов } end;//SelectedAttributes *) IdsTagSimpleTree = interface(IdsSimpleTree) {* Интерфейс бизнес объекта для словарных атрибутов } ['{1D3A604E-72E8-400E-B9A1-1F7FBB2D791A}'] function pm_GetSearch: IdeSearch; function pm_GetOperations: TLogicOperationSet; function pm_GetIsOneOperation: Boolean; property Search: IdeSearch read pm_GetSearch; {* таг дерева реквизитов } property Operations: TLogicOperationSet read pm_GetOperations; {* доступные операции для словарного атрибута } property IsOneOperation: Boolean read pm_GetIsOneOperation; {* доступна только одна операция } end;//IdsTagSimpleTree InsProgressIndicator = interface ['{E143834D-F9AB-4E19-BE38-295974997825}'] procedure StartProcess(const aProgressIndicator: IvcmEntity); procedure StopProcess; function Execute(const aCaption: Il3CString; out aSearchEntity: ISearchEntity): Boolean; end;//InsProgressIndicator InsSelectedAttributesIterators = interface ['{DD41838B-4B9B-4AC7-AF96-1C62DD92BE75}'] function Get_OrIterator: INodeIterator; function Get_AndIterator: INodeIterator; function Get_NotIterator: INodeIterator; property OrIterator: INodeIterator read Get_OrIterator; property AndIterator: INodeIterator read Get_AndIterator; property NotIterator: INodeIterator read Get_NotIterator; end;//InsSelectedAttributesIterators IbsSelectedAttributes = interface {* Выделенные атрибуты } ['{02D0B494-46D1-4BF3-B0E6-8076D6E07E08}'] procedure UpdateSelectedAttributes; {* обновить данные в форме выбранных атрибутов } end;//IbsSelectedAttributes IdsSituation = interface(IdsTagSimpleTree) {* "Ситуация" } ['{ACBD2B86-E114-4DB8-A546-F4BBC4589AF4}'] function As_IbsCurrentChangedListener: IbsCurrentChangedListener; {* Метод приведения нашего интерфейса к IbsCurrentChangedListener } end;//IdsSituation IdsAttributeSelect = interface(IvcmViewAreaController) {* бизнес объект формы cfAttributeSelect } ['{47345B7D-E460-4710-BF6E-E471D35F2F1B}'] function pm_GetSearch: IdeSearch; property Search: IdeSearch read pm_GetSearch; {* таг дерева реквизитов } end;//IdsAttributeSelect IdsTreeAttributeSelect = interface(IdsSituation) {* Бизнес объекта формы "enTreeAttributeSelectForm" } ['{40B0AB8A-4B02-4E72-BCA4-85F85A5DEC14}'] function pm_GetRefreshValues: InsSelectedAttributesIterators; procedure UpdateSelectedAttributes; {* обновить данные в форме выбранных атрибутов } property RefreshValues: InsSelectedAttributesIterators read pm_GetRefreshValues; {* данные необходимые для обновления формы выбранных атрибутов } end;//IdsTreeAttributeSelect IdsSelectedAttributes = interface(IdsTagSimpleTree) ['{BEFD0C90-5EC9-4847-94E2-C98BA4754E58}'] function pm_GetRefreshValues: InsSelectedAttributesIterators; property RefreshValues: InsSelectedAttributesIterators read pm_GetRefreshValues; {* данные для формы } end;//IdsSelectedAttributes IdeSelectedAttributes = interface(IdeSearch) ['{D77AAF2E-A5BF-4AD4-AEB7-E288C11E1782}'] function Get_RefreshValues: InsSelectedAttributesIterators; property RefreshValues: InsSelectedAttributesIterators read Get_RefreshValues; end;//IdeSelectedAttributes implementation uses l3ImplUses ; end.
unit Compile; { Inno Setup Copyright (C) 1997-2012 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Compiler } {x$DEFINE STATICPREPROC} { For debugging purposes, remove the 'x' to have it link the ISPP code into this program and not depend on ISPP.dll. Most useful when combined with CompForm's STATICCOMPILER. Note: the ISPP source doesn't support Delphi 3 which is normally used for the ANSI compiler, and the IS source code doesn't support Delphi 7 which is normally used for ANSI ISPP. So use Unicode. } {$I VERSION.INC} interface uses Windows, SysUtils, CompInt; function ISCompileScript(const Params: TCompileScriptParamsEx; const PropagateExceptions: Boolean): Integer; function ISGetVersion: PCompilerVersionInfo; type EISCompileError = class(Exception); implementation uses CompPreprocInt, Commctrl, {$IFDEF IS_DXE}VCL.Consts{$ELSE}Consts{$ENDIF}, Classes, IniFiles, TypInfo, PathFunc, CmnFunc2, Struct, Int64Em, CompMsgs, SetupEnt, FileClass, Compress, CompressZlib, bzlib, LZMA, ArcFour, SHA1, MsgIDs, DebugStruct, VerInfo, ResUpdate, CompResUpdate, {$IFDEF STATICPREPROC} IsppPreprocess, {$ENDIF} ScriptCompiler, SimpleExpression, SetupTypes; type TParamInfo = record Name: String; Flags: set of (piRequired, piNoEmpty, piNoQuotes); end; TParamValue = record Found: Boolean; Data: String; end; TEnumIniSectionProc = procedure(const Line: PChar; const Ext: Integer) of object; TSetupSectionDirectives = ( ssAllowCancelDuringInstall, ssAllowNetworkDrive, ssAllowNoIcons, ssAllowRootDirectory, ssAllowUNCPath, ssAlwaysRestart, ssAlwaysShowComponentsList, ssAlwaysShowDirOnReadyPage, ssAlwaysShowGroupOnReadyPage, ssAlwaysUsePersonalGroup, ssAppCopyright, ssAppendDefaultDirName, ssAppendDefaultGroupName, ssAppComments, ssAppContact, ssAppId, ssAppModifyPath, ssAppMutex, ssAppName, ssAppPublisher, ssAppPublisherURL, ssAppReadmeFile, ssAppSupportPhone, ssAppSupportURL, ssAppUpdatesURL, ssAppVerName, ssAppVersion, ssArchitecturesAllowed, ssArchitecturesInstallIn64BitMode, ssBackColor, ssBackColor2, ssBackColorDirection, ssBackSolid, ssChangesAssociations, ssChangesEnvironment, ssCloseApplications, ssCloseApplicationsFilter, ssCompression, ssCompressionThreads, ssCreateAppDir, ssCreateUninstallRegKey, ssDefaultDialogFontName, ssDefaultDirName, ssDefaultGroupName, ssDefaultUserInfoName, ssDefaultUserInfoOrg, ssDefaultUserInfoSerial, ssDirExistsWarning, ssDisableDirPage, ssDisableFinishedPage, ssDisableProgramGroupPage, ssDisableReadyMemo, ssDisableReadyPage, ssDisableStartupPrompt, ssDisableWelcomePage, ssDiskClusterSize, ssDiskSliceSize, ssDiskSpanning, ssDontMergeDuplicateFiles, ssEnableDirDoesntExistWarning, ssEncryption, ssExtraDiskSpaceRequired, ssFlatComponentsList, ssInfoAfterFile, ssInfoBeforeFile, ssInternalCompressLevel, ssLanguageDetectionMethod, ssLicenseFile, ssLZMAAlgorithm, ssLZMABlockSize, ssLZMADictionarySize, ssLZMAMatchFinder, ssLZMANumBlockThreads, ssLZMANumFastBytes, ssLZMAUseSeparateProcess, ssMergeDuplicateFiles, ssMessagesFile, ssMinVersion, ssOnlyBelowVersion, ssOutputBaseFilename, ssOutputDir, ssOutputManifestFile, ssPassword, ssPrivilegesRequired, ssReserveBytes, ssRestartApplications, ssRestartIfNeededByRun, ssSetupIconFile, ssSetupLogging, ssShowComponentSizes, ssShowLanguageDialog, ssShowTasksTreeLines, ssShowUndisplayableLanguages, ssSignedUninstaller, ssSignedUninstallerDir, ssSignTool, ssSlicesPerDisk, ssSolidCompression, ssSourceDir, ssTerminalServicesAware, ssTimeStampRounding, ssTimeStampsInUTC, ssTouchDate, ssTouchTime, ssUpdateUninstallLogAppName, ssUninstallable, ssUninstallDisplayIcon, ssUninstallDisplayName, ssUninstallDisplaySize, ssUninstallFilesDir, ssUninstallIconFile, ssUninstallLogMode, ssUninstallRestartComputer, ssUninstallStyle, ssUsePreviousAppDir, ssUsePreviousGroup, ssUsePreviousLanguage, ssUsePreviousSetupType, ssUsePreviousTasks, ssUsePreviousUserInfo, ssUseSetupLdr, ssUserInfoPage, ssVersionInfoCompany, ssVersionInfoCopyright, ssVersionInfoDescription, ssVersionInfoProductName, ssVersionInfoProductVersion, ssVersionInfoProductTextVersion, ssVersionInfoTextVersion, ssVersionInfoVersion, ssWindowResizable, ssWindowShowCaption, ssWindowStartMaximized, ssWindowVisible, ssWizardImageBackColor, ssWizardImageFile, ssWizardImageStretch, ssWizardSmallImageBackColor, ssWizardSmallImageFile, ssWizardStyle); TLangOptionsSectionDirectives = ( lsCopyrightFontName, lsCopyrightFontSize, lsDialogFontName, lsDialogFontSize, lsDialogFontStandardHeight, lsLanguageCodePage, lsLanguageID, lsLanguageName, lsRightToLeft, lsTitleFontName, lsTitleFontSize, lsWelcomeFontName, lsWelcomeFontSize); TAllowedConst = (acOldData, acBreak); TAllowedConsts = set of TAllowedConst; TLineInfo = class public FileName: String; FileLineNumber: Integer; end; {$IFDEF UNICODE} TPreLangData = class public Name: String; LanguageCodePage: Integer; end; {$ENDIF} TLangData = class public MessagesDefined: array[TSetupMessageID] of Boolean; Messages: array[TSetupMessageID] of String; end; TSignTool = class Name, Command: String; end; TNameAndAccessMask = record Name: String; Mask: DWORD; end; TLowFragList = class(TList) protected procedure Grow; override; end; TLowFragStringList = class private FInternalList: TLowFragList; function Get(Index: Integer): String; function GetCount: Integer; procedure Put(Index: Integer; const Value: String); public constructor Create; destructor Destroy; override; function Add(const S: String): Integer; procedure Clear; property Count: Integer read GetCount; property Strings[Index: Integer]: String read Get write Put; default; end; THashStringItem = record Hash: Longint; Str: String; end; PHashStringItemList = ^THashStringItemList; THashStringItemList = array[0..MaxListSize-1] of THashStringItem; THashStringList = class private FCapacity: Integer; FCount: Integer; FList: PHashStringItemList; procedure Grow; public destructor Destroy; override; function Add(const S: String): Integer; function CaseInsensitiveIndexOf(const S: String): Integer; procedure Clear; function Get(Index: Integer): String; property Count: Integer read FCount; property Strings[Index: Integer]: String read Get; default; end; PScriptFileLine = ^TScriptFileLine; TScriptFileLine = record LineFilename: String; LineNumber: Integer; LineText: String; end; TScriptFileLines = class private FLines: TLowFragList; function Get(Index: Integer): PScriptFileLine; function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Add(const LineFilename: String; const LineNumber: Integer; const LineText: String); property Count: Integer read GetCount; property Lines[Index: Integer]: PScriptFileLine read Get; default; end; TCheckOrInstallKind = (cikCheck, cikDirectiveCheck, cikInstall); TSetupCompiler = class private ScriptFiles: TStringList; PreprocOptionsString: String; PreprocCleanupProc: TPreprocCleanupProc; PreprocCleanupProcData: Pointer; LanguageEntries, CustomMessageEntries, PermissionEntries, TypeEntries, ComponentEntries, TaskEntries, DirEntries, FileEntries, FileLocationEntries, IconEntries, IniEntries, RegistryEntries, InstallDeleteEntries, UninstallDeleteEntries, RunEntries, UninstallRunEntries: TList; FileLocationEntryFilenames: THashStringList; WarningsList: TLowFragStringList; ExpectedCustomMessageNames: TStringList; DefaultLangData: TLangData; {$IFDEF UNICODE} PreLangDataList, {$ENDIF} LangDataList: TList; SignToolList: TList; SignTool, SignToolParams: String; OutputDir, OutputBaseFilename, OutputManifestFile, SignedUninstallerDir, ExeFilename: String; FixedOutputDir, FixedOutputBaseFilename: Boolean; CompressMethod: TSetupCompressMethod; InternalCompressLevel, CompressLevel: Integer; InternalCompressProps, CompressProps: TLZMACompressorProps; UseSolidCompression: Boolean; DontMergeDuplicateFiles: Boolean; CryptKey: String; TimeStampsInUTC: Boolean; TimeStampRounding: Integer; TouchDateOption: (tdCurrent, tdNone, tdExplicit); TouchDateYear, TouchDateMonth, TouchDateDay: Integer; TouchTimeOption: (ttCurrent, ttNone, ttExplicit); TouchTimeHour, TouchTimeMinute, TouchTimeSecond: Integer; SetupHeader: TSetupHeader; SetupDirectiveLines: array[TSetupSectionDirectives] of Integer; UseSetupLdr, DiskSpanning, BackSolid, TerminalServicesAware: Boolean; DiskSliceSize, DiskClusterSize, SlicesPerDisk, ReserveBytes: Longint; LicenseFile, InfoBeforeFile, InfoAfterFile, WizardImageFile: String; WizardSmallImageFile: String; DefaultDialogFontName: String; VersionInfoVersion, VersionInfoProductVersion: TFileVersionNumbers; VersionInfoVersionOriginalValue, VersionInfoCompany, VersionInfoCopyright, VersionInfoDescription, VersionInfoTextVersion, VersionInfoProductName, VersionInfoProductTextVersion, VersionInfoProductVersionOriginalValue: String; SetupIconFilename: String; CodeText: TStringList; CodeCompiler: TScriptCompiler; CompiledCodeText: AnsiString; CompileWasAlreadyCalled: Boolean; LineFilename: String; LineNumber: Integer; DebugInfo, CodeDebugInfo: TMemoryStream; DebugEntryCount, VariableDebugEntryCount: Integer; CompiledCodeTextLength, CompiledCodeDebugInfoLength: Integer; TotalBytesToCompress, BytesCompressedSoFar: Integer64; CompressionInProgress: Boolean; CompressionStartTick: DWORD; CachedUserDocsDir: String; procedure AddStatus(const S: String); procedure AddStatusFmt(const Msg: String; const Args: array of const); procedure AbortCompile(const Msg: String); procedure AbortCompileFmt(const Msg: String; const Args: array of const); procedure AbortCompileOnLine(const Msg: String); procedure AbortCompileOnLineFmt(const Msg: String; const Args: array of const); procedure AbortCompileParamError(const Msg, ParamName: String); function PrependDirName(const Filename, Dir: String): String; function PrependSourceDirName(const Filename: String): String; procedure CallIdleProc; procedure DoCallback(const Code: Integer; var Data: TCompilerCallbackData); procedure EnumIniSection(const EnumProc: TEnumIniSectionProc; const SectionName: String; const Ext: Integer; const Verbose, SkipBlankLines: Boolean; const Filename: String; const AnsiLanguageFile, Pre: Boolean); function EvalCheckOrInstallIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; procedure CheckCheckOrInstall(const ParamName, ParamData: String; const Kind: TCheckOrInstallKind); function CheckConst(const S: String; const MinVersion: TSetupVersionData; const AllowedConsts: TAllowedConsts): Boolean; procedure CheckCustomMessageDefinitions; procedure CheckCustomMessageReferences; procedure EnumTypes(const Line: PChar; const Ext: Integer); procedure EnumComponents(const Line: PChar; const Ext: Integer); procedure EnumTasks(const Line: PChar; const Ext: Integer); procedure EnumDirs(const Line: PChar; const Ext: Integer); procedure EnumIcons(const Line: PChar; const Ext: Integer); procedure EnumINI(const Line: PChar; const Ext: Integer); {$IFDEF UNICODE} procedure EnumLangOptionsPre(const Line: PChar; const Ext: Integer); {$ENDIF} procedure EnumLangOptions(const Line: PChar; const Ext: Integer); {$IFDEF UNICODE} procedure EnumLanguagesPre(const Line: PChar; const Ext: Integer); {$ENDIF} procedure EnumLanguages(const Line: PChar; const Ext: Integer); procedure EnumRegistry(const Line: PChar; const Ext: Integer); procedure EnumDelete(const Line: PChar; const Ext: Integer); procedure EnumFiles(const Line: PChar; const Ext: Integer); procedure EnumRun(const Line: PChar; const Ext: Integer); procedure EnumSetup(const Line: PChar; const Ext: Integer); procedure EnumMessages(const Line: PChar; const Ext: Integer); procedure EnumCustomMessages(const Line: PChar; const Ext: Integer); procedure ExtractParameters(S: PChar; const ParamInfo: array of TParamInfo; var ParamValues: array of TParamValue); function FindLangEntryIndexByName(const AName: String; const Pre: Boolean): Integer; function FindSignToolIndexByName(const AName: String): Integer; function GetLZMAExeFilename(const Allow64Bit: Boolean): String; procedure InitBzipDLL; procedure InitCryptDLL; {$IFDEF UNICODE} procedure InitPreLangData(const APreLangData: TPreLangData); {$ENDIF} procedure InitLanguageEntry(var ALanguageEntry: TSetupLanguageEntry); procedure InitLZMADLL; procedure InitPreprocessor; procedure InitZipDLL; function ParseFilename: String; procedure PopulateLanguageEntryData; procedure ProcessMinVersionParameter(const ParamValue: TParamValue; var AMinVersion: TSetupVersionData); procedure ProcessOnlyBelowVersionParameter(const ParamValue: TParamValue; var AOnlyBelowVersion: TSetupVersionData); procedure ProcessPermissionsParameter(ParamData: String; const AccessMasks: array of TNameAndAccessMask; var PermissionsEntry: Smallint); function EvalComponentIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; function EvalTaskIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; function EvalLanguageIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; procedure ProcessExpressionParameter(const ParamName, ParamData: String; OnEvalIdentifier: TSimpleExpressionOnEvalIdentifier; SlashConvert: Boolean; var ProcessedParamData: String); procedure ProcessWildcardsParameter(const ParamData: String; const AWildcards: TStringList; const TooLongMsg: String); procedure ReadDefaultMessages; {$IFDEF UNICODE} procedure ReadMessagesFromFilesPre(const AFiles: String; const ALangIndex: Integer); {$ENDIF} procedure ReadMessagesFromFiles(const AFiles: String; const ALangIndex: Integer); {$IFDEF UNICODE} procedure ReadMessagesFromScriptPre; {$ENDIF} procedure ReadMessagesFromScript; function ReadScriptFile(const Filename: String; const UseCache: Boolean; const AnsiConvertCodePage: Cardinal): TScriptFileLines; procedure EnumCode(const Line: PChar; const Ext: Integer); procedure ReadCode; procedure CodeCompilerOnLineToLineInfo(const Line: LongInt; var Filename: String; var FileLine: LongInt); procedure CodeCompilerOnUsedLine(const Filename: String; const Line, Position: LongInt); procedure CodeCompilerOnUsedVariable(const Filename: String; const Line, Col, Param1, Param2, Param3: LongInt; const Param4: AnsiString); procedure CodeCompilerOnError(const Msg: String; const ErrorFilename: String; const ErrorLine: LongInt); procedure CodeCompilerOnWarning(const Msg: String); procedure CompileCode; procedure ReadTextFile(const Filename: String; const LangIndex: Integer; var Text: AnsiString); procedure SeparateDirective(const Line: PChar; var Key, Value: String); procedure ShiftDebugEntryIndexes(AKind: TDebugEntryKind); procedure Sign(const ACommand, AParams, AExeFilename: String); procedure WriteDebugEntry(Kind: TDebugEntryKind; Index: Integer); procedure WriteCompiledCodeText(const CompiledCodeText: Ansistring); procedure WriteCompiledCodeDebugInfo(const CompiledCodeDebugInfo: AnsiString); public AppData: Longint; CallbackProc: TCompilerCallbackProc; CompilerDir, SourceDir, OriginalSourceDir: String; constructor Create(AOwner: TComponent); destructor Destroy; override; procedure AddSignTool(const Name, Command: String); procedure Compile; end; var {$IFNDEF UNICODE} CompilerLeadBytes: TLeadByteSet; {$ENDIF} ZipInitialized, BzipInitialized, LZMAInitialized, CryptInitialized: Boolean; PreprocessorInitialized: Boolean; PreprocessScriptProc: TPreprocessScriptProc; const ParamCommonFlags = 'Flags'; ParamCommonComponents = 'Components'; ParamCommonTasks = 'Tasks'; ParamCommonLanguages = 'Languages'; ParamCommonCheck = 'Check'; ParamCommonBeforeInstall = 'BeforeInstall'; ParamCommonAfterInstall = 'AfterInstall'; ParamCommonMinVersion = 'MinVersion'; ParamCommonOnlyBelowVersion = 'OnlyBelowVersion'; DefaultTypeEntryNames: array[0..2] of PChar = ('full', 'compact', 'custom'); MaxDiskSliceSize = 2100000000; type TColor = $7FFFFFFF-1..$7FFFFFFF; const clScrollBar = TColor(COLOR_SCROLLBAR or $80000000); clBackground = TColor(COLOR_BACKGROUND or $80000000); clActiveCaption = TColor(COLOR_ACTIVECAPTION or $80000000); clInactiveCaption = TColor(COLOR_INACTIVECAPTION or $80000000); clMenu = TColor(COLOR_MENU or $80000000); clWindow = TColor(COLOR_WINDOW or $80000000); clWindowFrame = TColor(COLOR_WINDOWFRAME or $80000000); clMenuText = TColor(COLOR_MENUTEXT or $80000000); clWindowText = TColor(COLOR_WINDOWTEXT or $80000000); clCaptionText = TColor(COLOR_CAPTIONTEXT or $80000000); clActiveBorder = TColor(COLOR_ACTIVEBORDER or $80000000); clInactiveBorder = TColor(COLOR_INACTIVEBORDER or $80000000); clAppWorkSpace = TColor(COLOR_APPWORKSPACE or $80000000); clHighlight = TColor(COLOR_HIGHLIGHT or $80000000); clHighlightText = TColor(COLOR_HIGHLIGHTTEXT or $80000000); clBtnFace = TColor(COLOR_BTNFACE or $80000000); clBtnShadow = TColor(COLOR_BTNSHADOW or $80000000); clGrayText = TColor(COLOR_GRAYTEXT or $80000000); clBtnText = TColor(COLOR_BTNTEXT or $80000000); clInactiveCaptionText = TColor(COLOR_INACTIVECAPTIONTEXT or $80000000); clBtnHighlight = TColor(COLOR_BTNHIGHLIGHT or $80000000); cl3DDkShadow = TColor(COLOR_3DDKSHADOW or $80000000); cl3DLight = TColor(COLOR_3DLIGHT or $80000000); clInfoText = TColor(COLOR_INFOTEXT or $80000000); clInfoBk = TColor(COLOR_INFOBK or $80000000); clBlack = TColor($000000); clMaroon = TColor($000080); clGreen = TColor($008000); clOlive = TColor($008080); clNavy = TColor($800000); clPurple = TColor($800080); clTeal = TColor($808000); clGray = TColor($808080); clSilver = TColor($C0C0C0); clRed = TColor($0000FF); clLime = TColor($00FF00); clYellow = TColor($00FFFF); clBlue = TColor($FF0000); clFuchsia = TColor($FF00FF); clAqua = TColor($FFFF00); clLtGray = TColor($C0C0C0); clDkGray = TColor($808080); clWhite = TColor($FFFFFF); clNone = TColor($1FFFFFFF); clDefault = TColor($20000000); type TColorEntry = record Value: TColor; Name: string; end; const Colors: array[0..41] of TColorEntry = ( (Value: clBlack; Name: 'clBlack'), (Value: clMaroon; Name: 'clMaroon'), (Value: clGreen; Name: 'clGreen'), (Value: clOlive; Name: 'clOlive'), (Value: clNavy; Name: 'clNavy'), (Value: clPurple; Name: 'clPurple'), (Value: clTeal; Name: 'clTeal'), (Value: clGray; Name: 'clGray'), (Value: clSilver; Name: 'clSilver'), (Value: clRed; Name: 'clRed'), (Value: clLime; Name: 'clLime'), (Value: clYellow; Name: 'clYellow'), (Value: clBlue; Name: 'clBlue'), (Value: clFuchsia; Name: 'clFuchsia'), (Value: clAqua; Name: 'clAqua'), (Value: clWhite; Name: 'clWhite'), (Value: clScrollBar; Name: 'clScrollBar'), (Value: clBackground; Name: 'clBackground'), (Value: clActiveCaption; Name: 'clActiveCaption'), (Value: clInactiveCaption; Name: 'clInactiveCaption'), (Value: clMenu; Name: 'clMenu'), (Value: clWindow; Name: 'clWindow'), (Value: clWindowFrame; Name: 'clWindowFrame'), (Value: clMenuText; Name: 'clMenuText'), (Value: clWindowText; Name: 'clWindowText'), (Value: clCaptionText; Name: 'clCaptionText'), (Value: clActiveBorder; Name: 'clActiveBorder'), (Value: clInactiveBorder; Name: 'clInactiveBorder'), (Value: clAppWorkSpace; Name: 'clAppWorkSpace'), (Value: clHighlight; Name: 'clHighlight'), (Value: clHighlightText; Name: 'clHighlightText'), (Value: clBtnFace; Name: 'clBtnFace'), (Value: clBtnShadow; Name: 'clBtnShadow'), (Value: clGrayText; Name: 'clGrayText'), (Value: clBtnText; Name: 'clBtnText'), (Value: clInactiveCaptionText; Name: 'clInactiveCaptionText'), (Value: clBtnHighlight; Name: 'clBtnHighlight'), (Value: cl3DDkShadow; Name: 'cl3DDkShadow'), (Value: cl3DLight; Name: 'cl3DLight'), (Value: clInfoText; Name: 'clInfoText'), (Value: clInfoBk; Name: 'clInfoBk'), (Value: clNone; Name: 'clNone')); function IdentToColor(const Ident: string; var Color: Longint): Boolean; var I: Integer; begin for I := Low(Colors) to High(Colors) do if CompareText(Colors[I].Name, Ident) = 0 then begin Result := True; Color := Longint(Colors[I].Value); Exit; end; Result := False; end; function StringToColor(const S: string): TColor; begin if not IdentToColor(S, Longint(Result)) then Result := TColor(StrToInt(S)); end; function IsRelativePath(const Filename: String): Boolean; var L: Integer; begin Result := True; L := Length(Filename); if ((L >= 1) and (Filename[1] = '\')) or ((L >= 2) and CharInSet(Filename[1], ['A'..'Z', 'a'..'z']) and (Filename[2] = ':')) then Result := False; end; function GetSelfFilename: String; { Returns Filename of the calling DLL or application. (ParamStr(0) can only return the filename of the calling application.) } var Buf: array[0..MAX_PATH-1] of Char; begin SetString(Result, Buf, GetModuleFileName(HInstance, Buf, SizeOf(Buf))) end; function CreateMemoryStreamFromFile(const Filename: String): TMemoryStream; { Creates a TMemoryStream and loads the contents of the specified file into it } var F: TFile; SizeOfFile: Cardinal; begin Result := TMemoryStream.Create; try { Why not use TMemoryStream.LoadFromFile here? 1. On Delphi 2 it opens files for exclusive access (not good). 2. It doesn't give specific error messages. } F := TFile.Create(Filename, fdOpenExisting, faRead, fsRead); try SizeOfFile := F.CappedSize; Result.SetSize(SizeOfFile); F.ReadBuffer(Result.Memory^, SizeOfFile); finally F.Free; end; except Result.Free; raise Exception.CreateFmt(SCompilerReadError, [Filename, GetExceptMessage]); end; end; function FileSizeAndCRCIs(const Filename: String; const Size: Cardinal; const CRC: Longint): Boolean; var F: TFile; SizeOfFile: Integer64; Buf: AnsiString; begin Result := False; try F := TFile.Create(Filename, fdOpenExisting, faRead, fsRead); try SizeOfFile := F.Size; if (SizeOfFile.Lo = Size) and (SizeOfFile.Hi = 0) then begin SetLength(Buf, Size); F.ReadBuffer(Buf[1], Size); if GetCRC32(Buf[1], Size) = CRC then Result := True; end; finally F.Free; end; except end; end; const IMAGE_NT_SIGNATURE = $00004550; { 'PE'#0#0 } IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b; type TImageFileHeader = packed record Machine: Word; NumberOfSections: Word; TimeDateStamp: DWORD; PointerToSymbolTable: DWORD; NumberOfSymbols: DWORD; SizeOfOptionalHeader: Word; Characteristics: Word; end; function SeekToPEHeader(const F: TCustomFile): Boolean; var DosHeader: packed record Sig: array[0..1] of AnsiChar; Other: array[0..57] of Byte; PEHeaderOffset: LongWord; end; Sig: DWORD; begin Result := False; F.Seek(0); if F.Read(DosHeader, SizeOf(DosHeader)) = SizeOf(DosHeader) then begin if (DosHeader.Sig[0] = 'M') and (DosHeader.Sig[1] = 'Z') and (DosHeader.PEHeaderOffset <> 0) then begin F.Seek(DosHeader.PEHeaderOffset); if F.Read(Sig, SizeOf(Sig)) = SizeOf(Sig) then if Sig = IMAGE_NT_SIGNATURE then Result := True; end; end; end; function IsX86OrX64Executable(const F: TFile): Boolean; const IMAGE_FILE_MACHINE_I386 = $014C; IMAGE_FILE_MACHINE_AMD64 = $8664; var DosHeader: array[0..63] of Byte; PEHeaderOffset: Longint; PESigAndHeader: packed record Sig: DWORD; Machine: Word; end; begin Result := False; if F.Read(DosHeader, SizeOf(DosHeader)) = SizeOf(DosHeader) then begin if (DosHeader[0] = Ord('M')) and (DosHeader[1] = Ord('Z')) then begin PEHeaderOffset := PLongint(@DosHeader[60])^; if PEHeaderOffset > 0 then begin F.Seek(PEHeaderOffset); if F.Read(PESigAndHeader, SizeOf(PESigAndHeader)) = SizeOf(PESigAndHeader) then begin if (PESigAndHeader.Sig = IMAGE_NT_SIGNATURE) and ((PESigAndHeader.Machine = IMAGE_FILE_MACHINE_I386) or (PESigAndHeader.Machine = IMAGE_FILE_MACHINE_AMD64)) then Result := True; end; end; end; end; F.Seek(0); end; function Is64BitPEImage(const Filename: String): Boolean; { Returns True if the specified file is a non-32-bit PE image, False otherwise. } var F: TFile; DosHeader: packed record Sig: array[0..1] of AnsiChar; Other: array[0..57] of Byte; PEHeaderOffset: LongWord; end; PESigAndHeader: packed record Sig: DWORD; Header: TImageFileHeader; OptHeaderMagic: Word; end; begin Result := False; F := TFile.Create(Filename, fdOpenExisting, faRead, fsRead); try if F.Read(DosHeader, SizeOf(DosHeader)) = SizeOf(DosHeader) then begin if (DosHeader.Sig[0] = 'M') and (DosHeader.Sig[1] = 'Z') and (DosHeader.PEHeaderOffset <> 0) then begin F.Seek(DosHeader.PEHeaderOffset); if F.Read(PESigAndHeader, SizeOf(PESigAndHeader)) = SizeOf(PESigAndHeader) then begin if (PESigAndHeader.Sig = IMAGE_NT_SIGNATURE) and (PESigAndHeader.OptHeaderMagic <> IMAGE_NT_OPTIONAL_HDR32_MAGIC) then Result := True; end; end; end; finally F.Free; end; end; procedure UpdateSetupPEHeaderFields(const F: TCustomFile; const IsTSAware: Boolean); const IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = $8000; OffsetOfImageVersion = $2C; OffsetOfDllCharacteristics = $46; var Header: TImageFileHeader; Ofs: Cardinal; OptMagic, DllChars, OrigDllChars: Word; ImageVersion: packed record Major, Minor: Word; end; begin if SeekToPEHeader(F) then begin if (F.Read(Header, SizeOf(Header)) = SizeOf(Header)) and (Header.SizeOfOptionalHeader = 224) then begin Ofs := F.Position.Lo; if (F.Read(OptMagic, SizeOf(OptMagic)) = SizeOf(OptMagic)) and (OptMagic = IMAGE_NT_OPTIONAL_HDR32_MAGIC) then begin { Update MajorImageVersion and MinorImageVersion to 6.0. Works around apparent bug in Vista (still present in Vista SP1; not reproducible on Server 2008): When UAC is turned off, launching an uninstaller (as admin) from ARP and answering No at the ConfirmUninstall message box causes a "This program might not have uninstalled correctly" dialog to be displayed, even if the EXE has a proper "Vista-aware" manifest. I discovered that if the EXE's image version is set to 6.0, like the EXEs that ship with Vista (notepad.exe), the dialog does not appear. (This is reproducible with notepad.exe too if its image version is changed to anything other than 6.0 exactly.) } F.Seek(Ofs + OffsetOfImageVersion); ImageVersion.Major := 6; ImageVersion.Minor := 0; F.WriteBuffer(ImageVersion, SizeOf(ImageVersion)); { Update DllCharacteristics } F.Seek(Ofs + OffsetOfDllCharacteristics); if F.Read(DllChars, SizeOf(DllChars)) = SizeOf(DllChars) then begin OrigDllChars := DllChars; if IsTSAware then DllChars := DllChars or IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE else DllChars := DllChars and not IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE; if DllChars <> OrigDllChars then begin F.Seek(Ofs + OffsetOfDllCharacteristics); F.WriteBuffer(DllChars, SizeOf(DllChars)); end; Exit; end; end; end; end; raise Exception.Create('UpdateSetupPEHeaderFields failed'); end; function CountChars(const S: String; C: Char): Integer; var I: Integer; begin Result := 0; for I := 1 to Length(S) do if S[I] = C then Inc(Result); end; function IsValidIdentString(const S: String; AllowBackslash, AllowOperators: Boolean): Boolean; var I, N: Integer; begin if S = '' then Result := False else if not AllowOperators and ((CompareText(S, 'not') = 0) or (CompareText(S, 'and') = 0) or (CompareText(S, 'or') = 0)) then Result := False else begin N := Length(S); for I := 1 to N do if not (CharInSet(S[I], ['A'..'Z', 'a'..'z', '_']) or ((I > 1) and CharInSet(S[I], ['0'..'9'])) or (AllowBackslash and (I > 1) and (I < N) and (S[I] = '\'))) then begin Result := False; Exit; end; Result := True; end; end; procedure SkipWhitespace(var S: PChar); begin while CharInSet(S^, [#1..' ']) do Inc(S); end; function ExtractWords(var S: PChar; const Sep: Char): String; { Extracts characters from S until it reaches the character Sep or the end of S. The returned string has trailing whitespace characters trimmed off. } var StartPos, EndPos: PChar; begin StartPos := S; EndPos := S; while (S^ <> #0) and (S^ <> Sep) do begin if S^ > ' ' then EndPos := S + 1; Inc(S); end; SetString(Result, StartPos, EndPos - StartPos); end; function UnescapeBraces(const S: String): String; { Changes all '{{' to '{'. Assumes that S does not contain any constants; you should check before calling. } var I: Integer; begin Result := S; I := 1; while I < Length(Result) do begin if Result[I] = '{' then begin Inc(I); if Result[I] = '{' then Delete(Result, I, 1); end else begin {$IFNDEF UNICODE} if Result[I] in CompilerLeadBytes then Inc(I); {$ENDIF} Inc(I); end; end; end; type HCRYPTPROV = DWORD; const PROV_RSA_FULL = 1; CRYPT_VERIFYCONTEXT = $F0000000; function CryptAcquireContext(var phProv: HCRYPTPROV; pszContainer: PAnsiChar; pszProvider: PAnsiChar; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall; external advapi32 name 'CryptAcquireContextA'; function CryptReleaseContext(hProv: HCRYPTPROV; dwFlags: DWORD): BOOL; stdcall; external advapi32 name 'CryptReleaseContext'; function CryptGenRandom(hProv: HCRYPTPROV; dwLen: DWORD; pbBuffer: Pointer): BOOL; stdcall; external advapi32 name 'CryptGenRandom'; var CryptProv: HCRYPTPROV; procedure GenerateRandomBytes(var Buffer; Bytes: Cardinal); var ErrorCode: DWORD; begin if CryptProv = 0 then begin if not CryptAcquireContext(CryptProv, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) then begin ErrorCode := GetLastError; raise Exception.CreateFmt('CryptAcquireContext failed with code 0x%.8x: %s', [ErrorCode, Win32ErrorString(ErrorCode)]); end; { Note: CryptProv is released in the 'finalization' section of this unit } end; FillChar(Buffer, Bytes, 0); if not CryptGenRandom(CryptProv, Bytes, @Buffer) then begin ErrorCode := GetLastError; raise Exception.CreateFmt('CryptGenRandom failed with code 0x%.8x: %s', [ErrorCode, Win32ErrorString(ErrorCode)]); end; end; { TLowFragList } procedure TLowFragList.Grow; var Delta: Integer; begin { Delphi 2's TList.Grow induces memory fragmentation big time. This is the Grow code from Delphi 3 and later. } if Capacity > 64 then Delta := Capacity div 4 else if Capacity > 8 then Delta := 16 else Delta := 4; SetCapacity(Capacity + Delta); end; { TLowFragStringList } constructor TLowFragStringList.Create; begin inherited; FInternalList := TLowFragList.Create; end; destructor TLowFragStringList.Destroy; begin if Assigned(FInternalList) then begin Clear; FInternalList.Free; end; inherited; end; function TLowFragStringList.Add(const S: String): Integer; var P: Pointer; begin FInternalList.Expand; P := nil; String(P) := S; { bump the ref count } Result := FInternalList.Add(P); end; procedure TLowFragStringList.Clear; begin if FInternalList.Count <> 0 then Finalize(String(FInternalList.List[0]), FInternalList.Count); FInternalList.Clear; end; function TLowFragStringList.Get(Index: Integer): String; begin Result := String(FInternalList[Index]); end; function TLowFragStringList.GetCount: Integer; begin Result := FInternalList.Count; end; procedure TLowFragStringList.Put(Index: Integer; const Value: String); begin if (Index < 0) or (Index >= FInternalList.Count) then raise EListError.CreateFmt('List index out of bounds (%d)', [Index]); String(FInternalList.List[Index]) := Value; end; { THashStringList } destructor THashStringList.Destroy; begin Clear; inherited; end; function THashStringList.Add(const S: String): Integer; var LS: String; begin Result := FCount; if Result = FCapacity then Grow; LS := PathLowercase(S); Pointer(FList[Result].Str) := nil; { since Grow doesn't zero init } FList[Result].Str := S; FList[Result].Hash := GetCRC32(Pointer(LS)^, Length(LS)*SizeOf(LS[1])); Inc(FCount); end; procedure THashStringList.Clear; begin if FCount > 0 then Finalize(FList[0], FCount); FCount := 0; FCapacity := 0; ReallocMem(FList, 0); end; function THashStringList.Get(Index: Integer): String; begin if (Index < 0) or (Index >= FCount) then raise EStringListError.CreateFmt('THashStringList: Index %d is out of bounds', [Index]); Result := FList[Index].Str; end; procedure THashStringList.Grow; var Delta, NewCapacity: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else if FCapacity > 8 then Delta := 16 else Delta := 4; NewCapacity := FCapacity + Delta; if NewCapacity > MaxListSize then raise EStringListError.Create('THashStringList: Exceeded maximum list size'); ReallocMem(FList, NewCapacity * SizeOf(FList[0])); FCapacity := NewCapacity; end; function THashStringList.CaseInsensitiveIndexOf(const S: String): Integer; var LS: String; Hash: Longint; I: Integer; begin LS := PathLowercase(S); Hash := GetCRC32(Pointer(LS)^, Length(LS)*SizeOf(LS[1])); for I := 0 to FCount-1 do if (FList[I].Hash = Hash) and (PathLowercase(FList[I].Str) = LS) then begin Result := I; Exit; end; Result := -1; end; { TScriptFileLines } constructor TScriptFileLines.Create; begin inherited; FLines := TLowFragList.Create; end; destructor TScriptFileLines.Destroy; var I: Integer; begin if Assigned(FLines) then begin for I := FLines.Count-1 downto 0 do Dispose(PScriptFileLine(FLines[I])); FLines.Free; end; inherited; end; procedure TScriptFileLines.Add(const LineFilename: String; const LineNumber: Integer; const LineText: String); var L, PrevLine: PScriptFileLine; begin FLines.Expand; New(L); try { Memory usage optimization: If LineFilename is equal to the previous line's LineFilename, then make this line's LineFilename reference the same string (i.e. just increment its refcount). } PrevLine := nil; if (LineFilename <> '') and (FLines.Count > 0) then PrevLine := PScriptFileLine(FLines[FLines.Count-1]); if Assigned(PrevLine) and (PrevLine.LineFilename = LineFilename) then L.LineFilename := PrevLine.LineFilename else L.LineFilename := LineFilename; L.LineNumber := LineNumber; L.LineText := LineText; except Dispose(L); raise; end; FLines.Add(L); end; function TScriptFileLines.Get(Index: Integer): PScriptFileLine; begin Result := PScriptFileLine(FLines[Index]); end; function TScriptFileLines.GetCount: Integer; begin Result := FLines.Count; end; { Built-in preprocessor } type EBuiltinPreprocessScriptError = class(Exception); function BuiltinPreprocessScript(var Params: TPreprocessScriptParams): Integer; stdcall; var IncludeStack: TStringList; procedure RaiseError(const LineFilename: String; const LineNumber: Integer; const Msg: String); begin Params.ErrorProc(Params.CompilerData, PChar(Msg), PChar(LineFilename), LineNumber, 0); { Note: This exception is caught and translated into ispePreprocessError } raise EBuiltinPreprocessScriptError.Create('BuiltinPreprocessScript error'); end; procedure ProcessLines(const Filename: String; const FileHandle: TPreprocFileHandle); forward; procedure ProcessLinesFromFile(const LineFilename: String; const LineNumber: Integer; const IncludeFilename: String); var I: Integer; FileHandle: TPreprocFileHandle; begin { Check if it's a recursive include } for I := 0 to IncludeStack.Count-1 do if PathCompare(IncludeStack[I], IncludeFilename) = 0 then RaiseError(LineFilename, LineNumber, Format(SCompilerRecursiveInclude, [IncludeFilename])); FileHandle := Params.LoadFileProc(Params.CompilerData, PChar(IncludeFilename), PChar(LineFilename), LineNumber, 0); if FileHandle < 0 then begin { Note: The message here shouldn't be seen as LoadFileProc should have already called ErrorProc itself } RaiseError(LineFilename, LineNumber, 'LoadFileProc failed'); end; ProcessLines(IncludeFilename, FileHandle); end; procedure ProcessDirective(const LineFilename: String; const LineNumber: Integer; D: String); var Dir, IncludeFilename: String; begin if Copy(D, 1, Length('include')) = 'include' then begin Delete(D, 1, Length('include')); if (D = '') or (D[1] > ' ') then RaiseError(LineFilename, LineNumber, SCompilerInvalidDirective); D := TrimLeft(D); if (Length(D) < 3) or (D[1] <> '"') or (PathLastChar(D)^ <> '"') then RaiseError(LineFilename, LineNumber, SCompilerInvalidDirective); if LineFilename = '' then Dir := Params.SourcePath else Dir := PathExtractPath(LineFilename); IncludeFilename := Params.PrependDirNameProc(Params.CompilerData, PChar(RemoveQuotes(D)), PChar(Dir), PChar(LineFilename), LineNumber, 0); if IncludeFilename = '' then begin { Note: The message here shouldn't be seen as PrependDirNameProc should have already called ErrorProc itself } RaiseError(LineFilename, LineNumber, 'PrependDirNameProc failed'); end; ProcessLinesFromFile(LineFilename, LineNumber, PathExpand(IncludeFilename)); end else RaiseError(LineFilename, LineNumber, SCompilerInvalidDirective); end; procedure ProcessLines(const Filename: String; const FileHandle: TPreprocFileHandle); var I: Integer; LineText, L: PChar; begin IncludeStack.Add(Filename); I := 0; while True do begin LineText := Params.LineInProc(Params.CompilerData, FileHandle, I); if LineText = nil then Break; L := LineText; SkipWhitespace(L); if L^ = '#' then ProcessDirective(Filename, I + 1, L + 1) else Params.LineOutProc(Params.CompilerData, PChar(Filename), I + 1, LineText); Inc(I); end; IncludeStack.Delete(IncludeStack.Count-1); end; begin if (Params.Size <> SizeOf(Params)) or (Params.InterfaceVersion <> 1) then begin Result := ispeInvalidParam; Exit; end; try IncludeStack := TStringList.Create; try ProcessLines(Params.Filename, 0); finally IncludeStack.Free; end; Result := ispeSuccess; except Result := ispePreprocessError; if not(ExceptObject is EBuiltinPreprocessScriptError) then raise; end; end; { TCompressionHandler } type TCompressionHandler = class private FCachedCompressors: TLowFragList; FCompiler: TSetupCompiler; FCompressor: TCustomCompressor; FChunkBytesRead: Integer64; FChunkBytesWritten: Integer64; FChunkEncrypted: Boolean; FChunkFirstSlice: Integer; FChunkStarted: Boolean; FChunkStartOffset: Longint; FCryptContext: TArcFourContext; FCurSlice: Integer; FDestFile: TFile; FDestFileIsDiskSlice: Boolean; FInitialBytesCompressedSoFar: Integer64; FSliceBaseOffset: Cardinal; FSliceBytesLeft: Cardinal; procedure EndSlice; procedure NewSlice(const Filename: String); public constructor Create(ACompiler: TSetupCompiler; const InitialSliceFilename: String); destructor Destroy; override; procedure CompressFile(const SourceFile: TFile; Bytes: Integer64; const CallOptimize: Boolean; var SHA1Sum: TSHA1Digest); procedure EndChunk; procedure Finish; procedure NewChunk(const ACompressorClass: TCustomCompressorClass; const ACompressLevel: Integer; const ACompressorProps: TCompressorProps; const AUseEncryption: Boolean; const ACryptKey: String); procedure ProgressProc(BytesProcessed: Cardinal); function ReserveBytesOnSlice(const Bytes: Cardinal): Boolean; procedure WriteProc(const Buf; BufSize: Longint); property ChunkBytesRead: Integer64 read FChunkBytesRead; property ChunkBytesWritten: Integer64 read FChunkBytesWritten; property ChunkEncrypted: Boolean read FChunkEncrypted; property ChunkFirstSlice: Integer read FChunkFirstSlice; property ChunkStartOffset: Longint read FChunkStartOffset; property ChunkStarted: Boolean read FChunkStarted; property CurSlice: Integer read FCurSlice; end; constructor TCompressionHandler.Create(ACompiler: TSetupCompiler; const InitialSliceFilename: String); begin inherited Create; FCompiler := ACompiler; FCurSlice := -1; FCachedCompressors := TLowFragList.Create; NewSlice(InitialSliceFilename); end; destructor TCompressionHandler.Destroy; var I: Integer; begin if Assigned(FCachedCompressors) then begin for I := FCachedCompressors.Count-1 downto 0 do TCustomCompressor(FCachedCompressors[I]).Free; FreeAndNil(FCachedCompressors); end; FreeAndNil(FDestFile); inherited; end; procedure TCompressionHandler.Finish; begin EndChunk; EndSlice; end; procedure TCompressionHandler.EndSlice; var DiskSliceHeader: TDiskSliceHeader; begin if Assigned(FDestFile) then begin if FDestFileIsDiskSlice then begin DiskSliceHeader.TotalSize := FDestFile.Size.Lo; FDestFile.Seek(SizeOf(DiskSliceID)); FDestFile.WriteBuffer(DiskSliceHeader, SizeOf(DiskSliceHeader)); end; FreeAndNil(FDestFile); end; end; procedure TCompressionHandler.NewSlice(const Filename: String); function GenerateSliceFilename(const Compiler: TSetupCompiler; const ASlice: Integer): String; var Major, Minor: Integer; begin Major := ASlice div Compiler.SlicesPerDisk + 1; Minor := ASlice mod Compiler.SlicesPerDisk; if Compiler.SlicesPerDisk = 1 then Result := Format('%s-%d.bin', [Compiler.OutputBaseFilename, Major]) else Result := Format('%s-%d%s.bin', [Compiler.OutputBaseFilename, Major, Chr(Ord('a') + Minor)]); end; var DiskHeader: TDiskSliceHeader; begin EndSlice; Inc(FCurSlice); if (FCurSlice > 0) and not FCompiler.DiskSpanning then FCompiler.AbortCompileFmt(SCompilerMustUseDiskSpanning, [FCompiler.DiskSliceSize]); if Filename = '' then begin FDestFileIsDiskSlice := True; FDestFile := TFile.Create(FCompiler.OutputDir + GenerateSliceFilename(FCompiler, FCurSlice), fdCreateAlways, faReadWrite, fsNone); FDestFile.WriteBuffer(DiskSliceID, SizeOf(DiskSliceID)); DiskHeader.TotalSize := 0; FDestFile.WriteBuffer(DiskHeader, SizeOf(DiskHeader)); FSliceBaseOffset := 0; FSliceBytesLeft := FCompiler.DiskSliceSize - (SizeOf(DiskSliceID) + SizeOf(DiskHeader)); end else begin FDestFileIsDiskSlice := False; FDestFile := TFile.Create(Filename, fdOpenExisting, faReadWrite, fsNone); FDestFile.SeekToEnd; FSliceBaseOffset := FDestFile.Position.Lo; FSliceBytesLeft := Cardinal(FCompiler.DiskSliceSize) - FSliceBaseOffset; end; end; function TCompressionHandler.ReserveBytesOnSlice(const Bytes: Cardinal): Boolean; begin if FSliceBytesLeft >= Bytes then begin Dec(FSliceBytesLeft, Bytes); Result := True; end else Result := False; end; procedure TCompressionHandler.NewChunk(const ACompressorClass: TCustomCompressorClass; const ACompressLevel: Integer; const ACompressorProps: TCompressorProps; const AUseEncryption: Boolean; const ACryptKey: String); procedure SelectCompressor; var I: Integer; C: TCustomCompressor; begin { No current compressor, or changing compressor classes? } if (FCompressor = nil) or (FCompressor.ClassType <> ACompressorClass) then begin FCompressor := nil; { Search cache for requested class } for I := FCachedCompressors.Count-1 downto 0 do begin C := FCachedCompressors[I]; if C.ClassType = ACompressorClass then begin FCompressor := C; Break; end; end; end; if FCompressor = nil then begin FCachedCompressors.Expand; FCompressor := ACompressorClass.Create(WriteProc, ProgressProc, ACompressLevel, ACompressorProps); FCachedCompressors.Add(FCompressor); end; end; procedure InitEncryption; var Salt: TSetupSalt; Context: TSHA1Context; Hash: TSHA1Digest; begin { Generate and write a random salt. This salt is hashed into the key to prevent the same key from ever being used twice (theoretically). } GenerateRandomBytes(Salt, SizeOf(Salt)); FDestFile.WriteBuffer(Salt, SizeOf(Salt)); { Create an SHA-1 hash of the salt plus ACryptKey, and use that as the key } SHA1Init(Context); SHA1Update(Context, Salt, SizeOf(Salt)); SHA1Update(Context, Pointer(ACryptKey)^, Length(ACryptKey)*SizeOf(ACryptKey[1])); Hash := SHA1Final(Context); ArcFourInit(FCryptContext, Hash, SizeOf(Hash)); { Discard first 1000 bytes of the output keystream, since according to <http://en.wikipedia.org/wiki/RC4_(cipher)>, "the first few bytes of output keystream are strongly non-random." } ArcFourDiscard(FCryptContext, 1000); end; var MinBytesLeft: Cardinal; begin EndChunk; { If there isn't enough room left to start a new chunk on the current slice, start a new slice } MinBytesLeft := SizeOf(ZLIBID); if AUseEncryption then Inc(MinBytesLeft, SizeOf(TSetupSalt)); Inc(MinBytesLeft); { for at least one byte of data } if FSliceBytesLeft < MinBytesLeft then NewSlice(''); FChunkFirstSlice := FCurSlice; FChunkStartOffset := FDestFile.Position.Lo - FSliceBaseOffset; FDestFile.WriteBuffer(ZLIBID, SizeOf(ZLIBID)); Dec(FSliceBytesLeft, SizeOf(ZLIBID)); FChunkBytesRead.Hi := 0; FChunkBytesRead.Lo := 0; FChunkBytesWritten.Hi := 0; FChunkBytesWritten.Lo := 0; FInitialBytesCompressedSoFar := FCompiler.BytesCompressedSoFar; SelectCompressor; FChunkEncrypted := AUseEncryption; if AUseEncryption then InitEncryption; FChunkStarted := True; end; procedure TCompressionHandler.EndChunk; begin if Assigned(FCompressor) then begin FCompressor.Finish; { In case we didn't get a ProgressProc call after the final block: } FCompiler.BytesCompressedSoFar := FInitialBytesCompressedSoFar; Inc6464(FCompiler.BytesCompressedSoFar, FChunkBytesRead); FCompiler.CallIdleProc; end; FChunkStarted := False; end; procedure TCompressionHandler.CompressFile(const SourceFile: TFile; Bytes: Integer64; const CallOptimize: Boolean; var SHA1Sum: TSHA1Digest); var Context: TSHA1Context; AddrOffset: LongWord; BufSize: Cardinal; Buf: array[0..65535] of Byte; { ^ *must* be the same buffer size used in Setup (TFileExtractor), otherwise the TransformCallInstructions call will break } begin SHA1Init(Context); AddrOffset := 0; while True do begin BufSize := SizeOf(Buf); if (Bytes.Hi = 0) and (Bytes.Lo < BufSize) then BufSize := Bytes.Lo; if BufSize = 0 then Break; SourceFile.ReadBuffer(Buf, BufSize); Inc64(FChunkBytesRead, BufSize); Dec64(Bytes, BufSize); SHA1Update(Context, Buf, BufSize); if CallOptimize then begin TransformCallInstructions(Buf, BufSize, True, AddrOffset); Inc(AddrOffset, BufSize); { may wrap, but OK } end; FCompressor.Compress(Buf, BufSize); end; SHA1Sum := SHA1Final(Context); end; procedure TCompressionHandler.WriteProc(const Buf; BufSize: Longint); var P, P2: Pointer; S: Cardinal; begin FCompiler.CallIdleProc; P := @Buf; while BufSize > 0 do begin S := BufSize; if FSliceBytesLeft = 0 then NewSlice(''); if S > Cardinal(FSliceBytesLeft) then S := FSliceBytesLeft; if not FChunkEncrypted then FDestFile.WriteBuffer(P^, S) else begin { Using encryption. Can't modify Buf in place so allocate a new, temporary buffer. } GetMem(P2, S); try ArcFourCrypt(FCryptContext, P^, P2^, S); FDestFile.WriteBuffer(P2^, S) finally FreeMem(P2); end; end; Inc64(FChunkBytesWritten, S); Inc(Cardinal(P), S); Dec(BufSize, S); Dec(FSliceBytesLeft, S); end; end; procedure TCompressionHandler.ProgressProc(BytesProcessed: Cardinal); begin Inc64(FCompiler.BytesCompressedSoFar, BytesProcessed); FCompiler.CallIdleProc; end; { TSetupCompiler } constructor TSetupCompiler.Create(AOwner: TComponent); begin inherited Create; ScriptFiles := TStringList.Create; LanguageEntries := TLowFragList.Create; CustomMessageEntries := TLowFragList.Create; PermissionEntries := TLowFragList.Create; TypeEntries := TLowFragList.Create; ComponentEntries := TLowFragList.Create; TaskEntries := TLowFragList.Create; DirEntries := TLowFragList.Create; FileEntries := TLowFragList.Create; FileLocationEntries := TLowFragList.Create; IconEntries := TLowFragList.Create; IniEntries := TLowFragList.Create; RegistryEntries := TLowFragList.Create; InstallDeleteEntries := TLowFragList.Create; UninstallDeleteEntries := TLowFragList.Create; RunEntries := TLowFragList.Create; UninstallRunEntries := TLowFragList.Create; FileLocationEntryFilenames := THashStringList.Create; WarningsList := TLowFragStringList.Create; ExpectedCustomMessageNames := TStringList.Create; DefaultLangData := TLangData.Create; {$IFDEF UNICODE} PreLangDataList := TLowFragList.Create; {$ENDIF} LangDataList := TLowFragList.Create; SignToolList := TLowFragList.Create; DebugInfo := TMemoryStream.Create; CodeDebugInfo := TMemoryStream.Create; CodeText := TStringList.Create; CodeCompiler := TScriptCompiler.Create; end; destructor TSetupCompiler.Destroy; var I: Integer; begin CodeCompiler.Free; CodeText.Free; CodeDebugInfo.Free; DebugInfo.Free; if Assigned(SignToolList) then begin for I := 0 to SignToolList.Count-1 do TSignTool(SignToolList[I]).Free; SignToolList.Free; end; LangDataList.Free; {$IFDEF UNICODE} PreLangDataList.Free; {$ENDIF} DefaultLangData.Free; ExpectedCustomMessageNames.Free; WarningsList.Free; FileLocationEntryFilenames.Free; UninstallRunEntries.Free; RunEntries.Free; UninstallDeleteEntries.Free; InstallDeleteEntries.Free; RegistryEntries.Free; IniEntries.Free; IconEntries.Free; FileLocationEntries.Free; FileEntries.Free; DirEntries.Free; TaskEntries.Free; ComponentEntries.Free; TypeEntries.Free; PermissionEntries.Free; CustomMessageEntries.Free; LanguageEntries.Free; ScriptFiles.Free; inherited Destroy; end; procedure TSetupCompiler.InitPreprocessor; {$IFNDEF STATICPREPROC} const FuncNameSuffix = {$IFDEF UNICODE} 'W' {$ELSE} 'A' {$ENDIF}; var Filename: String; Attr: DWORD; M: HMODULE; {$ENDIF} begin if PreprocessorInitialized then Exit; {$IFNDEF STATICPREPROC} Filename := CompilerDir + 'ISPP.dll'; Attr := GetFileAttributes(PChar(Filename)); if (Attr = $FFFFFFFF) and (GetLastError = ERROR_FILE_NOT_FOUND) then begin { ISPP unavailable; fall back to built-in preprocessor } end else begin M := SafeLoadLibrary(Filename, SEM_NOOPENFILEERRORBOX); if M = 0 then AbortCompileFmt('Failed to load preprocessor DLL "%s" (%d)', [Filename, GetLastError]); PreprocessScriptProc := GetProcAddress(M, PAnsiChar('ISPreprocessScript' + FuncNameSuffix)); if not Assigned(PreprocessScriptProc) then AbortCompileFmt('Failed to get address of functions in "%s"', [Filename]); end; {$ELSE} PreprocessScriptProc := ISPreprocessScript; {$ENDIF} PreprocessorInitialized := True; end; procedure TSetupCompiler.InitZipDLL; var M: HMODULE; begin if ZipInitialized then Exit; M := SafeLoadLibrary(CompilerDir + 'iszlib.dll', SEM_NOOPENFILEERRORBOX); if M = 0 then AbortCompileFmt('Failed to load iszlib.dll (%d)', [GetLastError]); if not ZlibInitCompressFunctions(M) then AbortCompile('Failed to get address of functions in iszlib.dll'); ZipInitialized := True; end; procedure TSetupCompiler.InitBzipDLL; var M: HMODULE; begin if BzipInitialized then Exit; M := SafeLoadLibrary(CompilerDir + 'isbzip.dll', SEM_NOOPENFILEERRORBOX); if M = 0 then AbortCompileFmt('Failed to load isbzip.dll (%d)', [GetLastError]); if not BZInitCompressFunctions(M) then AbortCompile('Failed to get address of functions in isbzip.dll'); BzipInitialized := True; end; procedure TSetupCompiler.InitLZMADLL; var M: HMODULE; begin if LZMAInitialized then Exit; M := SafeLoadLibrary(CompilerDir + 'islzma.dll', SEM_NOOPENFILEERRORBOX); if M = 0 then AbortCompileFmt('Failed to load islzma.dll (%d)', [GetLastError]); if not LZMAInitCompressFunctions(M) then AbortCompile('Failed to get address of functions in islzma.dll'); LZMAInitialized := True; end; function TSetupCompiler.GetLZMAExeFilename(const Allow64Bit: Boolean): String; const PROCESSOR_ARCHITECTURE_AMD64 = 9; ExeFilenames: array[Boolean] of String = ('islzma32.exe', 'islzma64.exe'); var UseX64Exe: Boolean; GetNativeSystemInfoFunc: procedure(var lpSystemInfo: TSystemInfo); stdcall; SysInfo: TSystemInfo; begin UseX64Exe := False; if Allow64Bit then begin GetNativeSystemInfoFunc := GetProcAddress(GetModuleHandle(kernel32), 'GetNativeSystemInfo'); if Assigned(GetNativeSystemInfoFunc) then begin GetNativeSystemInfoFunc(SysInfo); if SysInfo.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64 then UseX64Exe := True; end; end; Result := CompilerDir + ExeFilenames[UseX64Exe]; end; procedure TSetupCompiler.InitCryptDLL; var M: HMODULE; begin if CryptInitialized then Exit; M := SafeLoadLibrary(CompilerDir + 'iscrypt.dll', SEM_NOOPENFILEERRORBOX); if M = 0 then AbortCompileFmt('Failed to load iscrypt.dll (%d)', [GetLastError]); if not ArcFourInitFunctions(M) then AbortCompile('Failed to get address of functions in iscrypt.dll'); CryptInitialized := True; end; function TSetupCompiler.ParseFilename: String; begin Result := LineFilename; end; procedure TSetupCompiler.WriteDebugEntry(Kind: TDebugEntryKind; Index: Integer); var Rec: TDebugEntry; begin if ParseFilename = '' then Rec.LineNumber := LineNumber else Rec.LineNumber := 0; Rec.Kind := Ord(Kind); Rec.Index := Index; DebugInfo.WriteBuffer(Rec, SizeOf(Rec)); Inc(DebugEntryCount); end; procedure TSetupCompiler.WriteCompiledCodeText(const CompiledCodeText: AnsiString); begin CompiledCodeTextLength := Length(CompiledCodeText); CodeDebugInfo.WriteBuffer(CompiledCodeText[1], CompiledCodeTextLength); end; procedure TSetupCompiler.WriteCompiledCodeDebugInfo(const CompiledCodeDebugInfo: AnsiString); begin CompiledCodeDebugInfoLength := Length(CompiledCodeDebugInfo); CodeDebugInfo.WriteBuffer(CompiledCodeDebugInfo[1], CompiledCodeDebugInfoLength); end; procedure TSetupCompiler.ShiftDebugEntryIndexes(AKind: TDebugEntryKind); { Increments the Index field of each debug entry of the specified kind by 1. This has to be called when a new entry is inserted at the *front* of an *Entries array, since doing that causes the indexes of existing entries to shift. } var Rec: PDebugEntry; I: Integer; begin Cardinal(Rec) := Cardinal(DebugInfo.Memory) + SizeOf(TDebugInfoHeader); for I := 0 to DebugEntryCount-1 do begin if Rec.Kind = Ord(AKind) then Inc(Rec.Index); Inc(Rec); end; end; procedure TSetupCompiler.DoCallback(const Code: Integer; var Data: TCompilerCallbackData); begin case CallbackProc(Code, Data, AppData) of iscrSuccess: ; iscrRequestAbort: Abort; else AbortCompile('CallbackProc return code invalid'); end; end; procedure TSetupCompiler.CallIdleProc; const ProgressMax = 1024; var Data: TCompilerCallbackData; MillisecondsElapsed: Cardinal; X: Integer64; begin Data.SecondsRemaining := -1; Data.BytesCompressedPerSecond := 0; if ((BytesCompressedSoFar.Lo = 0) and (BytesCompressedSoFar.Hi = 0)) or ((TotalBytesToCompress.Lo = 0) and (TotalBytesToCompress.Hi = 0)) then begin { Optimization(?) and avoid division by zero when TotalBytesToCompress=0 } Data.CompressProgress := 0; end else begin Data.CompressProgress := Trunc((Comp(BytesCompressedSoFar) * ProgressMax) / Comp(TotalBytesToCompress)); { In case one of the files got bigger since we checked the sizes... } if Data.CompressProgress > ProgressMax then Data.CompressProgress := ProgressMax; if CompressionInProgress then begin MillisecondsElapsed := GetTickCount - CompressionStartTick; if MillisecondsElapsed >= Cardinal(1000) then begin X := BytesCompressedSoFar; Mul64(X, 1000); Div64(X, MillisecondsElapsed); if (X.Hi = 0) and (Longint(X.Lo) >= 0) then Data.BytesCompressedPerSecond := X.Lo else Data.BytesCompressedPerSecond := Maxint; if Compare64(BytesCompressedSoFar, TotalBytesToCompress) < 0 then begin { Protect against division by zero } if Data.BytesCompressedPerSecond <> 0 then begin X := TotalBytesToCompress; Dec6464(X, BytesCompressedSoFar); Inc64(X, Data.BytesCompressedPerSecond-1); { round up } Div64(X, Data.BytesCompressedPerSecond); if (X.Hi = 0) and (Longint(X.Lo) >= 0) then Data.SecondsRemaining := X.Lo else Data.SecondsRemaining := Maxint; end; end else begin { In case one of the files got bigger since we checked the sizes... } Data.SecondsRemaining := 0; end; end; end; end; Data.CompressProgressMax := ProgressMax; DoCallback(iscbNotifyIdle, Data); end; type PPreCompilerData = ^TPreCompilerData; TPreCompilerData = record Compiler: TSetupCompiler; InFiles: TStringList; OutLines: TScriptFileLines; AnsiConvertCodePage: Cardinal; CurInLine: String; ErrorSet: Boolean; ErrorMsg, ErrorFilename: String; ErrorLine, ErrorColumn: Integer; LastPrependDirNameResult: String; end; procedure PreErrorProc(CompilerData: TPreprocCompilerData; ErrorMsg: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer); stdcall; forward; function PreLoadFileProc(CompilerData: TPreprocCompilerData; AFilename: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer): TPreprocFileHandle; stdcall; var Data: PPreCompilerData; Filename: String; I: Integer; Lines: TLowFragStringList; F: TTextFileReader; L: String; {$IFDEF UNICODE} S: RawByteString; {$ENDIF} begin Data := CompilerData; Filename := AFilename; if Filename = '' then begin { Reject any attempt by the preprocessor to load the main script } PreErrorProc(CompilerData, 'Invalid parameter passed to PreLoadFileProc', ErrorFilename, ErrorLine, ErrorColumn); Result := -1; Exit; end; Filename := PathExpand(Filename); for I := 0 to Data.InFiles.Count-1 do if PathCompare(Data.InFiles[I], Filename) = 0 then begin Result := I; Exit; end; Lines := TLowFragStringList.Create; try F := TTextFileReader.Create(Filename, fdOpenExisting, faRead, fsRead); try while not F.Eof do begin {$IFDEF UNICODE} if Data.AnsiConvertCodePage <> 0 then begin { Read the ANSI line, then convert it to Unicode. } S := F.ReadAnsiLine; SetCodePage(S, Data.AnsiConvertCodePage, False); L := String(S); end else {$ENDIF} L := F.ReadLine; for I := 1 to Length(L) do if L[I] = #0 then raise Exception.CreateFmt(SCompilerIllegalNullChar, [Lines.Count + 1]); Lines.Add(L); end; finally F.Free; end; except Lines.Free; PreErrorProc(CompilerData, PChar(Format(SCompilerErrorOpeningIncludeFile, [Filename, GetExceptMessage])), ErrorFilename, ErrorLine, ErrorColumn); Result := -1; Exit; end; Result := Data.InFiles.AddObject(Filename, Lines); end; function PreLineInProc(CompilerData: TPreprocCompilerData; FileHandle: TPreprocFileHandle; LineIndex: Integer): PChar; stdcall; var Data: PPreCompilerData; Lines: TLowFragStringList; begin Data := CompilerData; if (FileHandle >= 0) and (FileHandle < Data.InFiles.Count) and (LineIndex >= 0) then begin Lines := TLowFragStringList(Data.InFiles.Objects[FileHandle]); if LineIndex < Lines.Count then begin Data.CurInLine := Lines[LineIndex]; Result := PChar(Data.CurInLine); end else Result := nil; end else begin PreErrorProc(CompilerData, 'Invalid parameter passed to LineInProc', nil, 0, 0); Result := nil; end; end; procedure PreLineOutProc(CompilerData: TPreprocCompilerData; Filename: PChar; LineNumber: Integer; Text: PChar); stdcall; var Data: PPreCompilerData; begin Data := CompilerData; Data.OutLines.Add(Filename, LineNumber, Text); end; procedure PreStatusProc(CompilerData: TPreprocCompilerData; StatusMsg: PChar); stdcall; var Data: PPreCompilerData; begin Data := CompilerData; Data.Compiler.AddStatus(StatusMsg); end; procedure PreErrorProc(CompilerData: TPreprocCompilerData; ErrorMsg: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer); stdcall; var Data: PPreCompilerData; begin Data := CompilerData; if not Data.ErrorSet then begin Data.ErrorMsg := ErrorMsg; Data.ErrorFilename := ErrorFilename; Data.ErrorLine := ErrorLine; Data.ErrorColumn := ErrorColumn; Data.ErrorSet := True; end; end; function PrePrependDirNameProc(CompilerData: TPreprocCompilerData; Filename: PChar; Dir: PChar; ErrorFilename: PChar; ErrorLine: Integer; ErrorColumn: Integer): PChar; stdcall; var Data: PPreCompilerData; begin Data := CompilerData; try Data.LastPrependDirNameResult := Data.Compiler.PrependDirName( PChar(Filename), PChar(Dir)); Result := PChar(Data.LastPrependDirNameResult); except PreErrorProc(CompilerData, PChar(GetExceptMessage), ErrorFilename, ErrorLine, ErrorColumn); Result := nil; end; end; function TSetupCompiler.ReadScriptFile(const Filename: String; const UseCache: Boolean; const AnsiConvertCodePage: Cardinal): TScriptFileLines; function ReadMainScriptLines: TLowFragStringList; var Reset: Boolean; Data: TCompilerCallbackData; begin Result := TLowFragStringList.Create; try Reset := True; while True do begin Data.Reset := Reset; Data.LineRead := nil; DoCallback(iscbReadScript, Data); if Data.LineRead = nil then Break; Result.Add(Data.LineRead); Reset := False; end; except Result.Free; raise; end; end; function SelectPreprocessor(const Lines: TLowFragStringList): TPreprocessScriptProc; var S: String; begin { Don't allow ISPPCC to be used if ISPP.dll is missing } if (PreprocOptionsString <> '') and not Assigned(PreprocessScriptProc) then raise Exception.Create(SCompilerISPPMissing); { By default, only pass the main script through ISPP } if (Filename = '') and Assigned(PreprocessScriptProc) then Result := PreprocessScriptProc else Result := BuiltinPreprocessScript; { Check for (and remove) #preproc override directive on the first line } if Lines.Count > 0 then begin S := Trim(Lines[0]); if S = '#preproc builtin' then begin Lines[0] := ''; Result := BuiltinPreprocessScript; end else if S = '#preproc ispp' then begin Lines[0] := ''; Result := PreprocessScriptProc; if not Assigned(Result) then raise Exception.Create(SCompilerISPPMissing); end; end; end; procedure PreprocessLines(const OutLines: TScriptFileLines); var LSourcePath, LCompilerPath: String; Params: TPreprocessScriptParams; Data: TPreCompilerData; FileLoaded: Boolean; ResultCode, CleanupResultCode, I: Integer; PreProc: TPreprocessScriptProc; begin LSourcePath := OriginalSourceDir; LCompilerPath := CompilerDir; FillChar(Params, SizeOf(Params), 0); Params.Size := SizeOf(Params); Params.InterfaceVersion := 1; Params.CompilerBinVersion := SetupBinVersion; Params.Filename := PChar(Filename); Params.SourcePath := PChar(LSourcePath); Params.CompilerPath := PChar(LCompilerPath); Params.Options := PChar(PreprocOptionsString); Params.CompilerData := @Data; Params.LoadFileProc := PreLoadFileProc; Params.LineInProc := PreLineInProc; Params.LineOutProc := PreLineOutProc; Params.StatusProc := PreStatusProc; Params.ErrorProc := PreErrorProc; Params.PrependDirNameProc := PrePrependDirNameProc; FillChar(Data, SizeOf(Data), 0); Data.Compiler := Self; Data.OutLines := OutLines; Data.AnsiConvertCodePage := AnsiConvertCodePage; Data.InFiles := TStringList.Create; try if Filename = '' then begin Data.InFiles.AddObject('', ReadMainScriptLines); FileLoaded := True; end else FileLoaded := (PreLoadFileProc(Params.CompilerData, PChar(Filename), PChar(LineFilename), LineNumber, 0) = 0); ResultCode := ispePreprocessError; if FileLoaded then begin PreProc := SelectPreprocessor(TLowFragStringList(Data.InFiles.Objects[0])); ResultCode := PreProc(Params); if Filename = '' then begin { Defer cleanup of main script until after compilation } PreprocCleanupProcData := Params.PreprocCleanupProcData; PreprocCleanupProc := Params.PreprocCleanupProc; end else if Assigned(Params.PreprocCleanupProc) then begin CleanupResultCode := Params.PreprocCleanupProc(Params.PreprocCleanupProcData); if CleanupResultCode <> 0 then AbortCompileFmt('Preprocessor cleanup function for "%s" failed with code %d', [Filename, CleanupResultCode]); end; end; if Data.ErrorSet then begin LineFilename := Data.ErrorFilename; LineNumber := Data.ErrorLine; if Data.ErrorColumn > 0 then { hack for now... } Insert(Format('Column %d:' + SNewLine, [Data.ErrorColumn]), Data.ErrorMsg, 1); AbortCompile(Data.ErrorMsg); end; case ResultCode of ispeSuccess: ; ispeSilentAbort: Abort; else AbortCompileFmt('Preprocess function failed with code %d', [ResultCode]); end; finally for I := Data.InFiles.Count-1 downto 0 do Data.InFiles.Objects[I].Free; Data.InFiles.Free; end; end; var I: Integer; Lines: TScriptFileLines; begin if UseCache then for I := 0 to ScriptFiles.Count-1 do if PathCompare(ScriptFiles[I], Filename) = 0 then begin Result := TScriptFileLines(ScriptFiles.Objects[I]); Exit; end; Lines := TScriptFileLines.Create; try PreprocessLines(Lines); except Lines.Free; raise; end; if UseCache then ScriptFiles.AddObject(Filename, Lines); Result := Lines; end; procedure TSetupCompiler.EnumIniSection(const EnumProc: TEnumIniSectionProc; const SectionName: String; const Ext: Integer; const Verbose, SkipBlankLines: Boolean; const Filename: String; const AnsiLanguageFile, Pre: Boolean); var FoundSection: Boolean; LastSection: String; procedure DoFile(Filename: String); const PreCodePage = 1252; var UseCache: Boolean; AnsiConvertCodePage: Cardinal; Lines: TScriptFileLines; SaveLineFilename, L: String; SaveLineNumber, LineIndex, I: Integer; Line: PScriptFileLine; begin if Filename <> '' then Filename := PathExpand(PrependSourceDirName(Filename)); UseCache := not (AnsiLanguageFile and Pre); AnsiConvertCodePage := 0; {$IFDEF UNICODE} { During a Pre pass on an .isl file, use code page 1252 for translation. Previously, the system code page was used, but on DBCS that resulted in "Illegal null character" errors on files containing byte sequences that do not form valid lead/trail byte combinations (i.e. most languages). } if AnsiLanguageFile and Pre then begin if not IsValidCodePage(PreCodePage) then { just in case } AbortCompileFmt('Code page %u unsupported', [PreCodePage]); AnsiConvertCodePage := PreCodePage; end; { Ext = LangIndex, except for Default.isl for which its -2 when default messages are read but no special conversion is needed for those. } if AnsiLanguageFile and (Ext >= 0) and not Pre then begin AnsiConvertCodePage := TPreLangData(PreLangDataList[Ext]).LanguageCodePage; if AnsiConvertCodePage <> 0 then AddStatus(Format(SCompilerStatusConvertCodePage , [AnsiConvertCodePage])); end; {$ENDIF} Lines := ReadScriptFile(Filename, UseCache, AnsiConvertCodePage); try SaveLineFilename := LineFilename; SaveLineNumber := LineNumber; for LineIndex := 0 to Lines.Count-1 do begin Line := Lines[LineIndex]; LineFilename := Line.LineFilename; LineNumber := Line.LineNumber; L := Trim(Line.LineText); { Check for blank lines or comments } if (not FoundSection or SkipBlankLines) and ((L = '') or (L[1] = ';')) then Continue; if (L <> '') and (L[1] = '[') then begin { Section tag } I := Pos(']', L); if (I < 3) or (I <> Length(L)) then AbortCompileOnLine(SCompilerSectionTagInvalid); L := Copy(L, 2, I-2); if L[1] = '/' then begin L := Copy(L, 2, Maxint); if (LastSection = '') or (CompareText(L, LastSection) <> 0) then AbortCompileOnLineFmt(SCompilerSectionBadEndTag, [L]); FoundSection := False; LastSection := ''; end else begin FoundSection := (CompareText(L, SectionName) = 0); LastSection := L; end; end else begin if not FoundSection then begin if LastSection = '' then AbortCompileOnLine(SCompilerTextNotInSection); Continue; { not on the right section } end; if Verbose then begin if ParseFilename = '' then AddStatus(Format(SCompilerStatusParsingSectionLine, [SectionName, LineNumber])) else AddStatus(Format(SCompilerStatusParsingSectionLineFile, [SectionName, LineNumber, ParseFilename])); end; EnumProc(PChar(Line.LineText), Ext); end; end; LineFilename := SaveLineFilename; LineNumber := SaveLineNumber; finally if not UseCache then Lines.Free; end; end; begin FoundSection := False; LastSection := ''; DoFile(Filename); end; procedure TSetupCompiler.ExtractParameters(S: PChar; const ParamInfo: array of TParamInfo; var ParamValues: array of TParamValue); function GetParamIndex(const AName: String): Integer; var I: Integer; begin for I := 0 to High(ParamInfo) do if CompareText(ParamInfo[I].Name, AName) = 0 then begin Result := I; if ParamValues[I].Found then AbortCompileParamError(SCompilerParamDuplicated, ParamInfo[I].Name); ParamValues[I].Found := True; Exit; end; { Unknown parameter } AbortCompileOnLineFmt(SCompilerParamUnknownParam, [AName]); Result := -1; end; var I, ParamIndex: Integer; ParamName, Data: String; begin for I := 0 to High(ParamValues) do begin ParamValues[I].Found := False; ParamValues[I].Data := ''; end; while True do begin { Parameter name } SkipWhitespace(S); if S^ = #0 then Break; ParamName := ExtractWords(S, ':'); ParamIndex := GetParamIndex(ParamName); if S^ <> ':' then AbortCompileOnLineFmt(SCompilerParamHasNoValue, [ParamName]); Inc(S); { Parameter value } SkipWhitespace(S); if S^ <> '"' then begin Data := ExtractWords(S, ';'); if Pos('"', Data) <> 0 then AbortCompileOnLineFmt(SCompilerParamQuoteError, [ParamName]); if S^ = ';' then Inc(S); end else begin Inc(S); Data := ''; while True do begin if S^ = #0 then AbortCompileOnLineFmt(SCompilerParamMissingClosingQuote, [ParamName]); if S^ = '"' then begin Inc(S); if S^ <> '"' then Break; end; Data := Data + S^; Inc(S); end; SkipWhitespace(S); case S^ of #0 : ; ';': Inc(S); else AbortCompileOnLineFmt(SCompilerParamQuoteError, [ParamName]); end; end; { Assign the data } if (piNoEmpty in ParamInfo[ParamIndex].Flags) and (Data = '') then AbortCompileParamError(SCompilerParamEmpty2, ParamInfo[ParamIndex].Name); if (piNoQuotes in ParamInfo[ParamIndex].Flags) and (Pos('"', Data) <> 0) then AbortCompileParamError(SCompilerParamNoQuotes2, ParamInfo[ParamIndex].Name); ParamValues[ParamIndex].Data := Data; end; { Check for missing required parameters } for I := 0 to High(ParamInfo) do begin if (piRequired in ParamInfo[I].Flags) and not ParamValues[I].Found then AbortCompileParamError(SCompilerParamNotSpecified, ParamInfo[I].Name); end; end; procedure TSetupCompiler.AddStatus(const S: String); var Data: TCompilerCallbackData; begin Data.StatusMsg := PChar(S); DoCallback(iscbNotifyStatus, Data); end; procedure TSetupCompiler.AddStatusFmt(const Msg: String; const Args: array of const); begin AddStatus(Format(Msg, Args)); end; procedure TSetupCompiler.AbortCompile(const Msg: String); begin raise EISCompileError.Create(Msg); end; procedure TSetupCompiler.AbortCompileFmt(const Msg: String; const Args: array of const); begin AbortCompile(Format(Msg, Args)); end; procedure TSetupCompiler.AbortCompileOnLine(const Msg: String); { AbortCompileOnLine is now equivalent to AbortCompile } begin AbortCompile(Msg); end; procedure TSetupCompiler.AbortCompileOnLineFmt(const Msg: String; const Args: array of const); begin AbortCompileOnLine(Format(Msg, Args)); end; procedure TSetupCompiler.AbortCompileParamError(const Msg, ParamName: String); begin AbortCompileOnLineFmt(Msg, [ParamName]); end; function TSetupCompiler.PrependDirName(const Filename, Dir: String): String; function GetShellFolderPathCached(const FolderID: Integer; var CachedDir: String): String; var S: String; begin if CachedDir = '' then begin S := GetShellFolderPath(FolderID); if S = '' then AbortCompileFmt('Failed to get shell folder path (0x%.4x)', [FolderID]); S := AddBackslash(PathExpand(S)); CachedDir := S; end; Result := CachedDir; end; const CSIDL_PERSONAL = $0005; var P: Integer; Prefix: String; begin P := PathPos(':', Filename); if (P = 0) or ((P = 2) and CharInSet(UpCase(Filename[1]), ['A'..'Z'])) then begin if (Filename = '') or not IsRelativePath(Filename) then Result := Filename else Result := Dir + Filename; end else begin Prefix := Copy(Filename, 1, P-1); if Prefix = 'compiler' then Result := CompilerDir + Copy(Filename, P+1, Maxint) else if Prefix = 'userdocs' then Result := GetShellFolderPathCached(CSIDL_PERSONAL, CachedUserDocsDir) + Copy(Filename, P+1, Maxint) else begin AbortCompileFmt(SCompilerUnknownFilenamePrefix, [Copy(Filename, 1, P)]); Result := Filename; { avoid warning } end; end; end; function TSetupCompiler.PrependSourceDirName(const Filename: String): String; begin Result := PrependDirName(Filename, SourceDir); end; function TSetupCompiler.CheckConst(const S: String; const MinVersion: TSetupVersionData; const AllowedConsts: TAllowedConsts): Boolean; { Returns True if S contains constants. Aborts compile if they are invalid. } function CheckEnvConst(C: String): Boolean; { based on ExpandEnvConst in Main.pas } var I: Integer; VarName, Default: String; begin Delete(C, 1, 1); I := ConstPos('|', C); { check for 'default' value } if I = 0 then I := Length(C)+1; VarName := Copy(C, 1, I-1); Default := Copy(C, I+1, Maxint); if ConvertConstPercentStr(VarName) and ConvertConstPercentStr(Default) then begin CheckConst(VarName, MinVersion, AllowedConsts); CheckConst(Default, MinVersion, AllowedConsts); Result := True; Exit; end; { it will only reach here if there was a parsing error } Result := False; end; function CheckRegConst(C: String): Boolean; { based on ExpandRegConst in Main.pas } type TKeyNameConst = packed record KeyName: String; KeyConst: HKEY; end; const KeyNameConsts: array[0..4] of TKeyNameConst = ( (KeyName: 'HKCR'; KeyConst: HKEY_CLASSES_ROOT), (KeyName: 'HKCU'; KeyConst: HKEY_CURRENT_USER), (KeyName: 'HKLM'; KeyConst: HKEY_LOCAL_MACHINE), (KeyName: 'HKU'; KeyConst: HKEY_USERS), (KeyName: 'HKCC'; KeyConst: HKEY_CURRENT_CONFIG)); var Z, Subkey, Value, Default: String; I, J, L: Integer; RootKey: HKEY; begin Delete(C, 1, 4); { skip past 'reg:' } I := ConstPos('\', C); if I <> 0 then begin Z := Copy(C, 1, I-1); if Z <> '' then begin L := Length(Z); if L >= 2 then begin { Check for '32' or '64' suffix } if ((Z[L-1] = '3') and (Z[L] = '2')) or ((Z[L-1] = '6') and (Z[L] = '4')) then SetLength(Z, L-2); end; RootKey := 0; for J := Low(KeyNameConsts) to High(KeyNameConsts) do if CompareText(KeyNameConsts[J].KeyName, Z) = 0 then begin RootKey := KeyNameConsts[J].KeyConst; Break; end; if RootKey <> 0 then begin Z := Copy(C, I+1, Maxint); I := ConstPos('|', Z); { check for a 'default' data } if I = 0 then I := Length(Z)+1; Default := Copy(Z, I+1, Maxint); SetLength(Z, I-1); I := ConstPos(',', Z); { comma separates subkey and value } if I <> 0 then begin Subkey := Copy(Z, 1, I-1); Value := Copy(Z, I+1, Maxint); if ConvertConstPercentStr(Subkey) and ConvertConstPercentStr(Value) and ConvertConstPercentStr(Default) then begin CheckConst(Subkey, MinVersion, AllowedConsts); CheckConst(Value, MinVersion, AllowedConsts); CheckConst(Default, MinVersion, AllowedConsts); Result := True; Exit; end; end; end; end; end; { it will only reach here if there was a parsing error } Result := False; end; function CheckIniConst(C: String): Boolean; { based on ExpandIniConst in Main.pas } var Z, Filename, Section, Key, Default: String; I: Integer; begin Delete(C, 1, 4); { skip past 'ini:' } I := ConstPos(',', C); if I <> 0 then begin Z := Copy(C, 1, I-1); if Z <> '' then begin Filename := Z; Z := Copy(C, I+1, Maxint); I := ConstPos('|', Z); { check for a 'default' data } if I = 0 then I := Length(Z)+1; Default := Copy(Z, I+1, Maxint); SetLength(Z, I-1); I := ConstPos(',', Z); { comma separates section and key } if I <> 0 then begin Section := Copy(Z, 1, I-1); Key := Copy(Z, I+1, Maxint); if ConvertConstPercentStr(Filename) and ConvertConstPercentStr(Section) and ConvertConstPercentStr(Key) and ConvertConstPercentStr(Default) then begin CheckConst(Filename, MinVersion, AllowedConsts); CheckConst(Section, MinVersion, AllowedConsts); CheckConst(Key, MinVersion, AllowedConsts); CheckConst(Default, MinVersion, AllowedConsts); Result := True; Exit; end; end; end; end; { it will only reach here if there was a parsing error } Result := False; end; function CheckParamConst(C: String): Boolean; var Z, Param, Default: String; I: Integer; begin Delete(C, 1, 6); { skip past 'param:' } Z := C; I := ConstPos('|', Z); { check for a 'default' data } if I = 0 then I := Length(Z)+1; Default := Copy(Z, I+1, Maxint); SetLength(Z, I-1); Param := Z; if ConvertConstPercentStr(Param) and ConvertConstPercentStr(Default) then begin CheckConst(Param, MinVersion, AllowedConsts); CheckConst(Default, MinVersion, AllowedConsts); Result := True; Exit; end; { it will only reach here if there was a parsing error } Result := False; end; function CheckCodeConst(C: String): Boolean; var Z, ScriptFunc, Param: String; I: Integer; begin Delete(C, 1, 5); { skip past 'code:' } Z := C; I := ConstPos('|', Z); { check for optional parameter } if I = 0 then I := Length(Z)+1; Param := Copy(Z, I+1, Maxint); SetLength(Z, I-1); ScriptFunc := Z; if ConvertConstPercentStr(ScriptFunc) and ConvertConstPercentStr(Param) then begin CheckConst(Param, MinVersion, AllowedConsts); CodeCompiler.AddExport(ScriptFunc, 'String @String', True, ParseFileName, LineNumber); Result := True; Exit; end; { it will only reach here if there was a parsing error } Result := False; end; function CheckDriveConst(C: String): Boolean; begin Delete(C, 1, 6); { skip past 'drive:' } if ConvertConstPercentStr(C) then begin CheckConst(C, MinVersion, AllowedConsts); Result := True; Exit; end; { it will only reach here if there was a parsing error } Result := False; end; function CheckCustomMessageConst(C: String): Boolean; var MsgName, Arg: String; I, ArgCount: Integer; Found: Boolean; LineInfo: TLineInfo; begin Delete(C, 1, 3); { skip past 'cm:' } I := ConstPos(',', C); if I = 0 then MsgName := C else MsgName := Copy(C, 1, I-1); { Check each argument } ArgCount := 0; while I > 0 do begin if ArgCount >= 9 then begin { Can't have more than 9 arguments (%1 through %9) } Result := False; Exit; end; Delete(C, 1, I); I := ConstPos(',', C); if I = 0 then Arg := C else Arg := Copy(C, 1, I-1); if not ConvertConstPercentStr(Arg) then begin Result := False; Exit; end; CheckConst(Arg, MinVersion, AllowedConsts); Inc(ArgCount); end; Found := False; for I := 0 to ExpectedCustomMessageNames.Count-1 do begin if CompareText(ExpectedCustomMessageNames[I], MsgName) = 0 then begin Found := True; Break; end; end; if not Found then begin LineInfo := TLineInfo.Create; LineInfo.FileName := ParseFileName; LineInfo.FileLineNumber := LineNumber; ExpectedCustomMessageNames.AddObject(MsgName, LineInfo); end; Result := True; end; const Consts: array[0..38] of String = ( 'src', 'srcexe', 'tmp', 'app', 'win', 'sys', 'sd', 'groupname', 'fonts', 'hwnd', 'pf', 'pf32', 'pf64', 'cf', 'cf32', 'cf64', 'computername', 'dao', 'cmd', 'username', 'wizardhwnd', 'sysuserinfoname', 'sysuserinfoorg', 'userinfoname', 'userinfoorg', 'userinfoserial', 'uninstallexe', 'language', 'syswow64', 'log', 'dotnet11', 'dotnet20', 'dotnet2032', 'dotnet2064', 'dotnet40', 'dotnet4032', 'dotnet4064', 'userpf', 'usercf'); ShellFolderConsts: array[0..18] of String = ( 'group', 'userdesktop', 'userstartmenu', 'userprograms', 'userstartup', 'commondesktop', 'commonstartmenu', 'commonprograms', 'commonstartup', 'sendto', 'userappdata', 'userdocs', 'commonappdata', 'commondocs', 'usertemplates', 'commontemplates', 'localappdata', 'userfavorites', 'commonfavorites'); AllowedConstsNames: array[TAllowedConst] of String = ( 'olddata', 'break'); var I, Start, K: Integer; C: TAllowedConst; Cnst: String; label 1; begin Result := False; I := 1; while I <= Length(S) do begin if S[I] = '{' then begin if (I < Length(S)) and (S[I+1] = '{') then Inc(I) else begin Result := True; Start := I; { Find the closing brace, skipping over any embedded constants } I := SkipPastConst(S, I); if I = 0 then { unclosed constant? } AbortCompileOnLineFmt(SCompilerUnterminatedConst, [Copy(S, Start+1, Maxint)]); Dec(I); { 'I' now points to the closing brace } { Now check the constant } Cnst := Copy(S, Start+1, I-(Start+1)); if Cnst <> '' then begin if Cnst = '\' then goto 1; if Cnst[1] = '%' then begin if not CheckEnvConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadEnvConst, [Cnst]); goto 1; end; if Copy(Cnst, 1, 4) = 'reg:' then begin if not CheckRegConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadRegConst, [Cnst]); goto 1; end; if Copy(Cnst, 1, 4) = 'ini:' then begin if not CheckIniConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadIniConst, [Cnst]); goto 1; end; if Copy(Cnst, 1, 6) = 'param:' then begin if not CheckParamConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadParamConst, [Cnst]); goto 1; end; if Copy(Cnst, 1, 5) = 'code:' then begin if not CheckCodeConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadCodeConst, [Cnst]); goto 1; end; if Copy(Cnst, 1, 6) = 'drive:' then begin if not CheckDriveConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadDriveConst, [Cnst]); goto 1; end; if Copy(Cnst, 1, 3) = 'cm:' then begin if not CheckCustomMessageConst(Cnst) then AbortCompileOnLineFmt(SCompilerBadCustomMessageConst, [Cnst]); goto 1; end; for K := Low(Consts) to High(Consts) do if Cnst = Consts[K] then goto 1; for K := Low(ShellFolderConsts) to High(ShellFolderConsts) do if Cnst = ShellFolderConsts[K] then goto 1; for C := Low(C) to High(C) do if Cnst = AllowedConstsNames[C] then begin if not(C in AllowedConsts) then AbortCompileOnLineFmt(SCompilerConstCannotUse, [Cnst]); goto 1; end; end; AbortCompileOnLineFmt(SCompilerUnknownConst, [Cnst]); 1:{ Constant is OK } end; {$IFDEF UNICODE} end; {$ELSE} end else if S[I] in CompilerLeadBytes then Inc(I); {$ENDIF} Inc(I); end; end; function TSetupCompiler.EvalCheckOrInstallIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; var IsCheck: Boolean; Decl: String; I: Integer; begin IsCheck := Boolean(Sender.Tag); if IsCheck then Decl := 'Boolean' else Decl := '0'; for I := Low(Parameters) to High(Parameters) do begin if Parameters[I].VType = {$IFDEF UNICODE} vtUnicodeString {$ELSE} vtAnsiString {$ENDIF} then Decl := Decl + ' @String' else if Parameters[I].VType = vtInteger then Decl := Decl + ' @LongInt' else if Parameters[I].VType = vtBoolean then Decl := Decl + ' @Boolean' else raise Exception.Create('Internal Error: unknown parameter type'); end; CodeCompiler.AddExport(Name, Decl, True, ParseFileName, LineNumber); Result := True; { Result doesn't matter } end; procedure TSetupCompiler.CheckCheckOrInstall(const ParamName, ParamData: String; const Kind: TCheckOrInstallKind); var SimpleExpression: TSimpleExpression; IsCheck, BoolResult: Boolean; begin if ParamData <> '' then begin if (Kind <> cikDirectiveCheck) or not TryStrToBoolean(ParamData, BoolResult) then begin IsCheck := Kind in [cikCheck, cikDirectiveCheck]; { Check the expression in ParamData and add exports while evaluating. Use Lazy checking to make sure everything is evaluated. } try SimpleExpression := TSimpleExpression.Create; try SimpleExpression.Lazy := False; SimpleExpression.Expression := ParamData; SimpleExpression.OnEvalIdentifier := EvalCheckOrInstallIdentifier; SimpleExpression.SilentOrAllowed := False; SimpleExpression.SingleIdentifierMode := not IsCheck; SimpleExpression.ParametersAllowed := True; SimpleExpression.Tag := Integer(IsCheck); SimpleExpression.Eval; finally SimpleExpression.Free; end; except AbortCompileOnLineFmt(SCompilerExpressionError, [ParamName, GetExceptMessage]); end; end; end else begin if Kind = cikDirectiveCheck then AbortCompileOnLineFmt(SCompilerEntryInvalid2, ['Setup', ParamName]); end; end; function ExtractStr(var S: String; const Separator: Char): String; var I: Integer; begin repeat I := PathPos(Separator, S); if I = 0 then I := Length(S)+1; Result := Trim(Copy(S, 1, I-1)); S := Trim(Copy(S, I+1, Maxint)); until (Result <> '') or (S = ''); end; function ExtractFlag(var S: String; const FlagStrs: array of PChar): Integer; var I: Integer; F: String; begin F := ExtractStr(S, ' '); if F = '' then begin Result := -2; Exit; end; Result := -1; for I := 0 to High(FlagStrs) do if StrIComp(FlagStrs[I], PChar(F)) = 0 then begin Result := I; Break; end; end; function ExtractType(var S: String; const TypeEntries: TList): Integer; var I: Integer; F: String; begin F := ExtractStr(S, ' '); if F = '' then begin Result := -2; Exit; end; Result := -1; if TypeEntries.Count <> 0 then begin for I := 0 to TypeEntries.Count-1 do if CompareText(PSetupTypeEntry(TypeEntries[I]).Name, F) = 0 then begin Result := I; Break; end; end else begin for I := 0 to High(DefaultTypeEntryNames) do if StrIComp(DefaultTypeEntryNames[I], PChar(F)) = 0 then begin Result := I; Break; end; end; end; function ExtractLangIndex(SetupCompiler: TSetupCompiler; var S: String; const LanguageEntryIndex: Integer; const Pre: Boolean): Integer; var I: Integer; begin if LanguageEntryIndex = -1 then begin { Message in the main script } I := Pos('.', S); if I = 0 then begin { No '.'; apply to all languages } Result := -1; end else begin { Apply to specified language } Result := SetupCompiler.FindLangEntryIndexByName(Copy(S, 1, I-1), Pre); S := Copy(S, I+1, Maxint); end; end else begin { Inside a language file } if Pos('.', S) <> 0 then SetupCompiler.AbortCompileOnLine(SCompilerCantSpecifyLanguage); Result := LanguageEntryIndex; end; end; procedure AddToCommaText(var CommaText: String; const S: String); begin if CommaText <> '' then CommaText := CommaText + ','; CommaText := CommaText + S; end; function TSetupCompiler.EvalComponentIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; var Found: Boolean; ComponentEntry: PSetupComponentEntry; I: Integer; begin Found := False; for I := 0 to ComponentEntries.Count-1 do begin ComponentEntry := PSetupComponentEntry(ComponentEntries[I]); if CompareText(ComponentEntry.Name, Name) = 0 then begin ComponentEntry.Used := True; Found := True; { Don't Break; there may be multiple components with the same name } end; end; if not Found then raise Exception.CreateFmt(SCompilerParamUnknownComponent, [ParamCommonComponents]); Result := True; { Result doesn't matter } end; function TSetupCompiler.EvalTaskIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; var Found: Boolean; TaskEntry: PSetupTaskEntry; I: Integer; begin Found := False; for I := 0 to TaskEntries.Count-1 do begin TaskEntry := PSetupTaskEntry(TaskEntries[I]); if CompareText(TaskEntry.Name, Name) = 0 then begin TaskEntry.Used := True; Found := True; { Don't Break; there may be multiple tasks with the same name } end; end; if not Found then raise Exception.CreateFmt(SCompilerParamUnknownTask, [ParamCommonTasks]); Result := True; { Result doesn't matter } end; function TSetupCompiler.EvalLanguageIdentifier(Sender: TSimpleExpression; const Name: String; const Parameters: array of const): Boolean; var LanguageEntry: PSetupLanguageEntry; I: Integer; begin for I := 0 to LanguageEntries.Count-1 do begin LanguageEntry := PSetupLanguageEntry(LanguageEntries[I]); if CompareText(LanguageEntry.Name, Name) = 0 then begin Result := True; { Result doesn't matter } Exit; end; end; raise Exception.CreateFmt(SCompilerParamUnknownLanguage, [ParamCommonLanguages]); end; procedure TSetupCompiler.ProcessExpressionParameter(const ParamName, ParamData: String; OnEvalIdentifier: TSimpleExpressionOnEvalIdentifier; SlashConvert: Boolean; var ProcessedParamData: String); var SimpleExpression: TSimpleExpression; begin ProcessedParamData := ParamData; if ProcessedParamData <> '' then begin if SlashConvert then StringChange(ProcessedParamData, '/', '\'); { Check the expression in ParamData and set the Used properties while evaluating. Use non-Lazy checking to make sure everything is evaluated. } try SimpleExpression := TSimpleExpression.Create; try SimpleExpression.Lazy := False; SimpleExpression.Expression := ProcessedParamData; SimpleExpression.OnEvalIdentifier := OnEvalIdentifier; SimpleExpression.SilentOrAllowed := True; SimpleExpression.SingleIdentifierMode := False; SimpleExpression.ParametersAllowed := False; SimpleExpression.Eval; finally SimpleExpression.Free; end; except AbortCompileOnLineFmt(SCompilerExpressionError, [ParamName, GetExceptMessage]); end; end; end; procedure TSetupCompiler.ProcessWildcardsParameter(const ParamData: String; const AWildcards: TStringList; const TooLongMsg: String); var S, AWildcard: String; begin S := PathLowercase(ParamData); while True do begin AWildcard := ExtractStr(S, ','); if AWildcard = '' then Break; { Impose a reasonable limit on the length of the string so that WildcardMatch can't overflow the stack } if Length(AWildcard) >= MAX_PATH then AbortCompileOnLine(TooLongMsg); AWildcards.Add(AWildcard); end; end; function StrToVersionInfoVersionNumber(const S: String; var Version: TFileVersionNumbers): Boolean; function SplitNextNumber(var Z: String): Word; var I, N: Integer; begin if Trim(Z) <> '' then begin I := Pos('.', Z); if I = 0 then I := Length(Z)+1; N := StrToInt(Trim(Copy(Z, 1, I-1))); if (N < Low(Word)) or (N > High(Word)) then Abort; Result := N; Z := Copy(Z, I+1, Maxint); end else Result := 0; end; var Z: String; W: Word; begin try Z := S; W := SplitNextNumber(Z); Version.MS := (DWord(W) shl 16) or SplitNextNumber(Z); W := SplitNextNumber(Z); Version.LS := (DWord(W) shl 16) or SplitNextNumber(Z); Result := True; except Result := False; end; end; procedure TSetupCompiler.ProcessMinVersionParameter(const ParamValue: TParamValue; var AMinVersion: TSetupVersionData); begin if ParamValue.Found then if not StrToVersionNumbers(ParamValue.Data, AMinVersion) then AbortCompileParamError(SCompilerParamInvalid2, ParamCommonMinVersion); end; procedure TSetupCompiler.ProcessOnlyBelowVersionParameter(const ParamValue: TParamValue; var AOnlyBelowVersion: TSetupVersionData); begin if ParamValue.Found then if not StrToVersionNumbers(ParamValue.Data, AOnlyBelowVersion) then AbortCompileParamError(SCompilerParamInvalid2, ParamCommonOnlyBelowVersion); end; procedure TSetupCompiler.ProcessPermissionsParameter(ParamData: String; const AccessMasks: array of TNameAndAccessMask; var PermissionsEntry: Smallint); procedure GetSidFromName(const AName: String; var ASid: TGrantPermissionSid); type TKnownSid = record Name: String; Sid: TGrantPermissionSid; end; const SECURITY_WORLD_SID_AUTHORITY = 1; SECURITY_WORLD_RID = $00000000; SECURITY_NT_AUTHORITY = 5; SECURITY_AUTHENTICATED_USER_RID = $0000000B; SECURITY_LOCAL_SYSTEM_RID = $00000012; SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; DOMAIN_ALIAS_RID_USERS = $00000221; DOMAIN_ALIAS_RID_POWER_USERS = $00000223; KnownSids: array[0..5] of TKnownSid = ( (Name: 'admins'; Sid: (Authority: (Value: (0, 0, 0, 0, 0, SECURITY_NT_AUTHORITY)); SubAuthCount: 2; SubAuth: (SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS))), (Name: 'authusers'; Sid: (Authority: (Value: (0, 0, 0, 0, 0, SECURITY_NT_AUTHORITY)); SubAuthCount: 1; SubAuth: (SECURITY_AUTHENTICATED_USER_RID, 0))), (Name: 'everyone'; Sid: (Authority: (Value: (0, 0, 0, 0, 0, SECURITY_WORLD_SID_AUTHORITY)); SubAuthCount: 1; SubAuth: (SECURITY_WORLD_RID, 0))), (Name: 'powerusers'; Sid: (Authority: (Value: (0, 0, 0, 0, 0, SECURITY_NT_AUTHORITY)); SubAuthCount: 2; SubAuth: (SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS))), (Name: 'system'; Sid: (Authority: (Value: (0, 0, 0, 0, 0, SECURITY_NT_AUTHORITY)); SubAuthCount: 1; SubAuth: (SECURITY_LOCAL_SYSTEM_RID, 0))), (Name: 'users'; Sid: (Authority: (Value: (0, 0, 0, 0, 0, SECURITY_NT_AUTHORITY)); SubAuthCount: 2; SubAuth: (SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_USERS))) ); var I: Integer; begin for I := Low(KnownSids) to High(KnownSids) do if CompareText(AName, KnownSids[I].Name) = 0 then begin ASid := KnownSids[I].Sid; Exit; end; AbortCompileOnLineFmt(SCompilerPermissionsUnknownSid, [AName]); end; procedure GetAccessMaskFromName(const AName: String; var AAccessMask: DWORD); var I: Integer; begin for I := Low(AccessMasks) to High(AccessMasks) do if CompareText(AName, AccessMasks[I].Name) = 0 then begin AAccessMask := AccessMasks[I].Mask; Exit; end; AbortCompileOnLineFmt(SCompilerPermissionsUnknownMask, [AName]); end; var Perms, E: AnsiString; S: String; PermsCount, P, I: Integer; Entry: TGrantPermissionEntry; NewPermissionEntry: PSetupPermissionEntry; begin { Parse } PermsCount := 0; while True do begin S := ExtractStr(ParamData, ' '); if S = '' then Break; P := Pos('-', S); if P = 0 then AbortCompileOnLineFmt(SCompilerPermissionsInvalidValue, [S]); FillChar(Entry, SizeOf(Entry), 0); GetSidFromName(Copy(S, 1, P-1), Entry.Sid); GetAccessMaskFromName(Copy(S, P+1, Maxint), Entry.AccessMask); SetString(E, PAnsiChar(@Entry), SizeOf(Entry)); Perms := Perms + E; Inc(PermsCount); if PermsCount > MaxGrantPermissionEntries then AbortCompileOnLineFmt(SCompilerPermissionsValueLimitExceeded, [MaxGrantPermissionEntries]); end; if Perms = '' then begin { No permissions } PermissionsEntry := -1; end else begin { See if there's already an identical permissions entry } for I := 0 to PermissionEntries.Count-1 do if PSetupPermissionEntry(PermissionEntries[I]).Permissions = Perms then begin PermissionsEntry := I; Exit; end; { If not, create a new one } PermissionEntries.Expand; NewPermissionEntry := AllocMem(SizeOf(NewPermissionEntry^)); NewPermissionEntry.Permissions := Perms; I := PermissionEntries.Add(NewPermissionEntry); if I > High(PermissionsEntry) then AbortCompileOnLine(SCompilerPermissionsTooMany); PermissionsEntry := I; end; end; procedure TSetupCompiler.ReadTextFile(const Filename: String; const LangIndex: Integer; var Text: AnsiString); var F: TFile; Size: Cardinal; {$IFDEF UNICODE} UnicodeFile, RTFFile: Boolean; AnsiConvertCodePage: Integer; S: RawByteString; U: String; {$ENDIF} begin try F := TFile.Create(Filename, fdOpenExisting, faRead, fsRead); try Size := F.Size.Lo; {$IFDEF UNICODE} SetLength(S, Size); F.ReadBuffer(S[1], Size); UnicodeFile := ((Size >= 2) and (PWord(Pointer(S))^ = $FEFF)) or ((Size >= 3) and (S[1] = #$EF) and (S[2] = #$BB) and (S[3] = #$BF)); RTFFile := Copy(S, 1, 6) = '{\rtf1'; if not UnicodeFile and not RTFFile and (LangIndex >= 0) then begin AnsiConvertCodePage := TPreLangData(PreLangDataList[LangIndex]).LanguageCodePage; if AnsiConvertCodePage <> 0 then begin AddStatus(Format(SCompilerStatusConvertCodePage , [AnsiConvertCodePage])); { Convert the ANSI text to Unicode. } SetCodePage(S, AnsiConvertCodePage, False); U := String(S); { Store the Unicode text in Text with a UTF16 BOM. } Size := Length(U)*SizeOf(U[1]); SetLength(Text, Size+2); PWord(Pointer(Text))^ := $FEFF; Move(U[1], Text[3], Size); end else Text := S; end else Text := S; {$ELSE} SetLength(Text, Size); F.ReadBuffer(Text[1], Size); {$ENDIF} finally F.Free; end; except raise Exception.CreateFmt(SCompilerReadError, [Filename, GetExceptMessage]); end; end; procedure TSetupCompiler.SeparateDirective(const Line: PChar; var Key, Value: String); var P: PChar; begin Key := ''; Value := ''; P := Line; SkipWhitespace(P); if P^ <> #0 then begin Key := ExtractWords(P, '='); if Key = '' then AbortCompileOnLine(SCompilerDirectiveNameMissing); if P^ <> '=' then AbortCompileOnLineFmt(SCompilerDirectiveHasNoValue, [Key]); Inc(P); SkipWhitespace(P); Value := ExtractWords(P, #0); { If Value is surrounded in quotes, remove them. Note that unlike parameter values, for backward compatibility we don't require embedded quotes to be doubled, nor do we require surrounding quotes when there's a quote in the middle of the value. } if (Length(Value) >= 2) and (Value[1] = '"') and (Value[Length(Value)] = '"') then Value := Copy(Value, 2, Length(Value)-2); end; end; procedure TSetupCompiler.EnumSetup(const Line: PChar; const Ext: Integer); var KeyName, Value: String; I: Integer; Directive: TSetupSectionDirectives; procedure Invalid; begin AbortCompileOnLineFmt(SCompilerEntryInvalid2, ['Setup', KeyName]); end; function StrToBool(const S: String): Boolean; begin Result := False; if not TryStrToBoolean(S, Result) then Invalid; end; function StrToIntRange(const S: String; const AMin, AMax: Integer): Integer; var E: Integer; begin Val(S, Result, E); if (E <> 0) or (Result < AMin) or (Result > AMax) then Invalid; end; procedure SetSetupHeaderOption(const Option: TSetupHeaderOption); begin if not StrToBool(Value) then Exclude(SetupHeader.Options, Option) else Include(SetupHeader.Options, Option); end; function ExtractNumber(var P: PChar): Integer; var I: Integer; begin Result := 0; for I := 0 to 3 do begin { maximum of 4 digits } if not CharInSet(P^, ['0'..'9']) then begin if I = 0 then Invalid; Break; end; Result := (Result * 10) + (Ord(P^) - Ord('0')); Inc(P); end; end; procedure GeneratePasswordHashAndSalt(const Password: String; var Hash: TSHA1Digest; var Salt: TSetupSalt); var Context: TSHA1Context; begin { Random salt is mixed into the password hash to make it more difficult for someone to tell that two installations use the same password. A fixed string is also mixed in "just in case" the system's RNG is broken -- this hash must never be the same as the hash used for encryption. } GenerateRandomBytes(Salt, SizeOf(Salt)); SHA1Init(Context); SHA1Update(Context, PAnsiChar('PasswordCheckHash')^, Length('PasswordCheckHash')); SHA1Update(Context, Salt, SizeOf(Salt)); SHA1Update(Context, Pointer(Password)^, Length(Password)*SizeOf(Password[1])); Hash := SHA1Final(Context); end; procedure StrToTouchDate(const S: String); var P: PChar; Year, Month, Day: Integer; ST: TSystemTime; FT: TFileTime; begin if CompareText(S, 'current') = 0 then begin TouchDateOption := tdCurrent; Exit; end; if CompareText(S, 'none') = 0 then begin TouchDateOption := tdNone; Exit; end; P := PChar(S); Year := ExtractNumber(P); if (Year < 1980) or (Year > 2107) or (P^ <> '-') then Invalid; Inc(P); Month := ExtractNumber(P); if (Month < 1) or (Month > 12) or (P^ <> '-') then Invalid; Inc(P); Day := ExtractNumber(P); if (Day < 1) or (Day > 31) or (P^ <> #0) then Invalid; { Verify that the day is valid for the specified month & year } FillChar(ST, SizeOf(ST), 0); ST.wYear := Year; ST.wMonth := Month; ST.wDay := Day; if not SystemTimeToFileTime(ST, FT) then Invalid; TouchDateOption := tdExplicit; TouchDateYear := Year; TouchDateMonth := Month; TouchDateDay := Day; end; procedure StrToTouchTime(const S: String); var P: PChar; Hour, Minute, Second: Integer; begin if CompareText(S, 'current') = 0 then begin TouchTimeOption := ttCurrent; Exit; end; if CompareText(S, 'none') = 0 then begin TouchTimeOption := ttNone; Exit; end; P := PChar(S); Hour := ExtractNumber(P); if (Hour > 23) or (P^ <> ':') then Invalid; Inc(P); Minute := ExtractNumber(P); if Minute > 59 then Invalid; if P^ = #0 then Second := 0 else begin if P^ <> ':' then Invalid; Inc(P); Second := ExtractNumber(P); if (Second > 59) or (P^ <> #0) then Invalid; end; TouchTimeOption := ttExplicit; TouchTimeHour := Hour; TouchTimeMinute := Minute; TouchTimeSecond := Second; end; function StrToArchitectures(S: String; const Only64Bit: Boolean): TSetupProcessorArchitectures; const ProcessorFlags: array[0..2] of PChar = ('x86', 'x64', 'ia64'); begin Result := []; while True do case ExtractFlag(S, ProcessorFlags) of -2: Break; -1: Invalid; 0: if Only64Bit then Invalid else Include(Result, paX86); 1: Include(Result, paX64); 2: Include(Result, paIA64); end; end; var P: Integer; AIncludes: TStringList; begin SeparateDirective(Line, KeyName, Value); if KeyName = '' then Exit; I := GetEnumValue(TypeInfo(TSetupSectionDirectives), 'ss' + KeyName); if I = -1 then AbortCompileOnLineFmt(SCompilerUnknownDirective, ['Setup', KeyName]); Directive := TSetupSectionDirectives(I); if SetupDirectiveLines[Directive] <> 0 then AbortCompileOnLineFmt(SCompilerEntryAlreadySpecified, ['Setup', KeyName]); SetupDirectiveLines[Directive] := LineNumber; case Directive of ssAllowCancelDuringInstall: begin SetSetupHeaderOption(shAllowCancelDuringInstall); end; ssAllowNetworkDrive: begin SetSetupHeaderOption(shAllowNetworkDrive); end; ssAllowNoIcons: begin SetSetupHeaderOption(shAllowNoIcons); end; ssAllowRootDirectory: begin SetSetupHeaderOption(shAllowRootDirectory); end; ssAllowUNCPath: begin SetSetupHeaderOption(shAllowUNCPath); end; ssAlwaysRestart: begin SetSetupHeaderOption(shAlwaysRestart); end; ssAlwaysUsePersonalGroup: begin SetSetupHeaderOption(shAlwaysUsePersonalGroup); end; ssAlwaysShowComponentsList: begin SetSetupHeaderOption(shAlwaysShowComponentsList); end; ssAlwaysShowDirOnReadyPage: begin SetSetupHeaderOption(shAlwaysShowDirOnReadyPage); end; ssAlwaysShowGroupOnReadyPage: begin SetSetupHeaderOption(shAlwaysShowGroupOnReadyPage); end; ssAppCopyright: begin SetupHeader.AppCopyright := Value; end; ssAppComments: begin SetupHeader.AppComments := Value; end; ssAppContact: begin SetupHeader.AppContact := Value; end; ssAppendDefaultDirName: begin SetSetupHeaderOption(shAppendDefaultDirName); end; ssAppendDefaultGroupName: begin SetSetupHeaderOption(shAppendDefaultGroupName); end; ssAppId: begin if Value = '' then Invalid; SetupHeader.AppId := Value; end; ssAppModifyPath: begin SetupHeader.AppModifyPath := Value; end; ssAppMutex: begin SetupHeader.AppMutex := Trim(Value); end; ssAppName: begin if Value = '' then Invalid; SetupHeader.AppName := Value; end; ssAppPublisher: begin SetupHeader.AppPublisher := Value; end; ssAppPublisherURL: begin SetupHeader.AppPublisherURL := Value; end; ssAppReadmeFile: begin SetupHeader.AppReadmeFile := Value; end; ssAppSupportPhone: begin SetupHeader.AppSupportPhone := Value; end; ssAppSupportURL: begin SetupHeader.AppSupportURL := Value; end; ssAppUpdatesURL: begin SetupHeader.AppUpdatesURL := Value; end; ssAppVerName: begin if Value = '' then Invalid; SetupHeader.AppVerName := Value; end; ssAppVersion: begin SetupHeader.AppVersion := Value; end; ssArchitecturesAllowed: begin SetupHeader.ArchitecturesAllowed := StrToArchitectures(Value, False); end; ssArchitecturesInstallIn64BitMode: begin SetupHeader.ArchitecturesInstallIn64BitMode := StrToArchitectures(Value, True); end; ssBackColor: begin try SetupHeader.BackColor := StringToColor(Value); except Invalid; end; end; ssBackColor2: begin try SetupHeader.BackColor2 := StringToColor(Value); except Invalid; end; end; ssBackColorDirection: begin if CompareText(Value, 'toptobottom') = 0 then Exclude(SetupHeader.Options, shBackColorHorizontal) else if CompareText(Value, 'lefttoright') = 0 then Include(SetupHeader.Options, shBackColorHorizontal) else Invalid; end; ssBackSolid: begin BackSolid := StrToBool(Value); end; ssChangesAssociations: begin SetSetupHeaderOption(shChangesAssociations); end; ssChangesEnvironment: begin SetSetupHeaderOption(shChangesEnvironment); end; ssCloseApplications: begin SetSetupHeaderOption(shCloseApplications); end; ssCloseApplicationsFilter: begin if Value = '' then Invalid; AIncludes := TStringList.Create; try ProcessWildcardsParameter(Value, AIncludes, SCompilerDirectiveCloseApplicationsFilterTooLong); SetupHeader.CloseApplicationsFilter := StringsToCommaString(AIncludes); finally AIncludes.Free; end; end; ssCompression: begin Value := Lowercase(Trim(Value)); if Value = 'none' then begin CompressMethod := cmStored; CompressLevel := 0; end else if Value = 'zip' then begin CompressMethod := cmZip; CompressLevel := 7; end else if Value = 'bzip' then begin CompressMethod := cmBzip; CompressLevel := 9; end else if Value = 'lzma' then begin CompressMethod := cmLZMA; CompressLevel := clLZMAMax; end else if Value = 'lzma2' then begin CompressMethod := cmLZMA2; CompressLevel := clLZMAMax; end else if Copy(Value, 1, 4) = 'zip/' then begin I := StrToIntDef(Copy(Value, 5, Maxint), -1); if (I < 1) or (I > 9) then Invalid; CompressMethod := cmZip; CompressLevel := I; end else if Copy(Value, 1, 5) = 'bzip/' then begin I := StrToIntDef(Copy(Value, 6, Maxint), -1); if (I < 1) or (I > 9) then Invalid; CompressMethod := cmBzip; CompressLevel := I; end else if Copy(Value, 1, 5) = 'lzma/' then begin if not LZMAGetLevel(Copy(Value, 6, Maxint), I) then Invalid; CompressMethod := cmLZMA; CompressLevel := I; end else if Copy(Value, 1, 6) = 'lzma2/' then begin if not LZMAGetLevel(Copy(Value, 7, Maxint), I) then Invalid; CompressMethod := cmLZMA2; CompressLevel := I; end else Invalid; end; ssCompressionThreads: begin if CompareText(Value, 'auto') = 0 then { do nothing; it's the default } else begin if StrToIntRange(Value, 1, 64) = 1 then begin InternalCompressProps.NumThreads := 1; CompressProps.NumThreads := 1; end; end; end; ssCreateAppDir: begin SetSetupHeaderOption(shCreateAppDir); end; ssCreateUninstallRegKey: begin SetupHeader.CreateUninstallRegKey := Value; end; ssDefaultDialogFontName: begin DefaultDialogFontName := Trim(Value); end; ssDefaultDirName: begin SetupHeader.DefaultDirName := Value; end; ssDefaultGroupName: begin SetupHeader.DefaultGroupName := Value; end; ssDefaultUserInfoName: begin SetupHeader.DefaultUserInfoName := Value; end; ssDefaultUserInfoOrg: begin SetupHeader.DefaultUserInfoOrg := Value; end; ssDefaultUserInfoSerial: begin SetupHeader.DefaultUserInfoSerial := Value; end; ssDirExistsWarning: begin if CompareText(Value, 'auto') = 0 then SetupHeader.DirExistsWarning := ddAuto else if StrToBool(Value) then { ^ exception will be raised if Value is invalid } SetupHeader.DirExistsWarning := ddYes else SetupHeader.DirExistsWarning := ddNo; end; ssDisableDirPage: begin if CompareText(Value, 'auto') = 0 then SetupHeader.DisableDirPage := dpAuto else if StrToBool(Value) then { ^ exception will be raised if Value is invalid } SetupHeader.DisableDirPage := dpYes else SetupHeader.DisableDirPage := dpNo; end; ssDisableFinishedPage: begin SetSetupHeaderOption(shDisableFinishedPage); end; ssDisableProgramGroupPage: begin if CompareText(Value, 'auto') = 0 then SetupHeader.DisableProgramGroupPage := dpAuto else if StrToBool(Value) then { ^ exception will be raised if Value is invalid } SetupHeader.DisableProgramGroupPage := dpYes else SetupHeader.DisableProgramGroupPage := dpNo; end; ssDisableReadyMemo: begin SetSetupHeaderOption(shDisableReadyMemo); end; ssDisableReadyPage: begin SetSetupHeaderOption(shDisableReadyPage); end; ssDisableStartupPrompt: begin SetSetupHeaderOption(shDisableStartupPrompt); end; ssDisableWelcomePage: begin SetSetupHeaderOption(shDisableWelcomePage); end; ssDiskClusterSize: begin Val(Value, DiskClusterSize, I); if I <> 0 then Invalid; if (DiskClusterSize < 1) or (DiskClusterSize > 32768) then AbortCompileOnLine(SCompilerDiskClusterSizeInvalid); end; ssDiskSliceSize: begin if CompareText(Value, 'max') = 0 then DiskSliceSize := MaxDiskSliceSize else begin Val(Value, DiskSliceSize, I); if I <> 0 then Invalid; if (DiskSliceSize < 262144) or (DiskSliceSize > MaxDiskSliceSize) then AbortCompileFmt(SCompilerDiskSliceSizeInvalid, [262144, MaxDiskSliceSize]); end; end; ssDiskSpanning: begin DiskSpanning := StrToBool(Value); end; ssDontMergeDuplicateFiles: begin { obsolete; superceded by "MergeDuplicateFiles" } if SetupDirectiveLines[ssMergeDuplicateFiles] = 0 then DontMergeDuplicateFiles := StrToBool(Value); WarningsList.Add(Format(SCompilerEntrySuperseded2, ['Setup', KeyName, 'MergeDuplicateFiles'])); end; ssEnableDirDoesntExistWarning: begin SetSetupHeaderOption(shEnableDirDoesntExistWarning); end; ssEncryption: begin SetSetupHeaderOption(shEncryptionUsed); end; ssExtraDiskSpaceRequired: begin if not StrToInteger64(Value, SetupHeader.ExtraDiskSpaceRequired) then Invalid; end; ssFlatComponentsList: begin SetSetupHeaderOption(shFlatComponentsList); end; ssInfoBeforeFile: begin InfoBeforeFile := Value; end; ssInfoAfterFile: begin InfoAfterFile := Value; end; ssInternalCompressLevel: begin Value := Lowercase(Trim(Value)); if (Value = '0') or (CompareText(Value, 'none') = 0) then InternalCompressLevel := 0 else if not LZMAGetLevel(Value, InternalCompressLevel) then Invalid; end; ssLanguageDetectionMethod: begin if CompareText(Value, 'uilanguage') = 0 then SetupHeader.LanguageDetectionMethod := ldUILanguage else if CompareText(Value, 'locale') = 0 then SetupHeader.LanguageDetectionMethod := ldLocale else if CompareText(Value, 'none') = 0 then SetupHeader.LanguageDetectionMethod := ldNone else Invalid; end; ssLicenseFile: begin LicenseFile := Value; end; ssLZMAAlgorithm: begin CompressProps.Algorithm := StrToIntRange(Value, 0, 1); end; ssLZMABlockSize: begin CompressProps.BlockSize := StrToIntRange(Value, 1024, 262144) * 1024; end; ssLZMADictionarySize: begin CompressProps.DictionarySize := StrToIntRange(Value, 4, 262144) * 1024; end; ssLZMAMatchFinder: begin if CompareText(Value, 'BT') = 0 then I := 1 else if CompareText(Value, 'HC') = 0 then I := 0 else Invalid; CompressProps.BTMode := I; end; ssLZMANumBlockThreads: begin CompressProps.NumBlockThreads := StrToIntRange(Value, 1, 32); end; ssLZMANumFastBytes: begin CompressProps.NumFastBytes := StrToIntRange(Value, 5, 273); end; ssLZMAUseSeparateProcess: begin if CompareText(Value, 'x86') = 0 then CompressProps.WorkerProcessFilename := GetLZMAExeFilename(False) else if StrToBool(Value) then CompressProps.WorkerProcessFilename := GetLZMAExeFilename(True) else CompressProps.WorkerProcessFilename := ''; if (CompressProps.WorkerProcessFilename <> '') and (Byte(GetVersion()) < 5) then AbortCompileOnLineFmt(SCompilerDirectiveRequiresWindows2000, ['Setup', KeyName]); end; ssMergeDuplicateFiles: begin DontMergeDuplicateFiles := not StrToBool(Value); end; ssMessagesFile: begin AbortCompileOnLine(SCompilerMessagesFileObsolete); end; ssMinVersion: begin if not StrToVersionNumbers(Value, SetupHeader.MinVersion) then Invalid; if SetupHeader.MinVersion.WinVersion <> 0 then AbortCompileOnLine(SCompilerMinVersionWinMustBeZero); if SetupHeader.MinVersion.NTVersion < $05000000 then AbortCompileOnLineFmt(SCompilerMinVersionNTTooLow, ['5.0']); end; ssOnlyBelowVersion: begin if not StrToVersionNumbers(Value, SetupHeader.OnlyBelowVersion) then Invalid; end; ssOutputBaseFilename: begin if not FixedOutputBaseFilename then begin if Value = '' then Invalid; OutputBaseFilename := Value; end; end; ssOutputDir: begin if not FixedOutputDir then begin if Value = '' then Invalid; OutputDir := Value; end; end; ssOutputManifestFile: begin if Value = '' then Invalid; OutputManifestFile := Value; end; ssPassword: begin if Value <> '' then begin CryptKey := Value; GeneratePasswordHashAndSalt(Value, SetupHeader.PasswordHash, SetupHeader.PasswordSalt); Include(SetupHeader.Options, shPassword); end; end; ssPrivilegesRequired: begin if CompareText(Value, 'none') = 0 then SetupHeader.PrivilegesRequired := prNone else if CompareText(Value, 'poweruser') = 0 then SetupHeader.PrivilegesRequired := prPowerUser else if CompareText(Value, 'admin') = 0 then SetupHeader.PrivilegesRequired := prAdmin else if CompareText(Value, 'lowest') = 0 then SetupHeader.PrivilegesRequired := prLowest else Invalid; end; ssReserveBytes: begin Val(Value, ReserveBytes, I); if (I <> 0) or (ReserveBytes < 0) then Invalid; end; ssRestartApplications: begin SetSetupHeaderOption(shRestartApplications); end; ssRestartIfNeededByRun: begin SetSetupHeaderOption(shRestartIfNeededByRun); end; ssSetupIconFile: begin if (Value <> '') and (Win32Platform <> VER_PLATFORM_WIN32_NT) then AbortCompileOnLineFmt(SCompilerDirectiveIsNTOnly, ['Setup', KeyName]); SetupIconFilename := Value; end; ssSetupLogging: begin SetSetupHeaderOption(shSetupLogging); end; ssShowComponentSizes: begin SetSetupHeaderOption(shShowComponentSizes); end; ssShowLanguageDialog: begin if CompareText(Value, 'auto') = 0 then SetupHeader.ShowLanguageDialog := slAuto else if StrToBool(Value) then SetupHeader.ShowLanguageDialog := slYes else SetupHeader.ShowLanguageDialog := slNo; end; ssShowTasksTreeLines: begin SetSetupHeaderOption(shShowTasksTreeLines); end; ssShowUndisplayableLanguages: begin {$IFDEF UNICODE} WarningsList.Add(Format(SCompilerEntryObsolete, ['Setup', KeyName])); {$ELSE} SetSetupHeaderOption(shShowUndisplayableLanguages); {$ENDIF} end; ssSignedUninstaller: begin SetSetupHeaderOption(shSignedUninstaller); end; ssSignedUninstallerDir: begin if Value = '' then Invalid; SignedUninstallerDir := Value; end; ssSignTool: begin P := Pos(' ', Value); if (P <> 0) then begin SignTool := Copy(Value, 1, P-1); SignToolParams := Copy(Value, P+1, MaxInt); end else begin SignTool := Value; SignToolParams := ''; end; if FindSignToolIndexByName(SignTool) = -1 then Invalid; end; ssSlicesPerDisk: begin I := StrToIntDef(Value, -1); if (I < 1) or (I > 26) then Invalid; SlicesPerDisk := I; end; ssSolidCompression: begin UseSolidCompression := StrToBool(Value); end; ssSourceDir: begin if Value = '' then Invalid; SourceDir := PrependDirName(Value, OriginalSourceDir); end; ssTerminalServicesAware: begin TerminalServicesAware := StrToBool(Value); end; ssTimeStampRounding: begin I := StrToIntDef(Value, -1); { Note: We can't allow really high numbers here because it gets multiplied by 10000000 } if (I < 0) or (I > 60) then Invalid; TimeStampRounding := I; end; ssTimeStampsInUTC: begin TimeStampsInUTC := StrToBool(Value); end; ssTouchDate: begin StrToTouchDate(Value); end; ssTouchTime: begin StrToTouchTime(Value); end; ssUpdateUninstallLogAppName: begin SetSetupHeaderOption(shUpdateUninstallLogAppName); end; ssUninstallable: begin SetupHeader.Uninstallable := Value; end; ssUninstallDisplayIcon: begin SetupHeader.UninstallDisplayIcon := Value; end; ssUninstallDisplayName: begin SetupHeader.UninstallDisplayName := Value; end; ssUninstallDisplaySize: begin if not StrToInteger64(Value, SetupHeader.UninstallDisplaySize) or ((SetupHeader.UninstallDisplaySize.Lo = 0) and (SetupHeader.UninstallDisplaySize.Hi = 0)) then Invalid; end; ssUninstallFilesDir: begin if Value = '' then Invalid; SetupHeader.UninstallFilesDir := Value; end; ssUninstallIconFile: begin WarningsList.Add(Format(SCompilerEntryObsolete, ['Setup', KeyName])); end; ssUninstallLogMode: begin if CompareText(Value, 'append') = 0 then SetupHeader.UninstallLogMode := lmAppend else if CompareText(Value, 'new') = 0 then SetupHeader.UninstallLogMode := lmNew else if CompareText(Value, 'overwrite') = 0 then SetupHeader.UninstallLogMode := lmOverwrite else Invalid; end; ssUninstallRestartComputer: begin SetSetupHeaderOption(shUninstallRestartComputer); end; ssUninstallStyle: begin WarningsList.Add(Format(SCompilerEntryObsolete, ['Setup', KeyName])); end; ssUsePreviousAppDir: begin SetSetupHeaderOption(shUsePreviousAppDir); end; ssUsePreviousGroup: begin SetSetupHeaderOption(shUsePreviousGroup); end; ssUsePreviousLanguage: begin SetSetupHeaderOption(shUsePreviousLanguage); end; ssUsePreviousSetupType: begin SetSetupHeaderOption(shUsePreviousSetupType); end; ssUsePreviousTasks: begin SetSetupHeaderOption(shUsePreviousTasks); end; ssUsePreviousUserInfo: begin SetSetupHeaderOption(shUsePreviousUserInfo); end; ssUseSetupLdr: begin UseSetupLdr := StrToBool(Value); end; ssUserInfoPage: begin SetSetupHeaderOption(shUserInfoPage); end; ssVersionInfoCompany: begin VersionInfoCompany := Value; end; ssVersionInfoCopyright: begin VersionInfoCopyright := Value; end; ssVersionInfoDescription: begin VersionInfoDescription := Value; end; ssVersionInfoProductName: begin VersionInfoProductName := Value; end; ssVersionInfoProductVersion: begin VersionInfoProductVersionOriginalValue := Value; if not StrToVersionInfoVersionNumber(Value, VersionInfoProductVersion) then Invalid; end; ssVersionInfoProductTextVersion: begin VersionInfoProductTextVersion := Value; end; ssVersionInfoTextVersion: begin VersionInfoTextVersion := Value; end; ssVersionInfoVersion: begin VersionInfoVersionOriginalValue := Value; if not StrToVersionInfoVersionNumber(Value, VersionInfoVersion) then Invalid; end; ssWindowResizable: begin SetSetupHeaderOption(shWindowResizable); end; ssWindowShowCaption: begin SetSetupHeaderOption(shWindowShowCaption); end; ssWindowStartMaximized: begin SetSetupHeaderOption(shWindowStartMaximized); end; ssWindowVisible: begin SetSetupHeaderOption(shWindowVisible); end; ssWizardImageBackColor: begin try SetupHeader.WizardImageBackColor := StringToColor(Value); except Invalid; end; end; ssWizardSmallImageBackColor: begin WarningsList.Add(Format(SCompilerEntryObsolete, ['Setup', KeyName])); end; ssWizardImageStretch: begin SetSetupHeaderOption(shWizardImageStretch); end; ssWizardImageFile: begin if Value = '' then Invalid; WizardImageFile := Value; end; ssWizardSmallImageFile: begin if Value = '' then Invalid; WizardSmallImageFile := Value; end; ssWizardStyle: begin if CompareText(Value, 'modern') = 0 then begin { no-op } end else Invalid; end; end; end; function TSetupCompiler.FindLangEntryIndexByName(const AName: String; const Pre: Boolean): Integer; var I: Integer; begin {$IFDEF UNICODE} if Pre then begin for I := 0 to PreLangDataList.Count-1 do begin if TPreLangData(PreLangDataList[I]).Name = AName then begin Result := I; Exit; end; end; AbortCompileOnLineFmt(SCompilerUnknownLanguage, [AName]); end; {$ENDIF} for I := 0 to LanguageEntries.Count-1 do begin if PSetupLanguageEntry(LanguageEntries[I]).Name = AName then begin Result := I; Exit; end; end; Result := -1; AbortCompileOnLineFmt(SCompilerUnknownLanguage, [AName]); end; function TSetupCompiler.FindSignToolIndexByName(const AName: String): Integer; var I: Integer; begin for I := 0 to SignToolList.Count-1 do begin if TSignTool(SignToolList[I]).Name = AName then begin Result := I; Exit; end; end; Result := -1; end; {$IFDEF UNICODE} procedure TSetupCompiler.EnumLangOptionsPre(const Line: PChar; const Ext: Integer); procedure ApplyToLangEntryPre(const KeyName, Value: String; const PreLangData: TPreLangData; const AffectsMultipleLangs: Boolean); var I: Integer; Directive: TLangOptionsSectionDirectives; procedure Invalid; begin AbortCompileOnLineFmt(SCompilerEntryInvalid2, ['LangOptions', KeyName]); end; function StrToIntCheck(const S: String): Integer; var E: Integer; begin Val(S, Result, E); if E <> 0 then Invalid; end; begin I := GetEnumValue(TypeInfo(TLangOptionsSectionDirectives), 'ls' + KeyName); if I = -1 then AbortCompileOnLineFmt(SCompilerUnknownDirective, ['LangOptions', KeyName]); Directive := TLangOptionsSectionDirectives(I); case Directive of lsLanguageCodePage: begin if AffectsMultipleLangs then AbortCompileOnLineFmt(SCompilerCantSpecifyLangOption, [KeyName]); PreLangData.LanguageCodePage := StrToIntCheck(Value); if (PreLangData.LanguageCodePage <> 0) and not IsValidCodePage(PreLangData.LanguageCodePage) then Invalid; end; end; end; var KeyName, Value: String; I, LangIndex: Integer; begin SeparateDirective(Line, KeyName, Value); LangIndex := ExtractLangIndex(Self, KeyName, Ext, True); if LangIndex = -1 then begin for I := 0 to PreLangDataList.Count-1 do ApplyToLangEntryPre(KeyName, Value, TPreLangData(PreLangDataList[I]), PreLangDataList.Count > 1); end else ApplyToLangEntryPre(KeyName, Value, TPreLangData(PreLangDataList[LangIndex]), False); end; {$ENDIF} procedure TSetupCompiler.EnumLangOptions(const Line: PChar; const Ext: Integer); procedure ApplyToLangEntry(const KeyName, Value: String; var LangOptions: TSetupLanguageEntry; const AffectsMultipleLangs: Boolean); var I: Integer; Directive: TLangOptionsSectionDirectives; procedure Invalid; begin AbortCompileOnLineFmt(SCompilerEntryInvalid2, ['LangOptions', KeyName]); end; function StrToIntCheck(const S: String): Integer; var E: Integer; begin Val(S, Result, E); if E <> 0 then Invalid; end; function ConvertLanguageName(N: String): String; var AsciiWarningShown: Boolean; I, J, L: Integer; W: Word; begin N := Trim(N); if N = '' then Invalid; AsciiWarningShown := False; Result := ''; I := 1; while I <= Length(N) do begin if N[I] = '<' then begin { Handle embedded Unicode characters ('<nnnn>') } if (I+5 > Length(N)) or (N[I+5] <> '>') then Invalid; for J := I+1 to I+4 do if not CharInSet(UpCase(N[J]), ['0'..'9', 'A'..'F']) then Invalid; W := StrToIntCheck('$' + Copy(N, I+1, 4)); Inc(I, 6); end else begin if (N[I] > #126) and not AsciiWarningShown then begin WarningsList.Add(SCompilerLanguageNameNotAscii); AsciiWarningShown := True; end; W := Ord(N[I]); Inc(I); end; L := Length(Result); SetLength(Result, L + (SizeOf(Word) div SizeOf(Char))); Word((@Result[L+1])^) := W; end; end; begin I := GetEnumValue(TypeInfo(TLangOptionsSectionDirectives), 'ls' + KeyName); if I = -1 then AbortCompileOnLineFmt(SCompilerUnknownDirective, ['LangOptions', KeyName]); Directive := TLangOptionsSectionDirectives(I); case Directive of lsCopyrightFontName: begin LangOptions.CopyrightFontName := Trim(Value); end; lsCopyrightFontSize: begin LangOptions.CopyrightFontSize := StrToIntCheck(Value); end; lsDialogFontName: begin LangOptions.DialogFontName := Trim(Value); end; lsDialogFontSize: begin LangOptions.DialogFontSize := StrToIntCheck(Value); end; lsDialogFontStandardHeight: begin WarningsList.Add(Format(SCompilerEntryObsolete, ['LangOptions', KeyName])); end; lsLanguageCodePage: begin if AffectsMultipleLangs then AbortCompileOnLineFmt(SCompilerCantSpecifyLangOption, [KeyName]); {$IFNDEF UNICODE}LangOptions.LanguageCodePage := {$ENDIF}StrToIntCheck(Value); end; lsLanguageID: begin if AffectsMultipleLangs then AbortCompileOnLineFmt(SCompilerCantSpecifyLangOption, [KeyName]); LangOptions.LanguageID := StrToIntCheck(Value); end; lsLanguageName: begin if AffectsMultipleLangs then AbortCompileOnLineFmt(SCompilerCantSpecifyLangOption, [KeyName]); LangOptions.LanguageName := ConvertLanguageName(Value); end; lsRightToLeft: begin if not TryStrToBoolean(Value, LangOptions.RightToLeft) then Invalid; end; lsTitleFontName: begin LangOptions.TitleFontName := Trim(Value); end; lsTitleFontSize: begin LangOptions.TitleFontSize := StrToIntCheck(Value); end; lsWelcomeFontName: begin LangOptions.WelcomeFontName := Trim(Value); end; lsWelcomeFontSize: begin LangOptions.WelcomeFontSize := StrToIntCheck(Value); end; end; end; var KeyName, Value: String; I, LangIndex: Integer; begin SeparateDirective(Line, KeyName, Value); LangIndex := ExtractLangIndex(Self, KeyName, Ext, False); if LangIndex = -1 then begin for I := 0 to LanguageEntries.Count-1 do ApplyToLangEntry(KeyName, Value, PSetupLanguageEntry(LanguageEntries[I])^, LanguageEntries.Count > 1); end else ApplyToLangEntry(KeyName, Value, PSetupLanguageEntry(LanguageEntries[LangIndex])^, False); end; procedure TSetupCompiler.EnumTypes(const Line: PChar; const Ext: Integer); function IsCustomTypeAlreadyDefined: Boolean; var I: Integer; begin for I := 0 to TypeEntries.Count-1 do if toIsCustom in PSetupTypeEntry(TypeEntries[I]).Options then begin Result := True; Exit; end; Result := False; end; type TParam = (paFlags, paName, paDescription, paLanguages, paCheck, paMinVersion, paOnlyBelowVersion); const ParamTypesName = 'Name'; ParamTypesDescription = 'Description'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamTypesName; Flags: [piRequired, piNoEmpty]), (Name: ParamTypesDescription; Flags: [piRequired, piNoEmpty]), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..0] of PChar = ( 'iscustom'); var Values: array[TParam] of TParamValue; NewTypeEntry: PSetupTypeEntry; begin ExtractParameters(Line, ParamInfo, Values); NewTypeEntry := AllocMem(SizeOf(TSetupTypeEntry)); try with NewTypeEntry^ do begin MinVersion := SetupHeader.MinVersion; Typ := ttUser; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, toIsCustom); end; { Name } Name := LowerCase(Values[paName].Data); { Description } Description := Values[paDescription].Data; { Common parameters } ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (toIsCustom in Options) and IsCustomTypeAlreadyDefined then AbortCompileOnLine(SCompilerTypesCustomTypeAlreadyDefined); CheckConst(Description, MinVersion, []); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); end; except SEFreeRec(NewTypeEntry, SetupTypeEntryStrings, SetupTypeEntryAnsiStrings); raise; end; TypeEntries.Add(NewTypeEntry); end; procedure TSetupCompiler.EnumComponents(const Line: PChar; const Ext: Integer); type TParam = (paFlags, paName, paDescription, paExtraDiskSpaceRequired, paTypes, paLanguages, paCheck, paMinVersion, paOnlyBelowVersion); const ParamComponentsName = 'Name'; ParamComponentsDescription = 'Description'; ParamComponentsExtraDiskSpaceRequired = 'ExtraDiskSpaceRequired'; ParamComponentsTypes = 'Types'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamComponentsName; Flags: [piRequired, piNoEmpty]), (Name: ParamComponentsDescription; Flags: [piRequired, piNoEmpty]), (Name: ParamComponentsExtraDiskSpaceRequired; Flags: []), (Name: ParamComponentsTypes; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..5] of PChar = ( 'fixed', 'restart', 'disablenouninstallwarning', 'exclusive', 'dontinheritcheck', 'checkablealone'); var Values: array[TParam] of TParamValue; NewComponentEntry: PSetupComponentEntry; PrevLevel, I: Integer; begin ExtractParameters(Line, ParamInfo, Values); NewComponentEntry := AllocMem(SizeOf(TSetupComponentEntry)); try with NewComponentEntry^ do begin MinVersion := SetupHeader.MinVersion; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, coFixed); 1: Include(Options, coRestart); 2: Include(Options, coDisableNoUninstallWarning); 3: Include(Options, coExclusive); 4: Include(Options, coDontInheritCheck); 5: Used := True; end; { Name } Name := LowerCase(Values[paName].Data); StringChange(Name, '/', '\'); if not IsValidIdentString(Name, True, False) then AbortCompileOnLine(SCompilerComponentsOrTasksBadName); Level := CountChars(Name, '\'); if ComponentEntries.Count > 0 then PrevLevel := PSetupComponentEntry(ComponentEntries[ComponentEntries.Count-1]).Level else PrevLevel := -1; if Level > PrevLevel + 1 then AbortCompileOnLine(SCompilerComponentsInvalidLevel); { Description } Description := Values[paDescription].Data; { ExtraDiskSpaceRequired } if Values[paExtraDiskSpaceRequired].Found then begin if not StrToInteger64(Values[paExtraDiskSpaceRequired].Data, ExtraDiskSpaceRequired) then AbortCompileParamError(SCompilerParamInvalid2, ParamComponentsExtraDiskSpaceRequired); end; { Types } while True do begin I := ExtractType(Values[paTypes].Data, TypeEntries); case I of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownType, ParamComponentsTypes); else begin if TypeEntries.Count <> 0 then AddToCommaText(Types, PSetupTypeEntry(TypeEntries[I]).Name) else AddToCommaText(Types, DefaultTypeEntryNames[I]); end; end; end; { Common parameters } ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (coDontInheritCheck in Options) and (coExclusive in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'dontinheritcheck', 'exclusive']); CheckConst(Description, MinVersion, []); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); end; except SEFreeRec(NewComponentEntry, SetupComponentEntryStrings, SetupComponentEntryAnsiStrings); raise; end; ComponentEntries.Add(NewComponentEntry); end; procedure TSetupCompiler.EnumTasks(const Line: PChar; const Ext: Integer); type TParam = (paFlags, paName, paDescription, paGroupDescription, paComponents, paLanguages, paCheck, paMinVersion, paOnlyBelowVersion); const ParamTasksName = 'Name'; ParamTasksDescription = 'Description'; ParamTasksGroupDescription = 'GroupDescription'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamTasksName; Flags: [piRequired, piNoEmpty, piNoQuotes]), (Name: ParamTasksDescription; Flags: [piRequired, piNoEmpty]), (Name: ParamTasksGroupDescription; Flags: [piNoEmpty]), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..5] of PChar = ( 'exclusive', 'unchecked', 'restart', 'checkedonce', 'dontinheritcheck', 'checkablealone'); var Values: array[TParam] of TParamValue; NewTaskEntry: PSetupTaskEntry; PrevLevel: Integer; begin ExtractParameters(Line, ParamInfo, Values); NewTaskEntry := AllocMem(SizeOf(TSetupTaskEntry)); try with NewTaskEntry^ do begin MinVersion := SetupHeader.MinVersion; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, toExclusive); 1: Include(Options, toUnchecked); 2: Include(Options, toRestart); 3: Include(Options, toCheckedOnce); 4: Include(Options, toDontInheritCheck); 5: Used := True; end; { Name } Name := LowerCase(Values[paName].Data); StringChange(Name, '/', '\'); if not IsValidIdentString(Name, True, False) then AbortCompileOnLine(SCompilerComponentsOrTasksBadName); Level := CountChars(Name, '\'); if TaskEntries.Count > 0 then PrevLevel := PSetupTaskEntry(TaskEntries[TaskEntries.Count-1]).Level else PrevLevel := -1; if Level > PrevLevel + 1 then AbortCompileOnLine(SCompilerTasksInvalidLevel); { Description } Description := Values[paDescription].Data; { GroupDescription } GroupDescription := Values[paGroupDescription].Data; { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (toDontInheritCheck in Options) and (toExclusive in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'dontinheritcheck', 'exclusive']); CheckConst(Description, MinVersion, []); CheckConst(GroupDescription, MinVersion, []); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); end; except SEFreeRec(NewTaskEntry, SetupTaskEntryStrings, SetupTaskEntryAnsiStrings); raise; end; TaskEntries.Add(NewTaskEntry); end; procedure TSetupCompiler.EnumDirs(const Line: PChar; const Ext: Integer); type TParam = (paFlags, paName, paAttribs, paPermissions, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamDirsName = 'Name'; ParamDirsAttribs = 'Attribs'; ParamDirsPermissions = 'Permissions'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamDirsName; Flags: [piRequired, piNoEmpty, piNoQuotes]), (Name: ParamDirsAttribs; Flags: []), (Name: ParamDirsPermissions; Flags: []), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..4] of PChar = ( 'uninsneveruninstall', 'deleteafterinstall', 'uninsalwaysuninstall', 'setntfscompression', 'unsetntfscompression'); AttribsFlags: array[0..2] of PChar = ( 'readonly', 'hidden', 'system'); AccessMasks: array[0..2] of TNameAndAccessMask = ( (Name: 'full'; Mask: $1F01FF), (Name: 'modify'; Mask: $1301BF), (Name: 'readexec'; Mask: $1200A9)); var Values: array[TParam] of TParamValue; NewDirEntry: PSetupDirEntry; begin ExtractParameters(Line, ParamInfo, Values); NewDirEntry := AllocMem(SizeOf(TSetupDirEntry)); try with NewDirEntry^ do begin MinVersion := SetupHeader.MinVersion; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, doUninsNeverUninstall); 1: Include(Options, doDeleteAfterInstall); 2: Include(Options, doUninsAlwaysUninstall); 3: Include(Options, doSetNTFSCompression); 4: Include(Options, doUnsetNTFSCompression); end; { Name } DirName := Values[paName].Data; { Attribs } while True do case ExtractFlag(Values[paAttribs].Data, AttribsFlags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamDirsAttribs); 0: Attribs := Attribs or FILE_ATTRIBUTE_READONLY; 1: Attribs := Attribs or FILE_ATTRIBUTE_HIDDEN; 2: Attribs := Attribs or FILE_ATTRIBUTE_SYSTEM; end; { Permissions } ProcessPermissionsParameter(Values[paPermissions].Data, AccessMasks, PermissionsEntry); { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (doUninsNeverUninstall in Options) and (doUninsAlwaysUninstall in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsneveruninstall', 'uninsalwaysuninstall']); if (doSetNTFSCompression in Options) and (doUnsetNTFSCompression in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'setntfscompression', 'unsetntfscompression']); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); CheckConst(DirName, MinVersion, []); end; except SEFreeRec(NewDirEntry, SetupDirEntryStrings, SetupDirEntryAnsiStrings); raise; end; WriteDebugEntry(deDir, DirEntries.Count); DirEntries.Add(NewDirEntry); end; function SpaceString(const S: String): String; var I: Integer; begin Result := ''; for I := 1 to Length(S) do begin if S[I] = ' ' then Continue; if Result <> '' then Result := Result + ' '; Result := Result + S[I]; end; end; type TMenuKeyCap = (mkcBkSp, mkcTab, mkcEsc, mkcEnter, mkcSpace, mkcPgUp, mkcPgDn, mkcEnd, mkcHome, mkcLeft, mkcUp, mkcRight, mkcDown, mkcIns, mkcDel, mkcShift, mkcCtrl, mkcAlt); {$IFDEF Delphi3OrHigher} var MenuKeyCaps: array[TMenuKeyCap] of string = ( SmkcBkSp, SmkcTab, SmkcEsc, SmkcEnter, SmkcSpace, SmkcPgUp, SmkcPgDn, SmkcEnd, SmkcHome, SmkcLeft, SmkcUp, SmkcRight, SmkcDown, SmkcIns, SmkcDel, SmkcShift, SmkcCtrl, SmkcAlt); {$ELSE} var MenuKeyCaps: array[TMenuKeyCap] of string; const MenuKeyCapIDs: array[TMenuKeyCap] of Word = ( SmkcBkSp, SmkcTab, SmkcEsc, SmkcEnter, SmkcSpace, SmkcPgUp, SmkcPgDn, SmkcEnd, SmkcHome, SmkcLeft, SmkcUp, SmkcRight, SmkcDown, SmkcIns, SmkcDel, SmkcShift, SmkcCtrl, SmkcAlt); {$ENDIF} procedure TSetupCompiler.EnumIcons(const Line: PChar; const Ext: Integer); {$IFNDEF Delphi3OrHigher} procedure LoadStrings; var I: TMenuKeyCap; begin for I := Low(TMenuKeyCap) to High(TMenuKeyCap) do MenuKeyCaps[I] := LoadStr(MenuKeyCapIDs[I]); end; {$ENDIF} function HotKeyToText(HotKey: Word): string; function GetSpecialName(HotKey: Word): string; var ScanCode: Integer; KeyName: array[0..255] of Char; begin Result := ''; ScanCode := MapVirtualKey(WordRec(HotKey).Lo, 0) shl 16; if ScanCode <> 0 then begin GetKeyNameText(ScanCode, KeyName, SizeOf(KeyName)); if (KeyName[1] = #0) and (KeyName[0] <> #0) then GetSpecialName := KeyName; end; end; var Name: string; begin case WordRec(HotKey).Lo of $08, $09: Name := MenuKeyCaps[TMenuKeyCap(Ord(mkcBkSp) + WordRec(HotKey).Lo - $08)]; $0D: Name := MenuKeyCaps[mkcEnter]; $1B: Name := MenuKeyCaps[mkcEsc]; $20..$28: Name := MenuKeyCaps[TMenuKeyCap(Ord(mkcSpace) + WordRec(HotKey).Lo - $20)]; $2D..$2E: Name := MenuKeyCaps[TMenuKeyCap(Ord(mkcIns) + WordRec(HotKey).Lo - $2D)]; $30..$39: Name := Chr(WordRec(HotKey).Lo - $30 + Ord('0')); $41..$5A: Name := Chr(WordRec(HotKey).Lo - $41 + Ord('A')); $60..$69: Name := Chr(WordRec(HotKey).Lo - $60 + Ord('0')); $70..$87: Name := 'F' + IntToStr(WordRec(HotKey).Lo - $6F); else Name := GetSpecialName(HotKey); end; if Name <> '' then begin Result := ''; if HotKey and (HOTKEYF_SHIFT shl 8) <> 0 then Result := Result + MenuKeyCaps[mkcShift]; if HotKey and (HOTKEYF_CONTROL shl 8) <> 0 then Result := Result + MenuKeyCaps[mkcCtrl]; if HotKey and (HOTKEYF_ALT shl 8) <> 0 then Result := Result + MenuKeyCaps[mkcAlt]; Result := Result + Name; end else Result := ''; end; function TextToHotKey(Text: string): Word; function CompareFront(var Text: string; const Front: string): Boolean; begin Result := False; if CompareText(Copy(Text, 1, Length(Front)), Front) = 0 then begin Result := True; Delete(Text, 1, Length(Front)); end; end; var Key: Word; Shift: Word; begin Result := 0; Shift := 0; while True do begin if CompareFront(Text, MenuKeyCaps[mkcShift]) then Shift := Shift or HOTKEYF_SHIFT else if CompareFront(Text, '^') then Shift := Shift or HOTKEYF_CONTROL else if CompareFront(Text, MenuKeyCaps[mkcCtrl]) then Shift := Shift or HOTKEYF_CONTROL else if CompareFront(Text, MenuKeyCaps[mkcAlt]) then Shift := Shift or HOTKEYF_ALT else Break; end; if Text = '' then Exit; for Key := $08 to $255 do { Copy range from table in HotKeyToText } if AnsiCompareText(Text, HotKeyToText(Key)) = 0 then begin Result := Key or (Shift shl 8); Exit; end; end; type TParam = (paFlags, paName, paFilename, paParameters, paWorkingDir, paHotKey, paIconFilename, paIconIndex, paComment, paAppUserModelID, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamIconsName = 'Name'; ParamIconsFilename = 'Filename'; ParamIconsParameters = 'Parameters'; ParamIconsWorkingDir = 'WorkingDir'; ParamIconsHotKey = 'HotKey'; ParamIconsIconFilename = 'IconFilename'; ParamIconsIconIndex = 'IconIndex'; ParamIconsComment = 'Comment'; ParamIconsAppUserModelID = 'AppUserModelID'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamIconsName; Flags: [piRequired, piNoEmpty, piNoQuotes]), (Name: ParamIconsFilename; Flags: [piRequired, piNoEmpty, piNoQuotes]), (Name: ParamIconsParameters; Flags: []), (Name: ParamIconsWorkingDir; Flags: [piNoQuotes]), (Name: ParamIconsHotKey; Flags: []), (Name: ParamIconsIconFilename; Flags: [piNoQuotes]), (Name: ParamIconsIconIndex; Flags: []), (Name: ParamIconsComment; Flags: []), (Name: ParamIconsAppUserModelID; Flags: []), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..9] of PChar = ( 'uninsneveruninstall', 'runminimized', 'createonlyiffileexists', 'useapppaths', 'closeonexit', 'dontcloseonexit', 'runmaximized', 'foldershortcut', 'excludefromshowinnewinstall', 'preventpinning'); var Values: array[TParam] of TParamValue; NewIconEntry: PSetupIconEntry; S: String; begin {$IFNDEF Delphi3OrHigher} LoadStrings; {$ENDIF} ExtractParameters(Line, ParamInfo, Values); NewIconEntry := AllocMem(SizeOf(TSetupIconEntry)); try with NewIconEntry^ do begin MinVersion := SetupHeader.MinVersion; ShowCmd := SW_SHOWNORMAL; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, ioUninsNeverUninstall); 1: ShowCmd := SW_SHOWMINNOACTIVE; 2: Include(Options, ioCreateOnlyIfFileExists); 3: Include(Options, ioUseAppPaths); 4: CloseOnExit := icYes; 5: CloseOnExit := icNo; 6: ShowCmd := SW_SHOWMAXIMIZED; 7: Include(Options, ioFolderShortcut); 8: Include(Options, ioExcludeFromShowInNewInstall); 9: Include(Options, ioPreventPinning); end; { Name } IconName := Values[paName].Data; { Filename } Filename := Values[paFilename].Data; { Parameters } Parameters := Values[paParameters].Data; { WorkingDir } WorkingDir := Values[paWorkingDir].Data; { HotKey } if Values[paHotKey].Found then begin HotKey := TextToHotKey(Values[paHotKey].Data); if HotKey = 0 then AbortCompileParamError(SCompilerParamInvalid2, ParamIconsHotKey); end; { IconFilename } IconFilename := Values[paIconFilename].Data; { IconIndex } if Values[paIconIndex].Found then begin try IconIndex := StrToInt(Values[paIconIndex].Data); except AbortCompileOnLine(SCompilerIconsIconIndexInvalid); end; end; { Comment } Comment := Values[paComment].Data; { AppUserModelID } AppUserModelID := Values[paAppUserModelID].Data; { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if Pos('"', IconName) <> 0 then AbortCompileParamError(SCompilerParamNoQuotes2, ParamIconsName); if PathPos('\', IconName) = 0 then AbortCompileOnLine(SCompilerIconsNamePathNotSpecified); if (IconIndex <> 0) and (IconFilename = '') then IconFilename := Filename; S := IconName; if Copy(S, 1, 8) = '{group}\' then Delete(S, 1, 8); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); CheckConst(S, MinVersion, []); CheckConst(Filename, MinVersion, []); CheckConst(Parameters, MinVersion, []); CheckConst(WorkingDir, MinVersion, []); CheckConst(IconFilename, MinVersion, []); CheckConst(Comment, MinVersion, []); CheckConst(AppUserModelID, MinVersion, []); end; except SEFreeRec(NewIconEntry, SetupIconEntryStrings, SetupIconEntryAnsiStrings); raise; end; WriteDebugEntry(deIcon, IconEntries.Count); IconEntries.Add(NewIconEntry); end; procedure TSetupCompiler.EnumINI(const Line: PChar; const Ext: Integer); type TParam = (paFlags, paFilename, paSection, paKey, paString, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamIniFilename = 'Filename'; ParamIniSection = 'Section'; ParamIniKey = 'Key'; ParamIniString = 'String'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamIniFilename; Flags: [piRequired, piNoQuotes]), (Name: ParamIniSection; Flags: [piRequired, piNoEmpty]), (Name: ParamIniKey; Flags: [piNoEmpty]), (Name: ParamIniString; Flags: []), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..3] of PChar = ( 'uninsdeleteentry', 'uninsdeletesection', 'createkeyifdoesntexist', 'uninsdeletesectionifempty'); var Values: array[TParam] of TParamValue; NewIniEntry: PSetupIniEntry; begin ExtractParameters(Line, ParamInfo, Values); NewIniEntry := AllocMem(SizeOf(TSetupIniEntry)); try with NewIniEntry^ do begin MinVersion := SetupHeader.MinVersion; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, ioUninsDeleteEntry); 1: Include(Options, ioUninsDeleteEntireSection); 2: Include(Options, ioCreateKeyIfDoesntExist); 3: Include(Options, ioUninsDeleteSectionIfEmpty); end; { Filename } Filename := Values[paFilename].Data; { Section } Section := Values[paSection].Data; { Key } Entry := Values[paKey].Data; { String } if Values[paString].Found then begin Value := Values[paString].Data; Include(Options, ioHasValue); end; { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (ioUninsDeleteEntry in Options) and (ioUninsDeleteEntireSection in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsdeleteentry', 'uninsdeletesection']); if (ioUninsDeleteEntireSection in Options) and (ioUninsDeleteSectionIfEmpty in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsdeletesection', 'uninsdeletesectionifempty']); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); CheckConst(Filename, MinVersion, []); CheckConst(Section, MinVersion, []); CheckConst(Entry, MinVersion, []); CheckConst(Value, MinVersion, []); end; except SEFreeRec(NewIniEntry, SetupIniEntryStrings, SetupIniEntryAnsiStrings); raise; end; WriteDebugEntry(deIni, IniEntries.Count); IniEntries.Add(NewIniEntry); end; procedure TSetupCompiler.EnumRegistry(const Line: PChar; const Ext: Integer); type TParam = (paFlags, paRoot, paSubkey, paValueType, paValueName, paValueData, paPermissions, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamRegistryRoot = 'Root'; ParamRegistrySubkey = 'Subkey'; ParamRegistryValueType = 'ValueType'; ParamRegistryValueName = 'ValueName'; ParamRegistryValueData = 'ValueData'; ParamRegistryPermissions = 'Permissions'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamRegistryRoot; Flags: [piRequired]), (Name: ParamRegistrySubkey; Flags: [piRequired]), (Name: ParamRegistryValueType; Flags: []), (Name: ParamRegistryValueName; Flags: []), (Name: ParamRegistryValueData; Flags: []), (Name: ParamRegistryPermissions; Flags: []), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..9] of PChar = ( 'createvalueifdoesntexist', 'uninsdeletevalue', 'uninsdeletekey', 'uninsdeletekeyifempty', 'uninsclearvalue', 'preservestringtype', 'deletekey', 'deletevalue', 'noerror', 'dontcreatekey'); AccessMasks: array[0..2] of TNameAndAccessMask = ( (Name: 'full'; Mask: $F003F), (Name: 'modify'; Mask: $3001F), { <- same access that Power Users get by default on HKLM\SOFTWARE } (Name: 'read'; Mask: $20019)); function ConvertBinaryString(const S: String): String; procedure Invalid; begin AbortCompileParamError(SCompilerParamInvalid2, ParamRegistryValueData); end; var I: Integer; C: Char; B: Byte; N: Integer; procedure EndByte; begin case N of 0: ; 2: begin Result := Result + Chr(B); N := 0; B := 0; end; else Invalid; end; end; begin Result := ''; N := 0; B := 0; for I := 1 to Length(S) do begin C := UpCase(S[I]); case C of ' ': EndByte; '0'..'9': begin Inc(N); if N > 2 then Invalid; B := (B shl 4) or (Ord(C) - Ord('0')); end; 'A'..'F': begin Inc(N); if N > 2 then Invalid; B := (B shl 4) or (10 + Ord(C) - Ord('A')); end; else Invalid; end; end; EndByte; end; function ConvertDWordString(const S: String): String; var DW: DWORD; E: Integer; begin Result := Trim(S); { Only check if it doesn't start with a constant } if (Result = '') or (Result[1] <> '{') then begin Val(Result, DW, E); if E <> 0 then AbortCompileParamError(SCompilerParamInvalid2, ParamRegistryValueData); { Not really necessary, but sanitize the value } Result := Format('$%x', [DW]); end; end; function ConvertQWordString(const S: String): String; var QW: Integer64; begin Result := Trim(S); { Only check if it doesn't start with a constant } if (Result = '') or (Result[1] <> '{') then begin if not StrToInteger64(Result, QW) then AbortCompileParamError(SCompilerParamInvalid2, ParamRegistryValueData); { Not really necessary, but sanitize the value } Result := Integer64ToStr(QW); end; end; var Values: array[TParam] of TParamValue; NewRegistryEntry: PSetupRegistryEntry; S, AData: String; begin ExtractParameters(Line, ParamInfo, Values); NewRegistryEntry := AllocMem(SizeOf(TSetupRegistryEntry)); try with NewRegistryEntry^ do begin MinVersion := SetupHeader.MinVersion; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, roCreateValueIfDoesntExist); 1: Include(Options, roUninsDeleteValue); 2: Include(Options, roUninsDeleteEntireKey); 3: Include(Options, roUninsDeleteEntireKeyIfEmpty); 4: Include(Options, roUninsClearValue); 5: Include(Options, roPreserveStringType); 6: Include(Options, roDeleteKey); 7: Include(Options, roDeleteValue); 8: Include(Options, roNoError); 9: Include(Options, roDontCreateKey); end; { Root } S := Uppercase(Trim(Values[paRoot].Data)); if Length(S) >= 2 then begin { Check for '32' or '64' suffix } if (S[Length(S)-1] = '3') and (S[Length(S)] = '2') then begin Include(Options, ro32Bit); SetLength(S, Length(S)-2); end else if (S[Length(S)-1] = '6') and (S[Length(S)] = '4') then begin Include(Options, ro64Bit); SetLength(S, Length(S)-2); end; end; if S = 'HKCR' then RootKey := HKEY_CLASSES_ROOT else if S = 'HKCU' then RootKey := HKEY_CURRENT_USER else if S = 'HKLM' then RootKey := HKEY_LOCAL_MACHINE else if S = 'HKU' then RootKey := HKEY_USERS else if S = 'HKCC' then RootKey := HKEY_CURRENT_CONFIG else AbortCompileParamError(SCompilerParamInvalid2, ParamRegistryRoot); { Subkey } if (Values[paSubkey].Data <> '') and (Values[paSubkey].Data[1] = '\') then AbortCompileParamError(SCompilerParamNoPrecedingBackslash, ParamRegistrySubkey); Subkey := Values[paSubkey].Data; { ValueType } if Values[paValueType].Found then begin Values[paValueType].Data := Uppercase(Trim(Values[paValueType].Data)); if Values[paValueType].Data = 'NONE' then Typ := rtNone else if Values[paValueType].Data = 'STRING' then Typ := rtString else if Values[paValueType].Data = 'EXPANDSZ' then Typ := rtExpandString else if Values[paValueType].Data = 'MULTISZ' then Typ := rtMultiString else if Values[paValueType].Data = 'DWORD' then Typ := rtDWord else if Values[paValueType].Data = 'QWORD' then Typ := rtQWord else if Values[paValueType].Data = 'BINARY' then Typ := rtBinary else AbortCompileParamError(SCompilerParamInvalid2, ParamRegistryValueType); end; { ValueName } ValueName := Values[paValueName].Data; { ValueData } AData := Values[paValueData].Data; { Permissions } ProcessPermissionsParameter(Values[paPermissions].Data, AccessMasks, PermissionsEntry); { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (roUninsDeleteEntireKey in Options) and (roUninsDeleteEntireKeyIfEmpty in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsdeletekey', 'uninsdeletekeyifempty']); if (roUninsDeleteEntireKey in Options) and (roUninsClearValue in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsclearvalue', 'uninsdeletekey']); if (roUninsDeleteValue in Options) and (roUninsDeleteEntireKey in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsdeletevalue', 'uninsdeletekey']); if (roUninsDeleteValue in Options) and (roUninsClearValue in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'uninsdeletevalue', 'uninsclearvalue']); { Safety checks } if ((roUninsDeleteEntireKey in Options) or (roDeleteKey in Options)) and (CompareText(Subkey, 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment') = 0) then AbortCompileOnLine(SCompilerRegistryDeleteKeyProhibited); case Typ of rtString, rtExpandString, rtMultiString: ValueData := AData; rtDWord: ValueData := ConvertDWordString(AData); rtQWord: ValueData := ConvertQWordString(AData); rtBinary: ValueData := ConvertBinaryString(AData); end; CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); CheckConst(Subkey, MinVersion, []); CheckConst(ValueName, MinVersion, []); case Typ of rtString, rtExpandString: CheckConst(ValueData, MinVersion, [acOldData]); rtMultiString: CheckConst(ValueData, MinVersion, [acOldData, acBreak]); rtDWord: CheckConst(ValueData, MinVersion, []); end; end; except SEFreeRec(NewRegistryEntry, SetupRegistryEntryStrings, SetupRegistryEntryAnsiStrings); raise; end; WriteDebugEntry(deRegistry, RegistryEntries.Count); RegistryEntries.Add(NewRegistryEntry); end; procedure TSetupCompiler.EnumDelete(const Line: PChar; const Ext: Integer); type TParam = (paType, paName, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamDeleteType = 'Type'; ParamDeleteName = 'Name'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamDeleteType; Flags: [piRequired]), (Name: ParamDeleteName; Flags: [piRequired, piNoEmpty]), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Types: array[TSetupDeleteType] of PChar = ( 'files', 'filesandordirs', 'dirifempty'); var Values: array[TParam] of TParamValue; NewDeleteEntry: PSetupDeleteEntry; Valid: Boolean; J: TSetupDeleteType; begin ExtractParameters(Line, ParamInfo, Values); NewDeleteEntry := AllocMem(SizeOf(TSetupDeleteEntry)); try with NewDeleteEntry^ do begin MinVersion := SetupHeader.MinVersion; { Type } Values[paType].Data := Trim(Values[paType].Data); Valid := False; for J := Low(J) to High(J) do if StrIComp(Types[J], PChar(Values[paType].Data)) = 0 then begin DeleteType := J; Valid := True; Break; end; if not Valid then AbortCompileParamError(SCompilerParamInvalid2, ParamDeleteType); { Name } Name := Values[paName].Data; { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); CheckConst(Name, MinVersion, []); end; except SEFreeRec(NewDeleteEntry, SetupDeleteEntryStrings, SetupDeleteEntryAnsiStrings); raise; end; if Ext = 0 then begin WriteDebugEntry(deInstallDelete, InstallDeleteEntries.Count); InstallDeleteEntries.Add(NewDeleteEntry); end else begin WriteDebugEntry(deUninstallDelete, UninstallDeleteEntries.Count); UninstallDeleteEntries.Add(NewDeleteEntry); end; end; procedure TSetupCompiler.EnumFiles(const Line: PChar; const Ext: Integer); function EscapeBraces(const S: String): String; { Changes all '{' to '{{' } var I: Integer; begin Result := S; I := 1; while I <= Length(Result) do begin if Result[I] = '{' then begin Insert('{', Result, I); Inc(I); {$IFDEF UNICODE} end; {$ELSE} end else if Result[I] in CompilerLeadBytes then Inc(I); {$ENDIF} Inc(I); end; end; type TParam = (paFlags, paSource, paDestDir, paDestName, paCopyMode, paAttribs, paPermissions, paFontInstall, paExcludes, paExternalSize, paStrongAssemblyName, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamFilesSource = 'Source'; ParamFilesDestDir = 'DestDir'; ParamFilesDestName = 'DestName'; ParamFilesCopyMode = 'CopyMode'; ParamFilesAttribs = 'Attribs'; ParamFilesPermissions = 'Permissions'; ParamFilesFontInstall = 'FontInstall'; ParamFilesExcludes = 'Excludes'; ParamFilesExternalSize = 'ExternalSize'; ParamFilesStrongAssemblyName = 'StrongAssemblyName'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamFilesSource; Flags: [piRequired, piNoEmpty, piNoQuotes]), (Name: ParamFilesDestDir; Flags: [piNoEmpty, piNoQuotes]), (Name: ParamFilesDestName; Flags: [piNoEmpty, piNoQuotes]), (Name: ParamFilesCopyMode; Flags: []), (Name: ParamFilesAttribs; Flags: []), (Name: ParamFilesPermissions; Flags: []), (Name: ParamFilesFontInstall; Flags: [piNoEmpty]), (Name: ParamFilesExcludes; Flags: []), (Name: ParamFilesExternalSize; Flags: []), (Name: ParamFilesStrongAssemblyName; Flags: [piNoEmpty]), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..37] of PChar = ( 'confirmoverwrite', 'uninsneveruninstall', 'isreadme', 'regserver', 'sharedfile', 'restartreplace', 'deleteafterinstall', 'comparetimestamp', 'fontisnttruetype', 'regtypelib', 'external', 'skipifsourcedoesntexist', 'overwritereadonly', 'onlyifdestfileexists', 'recursesubdirs', 'noregerror', 'allowunsafefiles', 'uninsrestartdelete', 'onlyifdoesntexist', 'ignoreversion', 'promptifolder', 'dontcopy', 'uninsremovereadonly', 'sortfilesbyextension', 'touch', 'replacesameversion', 'noencryption', 'nocompression', 'dontverifychecksum', 'uninsnosharedfileprompt', 'createallsubdirs', '32bit', '64bit', 'solidbreak', 'setntfscompression', 'unsetntfscompression', 'sortfilesbyname', 'gacinstall'); AttribsFlags: array[0..2] of PChar = ( 'readonly', 'hidden', 'system'); AccessMasks: array[0..2] of TNameAndAccessMask = ( (Name: 'full'; Mask: $1F01FF), (Name: 'modify'; Mask: $1301BF), (Name: 'readexec'; Mask: $1200A9)); var Values: array[TParam] of TParamValue; NewFileEntry, PrevFileEntry: PSetupFileEntry; NewFileLocationEntry: PSetupFileLocationEntry; VersionNumbers: TFileVersionNumbers; SourceWildcard, ADestDir, ADestName, AInstallFontName, AStrongAssemblyName: String; AExcludes: TStringList; ReadmeFile, ExternalFile, SourceIsWildcard, RecurseSubdirs, AllowUnsafeFiles, Touch, NoCompression, NoEncryption, SolidBreak: Boolean; type PFileListRec = ^TFileListRec; TFileListRec = record Name: String; Size: Integer64; end; PDirListRec = ^TDirListRec; TDirListRec = record Name: String; end; procedure CheckForUnsafeFile(const Filename, SourceFile: String; const IsRegistered: Boolean); { This generates errors on "unsafe files" } const UnsafeSysFiles: array[0..13] of String = ( 'ADVAPI32.DLL', 'COMCTL32.DLL', 'COMDLG32.DLL', 'GDI32.DLL', 'KERNEL32.DLL', 'MSCOREE.DLL', 'RICHED32.DLL', 'SHDOCVW.DLL', 'SHELL32.DLL', 'SHLWAPI.DLL', 'URLMON.DLL', 'USER32.DLL', 'UXTHEME.DLL', 'WININET.DLL'); UnsafeNonSysRegFiles: array[0..5] of String = ( 'COMCAT.DLL', 'MSVBVM50.DLL', 'MSVBVM60.DLL', 'OLEAUT32.DLL', 'OLEPRO32.DLL', 'STDOLE2.TLB'); var I: Integer; begin if AllowUnsafeFiles then Exit; if ADestDir = '{sys}\' then begin { Files that must NOT be deployed to the user's System directory } { Any DLL deployed from system's own System directory } if not ExternalFile and (CompareText(PathExtractExt(Filename), '.DLL') = 0) and (PathCompare(PathExpand(PathExtractDir(SourceFile)), GetSystemDir) = 0) then AbortCompileOnLine(SCompilerFilesSystemDirUsed); { CTL3D32.DLL } if not ExternalFile and (CompareText(Filename, 'CTL3D32.DLL') = 0) and (NewFileEntry^.MinVersion.WinVersion <> 0) and FileSizeAndCRCIs(SourceFile, 27136, $28A66C20) then AbortCompileOnLineFmt(SCompilerFilesUnsafeFile, ['CTL3D32.DLL, Windows NT-specific version']); { Remaining files } for I := Low(UnsafeSysFiles) to High(UnsafeSysFiles) do if CompareText(Filename, UnsafeSysFiles[I]) = 0 then AbortCompileOnLineFmt(SCompilerFilesUnsafeFile, [UnsafeSysFiles[I]]); end else begin { Files that MUST be deployed to the user's System directory } if IsRegistered then for I := Low(UnsafeNonSysRegFiles) to High(UnsafeNonSysRegFiles) do if CompareText(Filename, UnsafeNonSysRegFiles[I]) = 0 then AbortCompileOnLineFmt(SCompilerFilesSystemDirNotUsed, [UnsafeNonSysRegFiles[I]]); end; end; function IsExcluded(Text: String): Boolean; function CountBackslashes(S: PChar): Integer; begin Result := 0; while True do begin S := PathStrScan(S, '\'); if S = nil then Break; Inc(Result); Inc(S); end; end; var I, J, TB, PB: Integer; T, P, TStart, TEnd: PChar; MatchFront: Boolean; begin if AExcludes.Count > 0 then begin Text := PathLowercase(Text); UniqueString(Text); T := PChar(Text); TB := CountBackslashes(T); for I := 0 to AExcludes.Count-1 do begin P := PChar(AExcludes[I]); { Leading backslash in an exclude pattern means 'match at the front instead of the end' } MatchFront := False; if P^ = '\' then begin MatchFront := True; Inc(P); end; PB := CountBackslashes(P); { The text must contain at least as many backslashes as the pattern for a match to be possible } if TB >= PB then begin TStart := T; if not MatchFront then begin { If matching at the end, advance TStart so that TStart and P point to the same number of components } for J := 1 to TB - PB do TStart := PathStrScan(TStart, '\') + 1; TEnd := nil; end else begin { If matching at the front, clip T to the same number of components as P } TEnd := T; for J := 1 to PB do TEnd := PathStrScan(TEnd, '\') + 1; TEnd := PathStrScan(TEnd, '\'); if Assigned(TEnd) then TEnd^ := #0; end; if WildcardMatch(TStart, P) then begin Result := True; Exit; end; { Put back any backslash that was temporarily null'ed } if Assigned(TEnd) then TEnd^ := '\'; end; end; end; Result := False; end; procedure AddToFileList(const FileList: TList; const Filename: String; const SizeLo, SizeHi: LongWord); var Rec: PFileListRec; begin FileList.Expand; New(Rec); Rec.Name := Filename; Rec.Size.Lo := SizeLo; Rec.Size.Hi := SizeHi; FileList.Add(Rec); end; procedure AddToDirList(const DirList: TList; const Dirname: String); var Rec: PDirListRec; begin DirList.Expand; New(Rec); Rec.Name := Dirname; DirList.Add(Rec); end; procedure BuildFileList(const SearchBaseDir, SearchSubDir, SearchWildcard: String; FileList, DirList: TList; CreateAllSubDirs: Boolean); { Searches for any non excluded files matching "SearchBaseDir + SearchSubDir + SearchWildcard" and adds them to FileList. } var SearchFullPath, FileName: String; H: THandle; FindData: TWin32FindData; OldFileListCount, OldDirListCount: Integer; begin SearchFullPath := SearchBaseDir + SearchSubDir + SearchWildcard; OldFileListCount := FileList.Count; OldDirListCount := DirList.Count; H := FindFirstFile(PChar(SearchFullPath), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0 then Continue; if SourceIsWildcard then begin if FindData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN <> 0 then Continue; FileName := FindData.cFileName; end else FileName := SearchWildcard; { use the case specified in the script } if IsExcluded(SearchSubDir + FileName) then Continue; AddToFileList(FileList, SearchSubDir + FileName, FindData.nFileSizeLow, FindData.nFileSizeHigh); CallIdleProc; until not SourceIsWildcard or not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end else CallIdleProc; if RecurseSubdirs then begin H := FindFirstFile(PChar(SearchBaseDir + SearchSubDir + '*'), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) and (FindData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN = 0) and (StrComp(FindData.cFileName, '.') <> 0) and (StrComp(FindData.cFileName, '..') <> 0) and not IsExcluded(SearchSubDir + FindData.cFileName) then BuildFileList(SearchBaseDir, SearchSubDir + FindData.cFileName + '\', SearchWildcard, FileList, DirList, CreateAllSubDirs); until not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end; end; if SearchSubDir <> '' then begin { If both FileList and DirList didn't change size, this subdir won't be created during install, so add it to DirList now if CreateAllSubDirs is set } if CreateAllSubDirs and (FileList.Count = OldFileListCount) and (DirList.Count = OldDirListCount) then AddToDirList(DirList, SearchSubDir); end; end; procedure ProcessFileList(const FileListBaseDir: String; FileList: TList); var FileListRec: PFileListRec; CheckName: String; SourceFile: String; I, J: Integer; NewRunEntry: PSetupRunEntry; begin for I := 0 to FileList.Count-1 do begin FileListRec := FileList[I]; if NewFileEntry = nil then begin NewFileEntry := AllocMem(SizeOf(TSetupFileEntry)); SEDuplicateRec(PrevFileEntry, NewFileEntry, SizeOf(TSetupFileEntry), SetupFileEntryStrings, SetupFileEntryAnsiStrings); end; if Ext = 0 then begin if ADestName = '' then begin if not ExternalFile then NewFileEntry^.DestName := ADestDir + EscapeBraces(FileListRec.Name) else { Don't append the filename to DestName on 'external' files; it will be determined during installation } NewFileEntry^.DestName := ADestDir; end else begin if not ExternalFile then NewFileEntry^.DestName := ADestDir + EscapeBraces(PathExtractPath(FileListRec.Name)) + ADestName else NewFileEntry^.DestName := ADestDir + ADestName; { ^ user is already required to escape '{' in DestName } Include(NewFileEntry^.Options, foCustomDestName); end; end else NewFileEntry^.DestName := ''; SourceFile := FileListBaseDir + FileListRec.Name; NewFileLocationEntry := nil; if not ExternalFile then begin if not DontMergeDuplicateFiles then begin { See if the source filename is already in the list of files to be compressed. If so, merge it. } J := FileLocationEntryFilenames.CaseInsensitiveIndexOf(SourceFile); if J <> -1 then begin NewFileLocationEntry := FileLocationEntries[J]; NewFileEntry^.LocationEntry := J; end; end; if NewFileLocationEntry = nil then begin NewFileLocationEntry := AllocMem(SizeOf(TSetupFileLocationEntry)); SetupHeader.CompressMethod := CompressMethod; FileLocationEntries.Add(NewFileLocationEntry); FileLocationEntryFilenames.Add(SourceFile); NewFileEntry^.LocationEntry := FileLocationEntries.Count-1; if NewFileEntry^.FileType = ftUninstExe then Include(NewFileLocationEntry^.Flags, foIsUninstExe); Inc6464(TotalBytesToCompress, FileListRec.Size); if SetupHeader.CompressMethod <> cmStored then Include(NewFileLocationEntry^.Flags, foChunkCompressed); if shEncryptionUsed in SetupHeader.Options then Include(NewFileLocationEntry^.Flags, foChunkEncrypted); if SolidBreak and UseSolidCompression then begin Include(NewFileLocationEntry^.Flags, foSolidBreak); { If the entry matches multiple files, it should only break prior to compressing the first one } SolidBreak := False; end; end; if Touch then Include(NewFileLocationEntry^.Flags, foTouch); { Note: "nocompression"/"noencryption" on one file makes all merged copies uncompressed/unencrypted too } if NoCompression then Exclude(NewFileLocationEntry^.Flags, foChunkCompressed); if NoEncryption then Exclude(NewFileLocationEntry^.Flags, foChunkEncrypted); end else begin NewFileEntry^.SourceFilename := SourceFile; NewFileEntry^.LocationEntry := -1; end; { Read version info } if not ExternalFile and not(foIgnoreVersion in NewFileEntry^.Options) and (NewFileLocationEntry^.Flags * [foVersionInfoValid, foVersionInfoNotValid] = []) then begin AddStatus(Format(SCompilerStatusFilesVerInfo, [SourceFile])); { Windows versions prior to 2000 cannot read version info on 64-bit images. Throw an error rather than silently failing to read the version info (which could be dangerous). } if (Win32Platform <> VER_PLATFORM_WIN32_NT) or (Byte(GetVersion) < 5) then if Is64BitPEImage(SourceFile) then AbortCompileOnLine(SCompilerFilesCantReadVersionInfoOn64BitImage); if GetVersionNumbers(SourceFile, VersionNumbers) then begin NewFileLocationEntry^.FileVersionMS := VersionNumbers.MS; NewFileLocationEntry^.FileVersionLS := VersionNumbers.LS; Include(NewFileLocationEntry^.Flags, foVersionInfoValid); end else Include(NewFileLocationEntry^.Flags, foVersionInfoNotValid); end; { Safety checks } if Ext = 0 then begin if ADestName <> '' then CheckName := ADestName else CheckName := PathExtractName(FileListRec.Name); CheckForUnsafeFile(CheckName, SourceFile, (foRegisterServer in NewFileEntry^.Options) or (foRegisterTypeLib in NewFileEntry^.Options)); if (ADestDir = '{sys}\') and (foIgnoreVersion in NewFileEntry^.Options) and (CompareText(PathExtractExt(CheckName), '.scr') <> 0) then WarningsList.Add(Format(SCompilerFilesIgnoreVersionUsedUnsafely, [CheckName])); end; if ReadmeFile then begin NewRunEntry := AllocMem(Sizeof(TSetupRunEntry)); NewRunEntry.Name := NewFileEntry.DestName; NewRunEntry.Components := NewFileEntry.Components; NewRunEntry.Tasks := NewFileEntry.Tasks; NewRunEntry.Languages := NewFileEntry.Languages; NewRunEntry.Check := NewFileEntry.Check; NewRunEntry.BeforeInstall := ''; NewRunEntry.AfterInstall := ''; NewRunEntry.MinVersion := NewFileEntry.MinVersion; NewRunEntry.OnlyBelowVersion := NewFileEntry.OnlyBelowVersion; NewRunEntry.Options := [roShellExec, roSkipIfDoesntExist, roPostInstall, roSkipIfSilent, roRunAsOriginalUser]; NewRunEntry.ShowCmd := SW_SHOWNORMAL; NewRunEntry.Wait := rwNoWait; NewRunEntry.Verb := ''; RunEntries.Insert(0, NewRunEntry); ShiftDebugEntryIndexes(deRun); { because we inserted at the front } end; WriteDebugEntry(deFile, FileEntries.Count); FileEntries.Expand; PrevFileEntry := NewFileEntry; { nil before adding so there's no chance it could ever be double-freed } NewFileEntry := nil; FileEntries.Add(PrevFileEntry); CallIdleProc; end; end; procedure SortFileList(FileList: TList; L: Integer; const R: Integer; const ByExtension, ByName: Boolean); function Compare(const F1, F2: PFileListRec): Integer; function ComparePathStr(P1, P2: PChar): Integer; { Like CompareStr, but sorts backslashes correctly ('A\B' < 'AB\B') } var {$IFNDEF UNICODE} LastWasLeadByte: BOOL; {$ENDIF} C1, C2: Char; begin {$IFNDEF UNICODE} LastWasLeadByte := False; {$ENDIF} repeat C1 := P1^; if (C1 = '\') {$IFNDEF UNICODE} and not LastWasLeadByte {$ENDIF} then C1 := #1; C2 := P2^; if (C2 = '\') {$IFNDEF UNICODE} and not LastWasLeadByte {$ENDIF} then C2 := #1; Result := Ord(C1) - Ord(C2); if Result <> 0 then Break; if C1 = #0 then Break; {$IFNDEF UNICODE} if LastWasLeadByte then LastWasLeadByte := False else LastWasLeadByte := IsDBCSLeadByte(Ord(C1)); {$ENDIF} Inc(P1); Inc(P2); until False; end; var S1, S2: String; begin { Optimization: First check if we were passed the same string } if Pointer(F1.Name) = Pointer(F2.Name) then begin Result := 0; Exit; end; S1 := AnsiUppercase(F1.Name); { uppercase to mimic NTFS's sort order } S2 := AnsiUppercase(F2.Name); if ByExtension then Result := CompareStr(PathExtractExt(S1), PathExtractExt(S2)) else Result := 0; if ByName and (Result = 0) then Result := CompareStr(PathExtractName(S1), PathExtractName(S2)); if Result = 0 then begin { To avoid randomness in the sorting, sort by path and then name } Result := ComparePathStr(PChar(PathExtractPath(S1)), PChar(PathExtractPath(S2))); if Result = 0 then Result := CompareStr(S1, S2); end; end; var I, J: Integer; P: PFileListRec; begin repeat I := L; J := R; P := FileList[(L + R) shr 1]; repeat while Compare(FileList[I], P) < 0 do Inc(I); while Compare(FileList[J], P) > 0 do Dec(J); if I <= J then begin FileList.Exchange(I, J); Inc(I); Dec(J); end; until I > J; if L < J then SortFileList(FileList, L, J, ByExtension, ByName); L := I; until I >= R; end; procedure ProcessDirList(DirList: TList); var DirListRec: PDirListRec; NewDirEntry: PSetupDirEntry; BaseFileEntry: PSetupFileEntry; I: Integer; begin if NewFileEntry <> nil then { If NewFileEntry is still assigned it means ProcessFileList didn't process any files (i.e. only directories were matched) } BaseFileEntry := NewFileEntry else BaseFileEntry := PrevFileEntry; if not(foDontCopy in BaseFileEntry.Options) then begin for I := 0 to DirList.Count-1 do begin DirListRec := DirList[I]; NewDirEntry := AllocMem(Sizeof(TSetupDirEntry)); NewDirEntry.DirName := ADestDir + EscapeBraces(DirListRec.Name); NewDirEntry.Components := BaseFileEntry.Components; NewDirEntry.Tasks := BaseFileEntry.Tasks; NewDirEntry.Languages := BaseFileEntry.Languages; NewDirEntry.Check := BaseFileEntry.Check; NewDirEntry.BeforeInstall := ''; NewDirEntry.AfterInstall := ''; NewDirEntry.MinVersion := BaseFileEntry.MinVersion; NewDirEntry.OnlyBelowVersion := BaseFileEntry.OnlyBelowVersion; NewDirEntry.Attribs := 0; NewDirEntry.PermissionsEntry := -1; NewDirEntry.Options := []; DirEntries.Add(NewDirEntry); end; end; end; var FileList, DirList: TList; SortFilesByExtension, SortFilesByName: Boolean; I: Integer; begin CallIdleProc; if Ext = 0 then ExtractParameters(Line, ParamInfo, Values); AExcludes := TStringList.Create(); try PrevFileEntry := nil; NewFileEntry := AllocMem(SizeOf(TSetupFileEntry)); try with NewFileEntry^ do begin MinVersion := SetupHeader.MinVersion; PermissionsEntry := -1; ADestName := ''; ADestDir := ''; AInstallFontName := ''; AStrongAssemblyName := ''; ReadmeFile := False; ExternalFile := False; RecurseSubdirs := False; AllowUnsafeFiles := False; Touch := False; SortFilesByExtension := False; NoCompression := False; NoEncryption := False; SolidBreak := False; ExternalSize.Hi := 0; ExternalSize.Lo := 0; SortFilesByName := False; case Ext of 0: begin { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: Include(Options, foConfirmOverwrite); 1: Include(Options, foUninsNeverUninstall); 2: ReadmeFile := True; 3: Include(Options, foRegisterServer); 4: Include(Options, foSharedFile); 5: Include(Options, foRestartReplace); 6: Include(Options, foDeleteAfterInstall); 7: Include(Options, foCompareTimeStamp); 8: Include(Options, foFontIsntTrueType); 9: Include(Options, foRegisterTypeLib); 10: ExternalFile := True; 11: Include(Options, foSkipIfSourceDoesntExist); 12: Include(Options, foOverwriteReadOnly); 13: Include(Options, foOnlyIfDestFileExists); 14: RecurseSubdirs := True; 15: Include(Options, foNoRegError); 16: AllowUnsafeFiles := True; 17: Include(Options, foUninsRestartDelete); 18: Include(Options, foOnlyIfDoesntExist); 19: Include(Options, foIgnoreVersion); 20: Include(Options, foPromptIfOlder); 21: Include(Options, foDontCopy); 22: Include(Options, foUninsRemoveReadOnly); 23: SortFilesByExtension := True; 24: Touch := True; 25: Include(Options, foReplaceSameVersionIfContentsDiffer); 26: NoEncryption := True; 27: NoCompression := True; 28: Include(Options, foDontVerifyChecksum); 29: Include(Options, foUninsNoSharedFilePrompt); 30: Include(Options, foCreateAllSubDirs); 31: Include(Options, fo32Bit); 32: Include(Options, fo64Bit); 33: SolidBreak := True; 34: Include(Options, foSetNTFSCompression); 35: Include(Options, foUnsetNTFSCompression); 36: SortFilesByName := True; 37: Include(Options, foGacInstall); end; { Source } SourceWildcard := Values[paSource].Data; { DestDir } if Values[paDestDir].Found then ADestDir := Values[paDestDir].Data else begin if foDontCopy in Options then { DestDir is optional when the 'dontcopy' flag is used } ADestDir := '{tmp}' else AbortCompileParamError(SCompilerParamNotSpecified, ParamFilesDestDir); end; { DestName } if ConstPos('\', Values[paDestName].Data) <> 0 then AbortCompileParamError(SCompilerParamNoBackslash, ParamFilesDestName); ADestName := Values[paDestName].Data; { CopyMode } if Values[paCopyMode].Found then begin Values[paCopyMode].Data := Trim(Values[paCopyMode].Data); if CompareText(Values[paCopyMode].Data, 'normal') = 0 then begin Include(Options, foPromptIfOlder); WarningsList.Add(Format(SCompilerFilesWarningCopyMode, ['normal', 'promptifolder', 'promptifolder'])); end else if CompareText(Values[paCopyMode].Data, 'onlyifdoesntexist') = 0 then begin Include(Options, foOnlyIfDoesntExist); WarningsList.Add(Format(SCompilerFilesWarningCopyMode, ['onlyifdoesntexist', 'onlyifdoesntexist', 'onlyifdoesntexist'])); end else if CompareText(Values[paCopyMode].Data, 'alwaysoverwrite') = 0 then begin Include(Options, foIgnoreVersion); WarningsList.Add(Format(SCompilerFilesWarningCopyMode, ['alwaysoverwrite', 'ignoreversion', 'ignoreversion'])); end else if CompareText(Values[paCopyMode].Data, 'alwaysskipifsameorolder') = 0 then begin WarningsList.Add(SCompilerFilesWarningASISOO); end else if CompareText(Values[paCopyMode].Data, 'dontcopy') = 0 then begin Include(Options, foDontCopy); WarningsList.Add(Format(SCompilerFilesWarningCopyMode, ['dontcopy', 'dontcopy', 'dontcopy'])); end else AbortCompileParamError(SCompilerParamInvalid2, ParamFilesCopyMode); end; { Attribs } while True do case ExtractFlag(Values[paAttribs].Data, AttribsFlags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamFilesAttribs); 0: Attribs := Attribs or FILE_ATTRIBUTE_READONLY; 1: Attribs := Attribs or FILE_ATTRIBUTE_HIDDEN; 2: Attribs := Attribs or FILE_ATTRIBUTE_SYSTEM; end; { Permissions } ProcessPermissionsParameter(Values[paPermissions].Data, AccessMasks, PermissionsEntry); { FontInstall } AInstallFontName := Values[paFontInstall].Data; { StrongAssemblyName } AStrongAssemblyName := Values[paStrongAssemblyName].Data; { Excludes } ProcessWildcardsParameter(Values[paExcludes].Data, AExcludes, SCompilerFilesExcludeTooLong); { ExternalSize } if Values[paExternalSize].Found then begin if not ExternalFile then AbortCompileOnLine(SCompilerFilesCantHaveNonExternalExternalSize); if not StrToInteger64(Values[paExternalSize].Data, ExternalSize) then AbortCompileParamError(SCompilerParamInvalid2, ParamFilesExternalSize); Include(Options, foExternalSizePreset); end; { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); end; 1: begin SourceWildcard := ''; FileType := ftUninstExe; { Ordinary hash comparison on unins*.exe won't really work since Setup modifies the file after extracting it. Force same version to always be overwritten by including the special foOverwriteSameVersion option. } Options := [foOverwriteSameVersion]; ExternalFile := True; end; end; if (ADestDir = '{tmp}') or (Copy(ADestDir, 1, 4) = '{tmp}\') then Include(Options, foDeleteAfterInstall); if foDeleteAfterInstall in Options then begin if foRestartReplace in Options then AbortCompileOnLineFmt(SCompilerFilesTmpBadFlag, ['restartreplace']); if foUninsNeverUninstall in Options then AbortCompileOnLineFmt(SCompilerFilesTmpBadFlag, ['uninsneveruninstall']); if foRegisterServer in Options then AbortCompileOnLineFmt(SCompilerFilesTmpBadFlag, ['regserver']); if foRegisterTypeLib in Options then AbortCompileOnLineFmt(SCompilerFilesTmpBadFlag, ['regtypelib']); if foSharedFile in Options then AbortCompileOnLineFmt(SCompilerFilesTmpBadFlag, ['sharedfile']); if foGacInstall in Options then AbortCompileOnLineFmt(SCompilerFilesTmpBadFlag, ['gacinstall']); Include(Options, foUninsNeverUninstall); end; if (fo32Bit in Options) and (fo64Bit in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, '32bit', '64bit']); if AInstallFontName <> '' then begin if not(foFontIsntTrueType in Options) then AInstallFontName := AInstallFontName + ' (TrueType)'; InstallFontName := AInstallFontName; end; if (foGacInstall in Options) and (AStrongAssemblyName = '') then AbortCompileOnLine(SCompilerFilesStrongAssemblyNameMustBeSpecified); if AStrongAssemblyName <> '' then StrongAssemblyName := AStrongAssemblyName; if not NoCompression and (foDontVerifyChecksum in Options) then AbortCompileOnLineFmt(SCompilerParamFlagMissing, ['nocompression', 'dontverifychecksum']); if ExternalFile and (AExcludes.Count > 0) then AbortCompileOnLine(SCompilerFilesCantHaveExternalExclude); if not RecurseSubdirs and (foCreateAllSubDirs in Options) then AbortCompileOnLineFmt(SCompilerParamFlagMissing, ['recursesubdirs', 'createallsubdirs']); if (foSetNTFSCompression in Options) and (foUnsetNTFSCompression in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'setntfscompression', 'unsetntfscompression']); if (foSharedFile in Options) and (Copy(ADestDir, 1, Length('{syswow64}')) = '{syswow64}') then WarningsList.Add(SCompilerFilesWarningSharedFileSysWow64); SourceIsWildcard := IsWildcard(SourceWildcard); if ExternalFile then begin if RecurseSubdirs then Include(Options, foRecurseSubDirsExternal); CheckConst(SourceWildcard, MinVersion, []); end; if (ADestName <> '') and SourceIsWildcard then AbortCompileOnLine(SCompilerFilesDestNameCantBeSpecified); CheckConst(ADestDir, MinVersion, []); ADestDir := AddBackslash(ADestDir); CheckConst(ADestName, MinVersion, []); if not ExternalFile then SourceWildcard := PrependSourceDirName(SourceWildcard); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); end; FileList := TLowFragList.Create(); DirList := TLowFragList.Create(); try if not ExternalFile then begin BuildFileList(PathExtractPath(SourceWildcard), '', PathExtractName(SourceWildcard), FileList, DirList, foCreateAllSubDirs in NewFileEntry.Options); if FileList.Count > 1 then SortFileList(FileList, 0, FileList.Count-1, SortFilesByExtension, SortFilesByName); end else AddToFileList(FileList, SourceWildcard, 0, 0); if FileList.Count > 0 then begin if not ExternalFile then ProcessFileList(PathExtractPath(SourceWildcard), FileList) else ProcessFileList('', FileList); end; if DirList.Count > 0 then begin { Dirs found that need to be created. Can only happen if not external. } ProcessDirList(DirList); end; if (FileList.Count = 0) and (DirList.Count = 0) then begin { Nothing found. Can only happen if not external. } if not(foSkipIfSourceDoesntExist in NewFileEntry^.Options) then begin if SourceIsWildcard then AbortCompileOnLineFmt(SCompilerFilesWildcardNotMatched, [SourceWildcard]) else AbortCompileOnLineFmt(SCompilerSourceFileDoesntExist, [SourceWildcard]); end; end; finally for I := DirList.Count-1 downto 0 do Dispose(PDirListRec(DirList[I])); DirList.Free(); for I := FileList.Count-1 downto 0 do Dispose(PFileListRec(FileList[I])); FileList.Free(); end; finally { If NewFileEntry is still assigned at this point, either an exception occurred or no files were matched } SEFreeRec(NewFileEntry, SetupFileEntryStrings, SetupFileEntryAnsiStrings); end; finally AExcludes.Free(); end; end; procedure UpdateTimeStamp(H: THandle); var FT: TFileTime; begin GetSystemTimeAsFileTime(FT); SetFileTime(H, nil, nil, @FT); end; procedure TSetupCompiler.EnumRun(const Line: PChar; const Ext: Integer); type TParam = (paFlags, paFilename, paParameters, paWorkingDir, paRunOnceId, paDescription, paStatusMsg, paVerb, paComponents, paTasks, paLanguages, paCheck, paBeforeInstall, paAfterInstall, paMinVersion, paOnlyBelowVersion); const ParamRunFilename = 'Filename'; ParamRunParameters = 'Parameters'; ParamRunWorkingDir = 'WorkingDir'; ParamRunRunOnceId = 'RunOnceId'; ParamRunDescription = 'Description'; ParamRunStatusMsg = 'StatusMsg'; ParamRunVerb = 'Verb'; ParamInfo: array[TParam] of TParamInfo = ( (Name: ParamCommonFlags; Flags: []), (Name: ParamRunFilename; Flags: [piRequired, piNoEmpty, piNoQuotes]), (Name: ParamRunParameters; Flags: []), (Name: ParamRunWorkingDir; Flags: []), (Name: ParamRunRunOnceId; Flags: []), (Name: ParamRunDescription; Flags: []), (Name: ParamRunStatusMsg; Flags: []), (Name: ParamRunVerb; Flags: []), (Name: ParamCommonComponents; Flags: []), (Name: ParamCommonTasks; Flags: []), (Name: ParamCommonLanguages; Flags: []), (Name: ParamCommonCheck; Flags: []), (Name: ParamCommonBeforeInstall; Flags: []), (Name: ParamCommonAfterInstall; Flags: []), (Name: ParamCommonMinVersion; Flags: []), (Name: ParamCommonOnlyBelowVersion; Flags: [])); Flags: array[0..17] of PChar = ( 'nowait', 'waituntilidle', 'shellexec', 'skipifdoesntexist', 'runminimized', 'runmaximized', 'showcheckbox', 'postinstall', 'unchecked', 'skipifsilent', 'skipifnotsilent', 'hidewizard', 'runhidden', 'waituntilterminated', '32bit', '64bit', 'runasoriginaluser', 'runascurrentuser'); var Values: array[TParam] of TParamValue; NewRunEntry: PSetupRunEntry; WaitFlagSpecified, RunAsOriginalUser, RunAsCurrentUser: Boolean; begin ExtractParameters(Line, ParamInfo, Values); NewRunEntry := AllocMem(SizeOf(TSetupRunEntry)); try with NewRunEntry^ do begin MinVersion := SetupHeader.MinVersion; ShowCmd := SW_SHOWNORMAL; WaitFlagSpecified := False; RunAsOriginalUser := False; RunAsCurrentUser := False; { Flags } while True do case ExtractFlag(Values[paFlags].Data, Flags) of -2: Break; -1: AbortCompileParamError(SCompilerParamUnknownFlag2, ParamCommonFlags); 0: begin if WaitFlagSpecified then AbortCompileOnLine(SCompilerRunMultipleWaitFlags); Wait := rwNoWait; WaitFlagSpecified := True; end; 1: begin if WaitFlagSpecified then AbortCompileOnLine(SCompilerRunMultipleWaitFlags); Wait := rwWaitUntilIdle; WaitFlagSpecified := True; end; 2: Include(Options, roShellExec); 3: Include(Options, roSkipIfDoesntExist); 4: ShowCmd := SW_SHOWMINNOACTIVE; 5: ShowCmd := SW_SHOWMAXIMIZED; 6: begin if (Ext = 1) then AbortCompileParamError(SCompilerParamUnsupportedFlag, ParamCommonFlags); WarningsList.Add(Format(SCompilerRunFlagObsolete, ['showcheckbox', 'postinstall'])); Include(Options, roPostInstall); end; 7: begin if (Ext = 1) then AbortCompileParamError(SCompilerParamUnsupportedFlag, ParamCommonFlags); Include(Options, roPostInstall); end; 8: begin if (Ext = 1) then AbortCompileParamError(SCompilerParamUnsupportedFlag, ParamCommonFlags); Include(Options, roUnchecked); end; 9: begin if (Ext = 1) then AbortCompileParamError(SCompilerParamUnsupportedFlag, ParamCommonFlags); Include(Options, roSkipIfSilent); end; 10: begin if (Ext = 1) then AbortCompileParamError(SCompilerParamUnsupportedFlag, ParamCommonFlags); Include(Options, roSkipIfNotSilent); end; 11: Include(Options, roHideWizard); 12: ShowCmd := SW_HIDE; 13: begin if WaitFlagSpecified then AbortCompileOnLine(SCompilerRunMultipleWaitFlags); Wait := rwWaitUntilTerminated; WaitFlagSpecified := True; end; 14: Include(Options, roRun32Bit); 15: Include(Options, roRun64Bit); 16: begin if (Ext = 1) then AbortCompileParamError(SCompilerParamUnsupportedFlag, ParamCommonFlags); RunAsOriginalUser := True; end; 17: RunAsCurrentUser := True; end; if not WaitFlagSpecified then begin if roShellExec in Options then Wait := rwNoWait else Wait := rwWaitUntilTerminated; end; if RunAsOriginalUser and RunAsCurrentUser then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, 'runasoriginaluser', 'runascurrentuser']); if RunAsOriginalUser or (not RunAsCurrentUser and (roPostInstall in Options)) then Include(Options, roRunAsOriginalUser); { Filename } Name := Values[paFilename].Data; { Parameters } Parameters := Values[paParameters].Data; { WorkingDir } WorkingDir := Values[paWorkingDir].Data; { RunOnceId } if (Ext = 0) and (Values[paRunOnceId].Data <> '') then AbortCompileOnLine(SCompilerRunCantUseRunOnceId); RunOnceId := Values[paRunOnceId].Data; { Description } if (Ext = 1) and (Values[paDescription].Data <> '') then AbortCompileOnLine(SCompilerUninstallRunCantUseDescription); Description := Values[paDescription].Data; { StatusMsg } StatusMsg := Values[paStatusMsg].Data; { Verb } if not (roShellExec in Options) and Values[paVerb].Found then AbortCompileOnLineFmt(SCompilerParamFlagMissing2, ['shellexec', 'Verb']); Verb := Values[paVerb].Data; { Common parameters } ProcessExpressionParameter(ParamCommonComponents, Values[paComponents].Data, EvalComponentIdentifier, True, Components); ProcessExpressionParameter(ParamCommonTasks, Values[paTasks].Data, EvalTaskIdentifier, True, Tasks); ProcessExpressionParameter(ParamCommonLanguages, Values[paLanguages].Data, EvalLanguageIdentifier, False, Languages); Check := Values[paCheck].Data; BeforeInstall := Values[paBeforeInstall].Data; AfterInstall := Values[paAfterInstall].Data; ProcessMinVersionParameter(Values[paMinVersion], MinVersion); ProcessOnlyBelowVersionParameter(Values[paOnlyBelowVersion], OnlyBelowVersion); if (roRun32Bit in Options) and (roRun64Bit in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, '32bit', '64bit']); if (roRun32Bit in Options) and (roShellExec in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, '32bit', 'shellexec']); if (roRun64Bit in Options) and (roShellExec in Options) then AbortCompileOnLineFmt(SCompilerParamErrorBadCombo2, [ParamCommonFlags, '64bit', 'shellexec']); CheckCheckOrInstall(ParamCommonCheck, Check, cikCheck); CheckCheckOrInstall(ParamCommonBeforeInstall, BeforeInstall, cikInstall); CheckCheckOrInstall(ParamCommonAfterInstall, AfterInstall, cikInstall); CheckConst(Name, MinVersion, []); CheckConst(Parameters, MinVersion, []); CheckConst(WorkingDir, MinVersion, []); CheckConst(RunOnceId, MinVersion, []); CheckConst(Description, MinVersion, []); CheckConst(StatusMsg, MinVersion, []); CheckConst(Verb, MinVersion, []); end; except SEFreeRec(NewRunEntry, SetupRunEntryStrings, SetupRunEntryAnsiStrings); raise; end; if Ext = 0 then begin WriteDebugEntry(deRun, RunEntries.Count); RunEntries.Add(NewRunEntry) end else begin WriteDebugEntry(deUninstallRun, UninstallRunEntries.Count); UninstallRunEntries.Add(NewRunEntry); end; end; type TLanguagesParam = (paName, paMessagesFile, paLicenseFile, paInfoBeforeFile, paInfoAfterFile); const ParamLanguagesName = 'Name'; ParamLanguagesMessagesFile = 'MessagesFile'; ParamLanguagesLicenseFile = 'LicenseFile'; ParamLanguagesInfoBeforeFile = 'InfoBeforeFile'; ParamLanguagesInfoAfterFile = 'InfoAfterFile'; LanguagesParamInfo: array[TLanguagesParam] of TParamInfo = ( (Name: ParamLanguagesName; Flags: [piRequired, piNoEmpty]), (Name: ParamLanguagesMessagesFile; Flags: [piRequired, piNoEmpty]), (Name: ParamLanguagesLicenseFile; Flags: [piNoEmpty]), (Name: ParamLanguagesInfoBeforeFile; Flags: [piNoEmpty]), (Name: ParamLanguagesInfoAfterFile; Flags: [piNoEmpty])); {$IFDEF UNICODE} procedure TSetupCompiler.EnumLanguagesPre(const Line: PChar; const Ext: Integer); var Values: array[TLanguagesParam] of TParamValue; NewPreLangData: TPreLangData; Filename: String; begin ExtractParameters(Line, LanguagesParamInfo, Values); PreLangDataList.Expand; NewPreLangData := nil; try NewPreLangData := TPreLangData.Create; Filename := ''; InitPreLangData(NewPreLangData); { Name } if not IsValidIdentString(Values[paName].Data, False, False) then AbortCompileOnLine(SCompilerLanguagesBadName); NewPreLangData.Name := Values[paName].Data; { MessagesFile } Filename := Values[paMessagesFile].Data; except NewPreLangData.Free; raise; end; PreLangDataList.Add(NewPreLangData); ReadMessagesFromFilesPre(Filename, PreLangDataList.Count-1); end; {$ENDIF} procedure TSetupCompiler.EnumLanguages(const Line: PChar; const Ext: Integer); var Values: array[TLanguagesParam] of TParamValue; NewLanguageEntry: PSetupLanguageEntry; NewLangData: TLangData; Filename: String; begin ExtractParameters(Line, LanguagesParamInfo, Values); LanguageEntries.Expand; LangDataList.Expand; NewLangData := nil; NewLanguageEntry := AllocMem(SizeOf(TSetupLanguageEntry)); try NewLangData := TLangData.Create; Filename := ''; InitLanguageEntry(NewLanguageEntry^); { Name } if not IsValidIdentString(Values[paName].Data, False, False) then AbortCompileOnLine(SCompilerLanguagesBadName); NewLanguageEntry.Name := Values[paName].Data; { MessagesFile } Filename := Values[paMessagesFile].Data; { LicenseFile } if (Values[paLicenseFile].Data <> '') then begin AddStatus(Format(SCompilerStatusReadingInFile, [Values[paLicenseFile].Data])); ReadTextFile(PrependSourceDirName(Values[paLicenseFile].Data), LanguageEntries.Count, NewLanguageEntry.LicenseText); end; { InfoBeforeFile } if (Values[paInfoBeforeFile].Data <> '') then begin AddStatus(Format(SCompilerStatusReadingInFile, [Values[paInfoBeforeFile].Data])); ReadTextFile(PrependSourceDirName(Values[paInfoBeforeFile].Data), LanguageEntries.Count, NewLanguageEntry.InfoBeforeText); end; { InfoAfterFile } if (Values[paInfoAfterFile].Data <> '') then begin AddStatus(Format(SCompilerStatusReadingInFile, [Values[paInfoAfterFile].Data])); ReadTextFile(PrependSourceDirName(Values[paInfoAfterFile].Data), LanguageEntries.Count, NewLanguageEntry.InfoAfterText); end; except NewLangData.Free; SEFreeRec(NewLanguageEntry, SetupLanguageEntryStrings, SetupLanguageEntryAnsiStrings); raise; end; LanguageEntries.Add(NewLanguageEntry); LangDataList.Add(NewLangData); ReadMessagesFromFiles(Filename, LanguageEntries.Count-1); end; procedure TSetupCompiler.EnumMessages(const Line: PChar; const Ext: Integer); var P, P2: PChar; I, ID, LangIndex: Integer; N, M: String; begin P := StrScan(Line, '='); if P = nil then AbortCompileOnLine(SCompilerMessagesMissingEquals); SetString(N, Line, P - Line); N := Trim(N); LangIndex := ExtractLangIndex(Self, N, Ext, False); ID := GetEnumValue(TypeInfo(TSetupMessageID), 'msg' + N); if ID = -1 then begin if LangIndex = -2 then AbortCompileOnLineFmt(SCompilerMessagesNotRecognizedDefault, [N]); if ParseFilename = '' then WarningsList.Add(Format(SCompilerMessagesNotRecognizedWarning, [N])) else WarningsList.Add(Format(SCompilerMessagesNotRecognizedInFileWarning, [N, ParseFilename])); Exit; end; Inc(P); M := P; { Replace %n with actual CR/LF characters } P2 := PChar(M); while True do begin P2 := StrPos(P2, '%n'); if P2 = nil then Break; P2[0] := #13; P2[1] := #10; Inc(P2, 2); end; if LangIndex = -2 then begin { Special -2 value means store in DefaultLangData } DefaultLangData.Messages[TSetupMessageID(ID)] := M; DefaultLangData.MessagesDefined[TSetupMessageID(ID)] := True; end else begin for I := 0 to LangDataList.Count-1 do begin if (LangIndex <> -1) and (I <> LangIndex) then Continue; TLangData(LangDataList[I]).Messages[TSetupMessageID(ID)] := M; TLangData(LangDataList[I]).MessagesDefined[TSetupMessageID(ID)] := True; end; end; end; procedure TSetupCompiler.EnumCustomMessages(const Line: PChar; const Ext: Integer); function ExpandNewlines(const S: String): String; { Replaces '%n' with #13#10 } var L, I: Integer; begin Result := S; L := Length(Result); I := 1; while I < L do begin if Result[I] = '%' then begin if Result[I+1] = 'n' then begin Result[I] := #13; Result[I+1] := #10; end; Inc(I); end; Inc(I); end; end; var P: PChar; LangIndex: Integer; N: String; I: Integer; ExistingCustomMessageEntry, NewCustomMessageEntry: PSetupCustomMessageEntry; begin P := StrScan(Line, '='); if P = nil then AbortCompileOnLine(SCompilerMessagesMissingEquals); SetString(N, Line, P - Line); N := Trim(N); LangIndex := ExtractLangIndex(Self, N, Ext, False); Inc(P); CustomMessageEntries.Expand; NewCustomMessageEntry := AllocMem(SizeOf(TSetupCustomMessageEntry)); try if not IsValidIdentString(N, False, True) then AbortCompileOnLine(SCompilerCustomMessageBadName); { Delete existing entries} for I := CustomMessageEntries.Count-1 downto 0 do begin ExistingCustomMessageEntry := CustomMessageEntries[I]; if (CompareText(ExistingCustomMessageEntry.Name, N) = 0) and ((LangIndex = -1) or (ExistingCustomMessageEntry.LangIndex = LangIndex)) then begin SEFreeRec(ExistingCustomMessageEntry, SetupCustomMessageEntryStrings, SetupCustomMessageEntryAnsiStrings); CustomMessageEntries.Delete(I); end; end; { Setup the new one } NewCustomMessageEntry.Name := N; NewCustomMessageEntry.Value := ExpandNewlines(P); NewCustomMessageEntry.LangIndex := LangIndex; except SEFreeRec(NewCustomMessageEntry, SetupCustomMessageEntryStrings, SetupCustomMessageEntryAnsiStrings); raise; end; CustomMessageEntries.Add(NewCustomMessageEntry); end; procedure TSetupCompiler.CheckCustomMessageDefinitions; { Checks 'language completeness' of custom message constants } var MissingLang, Found: Boolean; I, J, K: Integer; CustomMessage1, CustomMessage2: PSetupCustomMessageEntry; begin for I := 0 to CustomMessageEntries.Count-1 do begin CustomMessage1 := PSetupCustomMessageEntry(CustomMessageEntries[I]); if CustomMessage1.LangIndex <> -1 then begin MissingLang := False; for J := 0 to LanguageEntries.Count-1 do begin { Check whether the outer custom message name exists for this language } Found := False; for K := 0 to CustomMessageEntries.Count-1 do begin CustomMessage2 := PSetupCustomMessageEntry(CustomMessageEntries[K]); if CompareText(CustomMessage1.Name, CustomMessage2.Name) = 0 then begin if (CustomMessage2.LangIndex = -1) or (CustomMessage2.LangIndex = J) then begin Found := True; Break; end; end; end; if not Found then begin WarningsList.Add(Format(SCompilerCustomMessagesMissingLangWarning, [CustomMessage1.Name, PSetupLanguageEntry(LanguageEntries[J]).Name, PSetupLanguageEntry(LanguageEntries[CustomMessage1.LangIndex]).Name])); MissingLang := True; end; end; if MissingLang then begin { The custom message CustomMessage1.Name is not 'language complete'. Force it to be by setting CustomMessage1.LangIndex to -1. This will cause languages that do not define the custom message to use this one (i.e. the first definition of it). Note: Languages that do define the custom message in subsequent entries will override this entry, since Setup looks for the *last* matching entry. } CustomMessage1.LangIndex := -1; end; end; end; end; procedure TSetupCompiler.CheckCustomMessageReferences; { Checks existance of expected custom message constants } var LineInfo: TLineInfo; Found: Boolean; S: String; I, J: Integer; begin for I := 0 to ExpectedCustomMessageNames.Count-1 do begin Found := False; S := ExpectedCustomMessageNames[I]; for J := 0 to CustomMessageEntries.Count-1 do begin if CompareText(PSetupCustomMessageEntry(CustomMessageEntries[J]).Name, S) = 0 then begin Found := True; Break; end; end; if not Found then begin LineInfo := TLineInfo(ExpectedCustomMessageNames.Objects[I]); LineFilename := LineInfo.Filename; LineNumber := LineInfo.FileLineNumber; AbortCompileFmt(SCompilerCustomMessagesMissingName, [S]); end; end; end; {$IFDEF UNICODE} procedure TSetupCompiler.InitPreLangData(const APreLangData: TPreLangData); { Initializes a TPreLangData object with the default settings } begin with APreLangData do begin Name := 'default'; LanguageCodePage := 0; end; end; {$ENDIF} procedure TSetupCompiler.InitLanguageEntry(var ALanguageEntry: TSetupLanguageEntry); { Initializes a TSetupLanguageEntry record with the default settings } begin with ALanguageEntry do begin Name := 'default'; LanguageName := 'English'; LanguageID := $0409; { U.S. English } {$IFNDEF UNICODE} LanguageCodePage := 0; {$ENDIF} DialogFontName := DefaultDialogFontName; DialogFontSize := 8; TitleFontName := 'Arial'; TitleFontSize := 29; WelcomeFontName := 'Verdana'; WelcomeFontSize := 12; CopyrightFontName := 'Arial'; CopyrightFontSize := 8; LicenseText := ''; InfoBeforeText := ''; InfoAfterText := ''; end; end; {$IFDEF UNICODE} procedure TSetupCompiler.ReadMessagesFromFilesPre(const AFiles: String; const ALangIndex: Integer); var S, Filename: String; AnsiLanguageFile: Boolean; begin S := AFiles; while True do begin Filename := ExtractStr(S, ','); if Filename = '' then Break; Filename := PathExpand(PrependSourceDirName(Filename)); AnsiLanguageFile := CompareText(PathExtractExt(Filename), '.islu') <> 0; AddStatus(Format(SCompilerStatusReadingInFile, [Filename])); EnumIniSection(EnumLangOptionsPre, 'LangOptions', ALangIndex, False, True, Filename, AnsiLanguageFile, True); CallIdleProc; end; end; {$ENDIF} procedure TSetupCompiler.ReadMessagesFromFiles(const AFiles: String; const ALangIndex: Integer); var S, Filename: String; AnsiLanguageFile: Boolean; begin S := AFiles; while True do begin Filename := ExtractStr(S, ','); if Filename = '' then Break; Filename := PathExpand(PrependSourceDirName(Filename)); AnsiLanguageFile := CompareText(PathExtractExt(Filename), '.islu') <> 0; AddStatus(Format(SCompilerStatusReadingInFile, [Filename])); EnumIniSection(EnumLangOptions, 'LangOptions', ALangIndex, False, True, Filename, AnsiLanguageFile, False); CallIdleProc; EnumIniSection(EnumMessages, 'Messages', ALangIndex, False, True, Filename, AnsiLanguageFile, False); CallIdleProc; EnumIniSection(EnumCustomMessages, 'CustomMessages', ALangIndex, False, True, Filename, AnsiLanguageFile, False); CallIdleProc; end; end; procedure TSetupCompiler.ReadDefaultMessages; var J: TSetupMessageID; begin { Read messages from Default.isl into DefaultLangData } EnumIniSection(EnumMessages, 'Messages', -2, False, True, 'compiler:Default.isl', True, False); CallIdleProc; { Check for missing messages in Default.isl } for J := Low(DefaultLangData.Messages) to High(DefaultLangData.Messages) do if not DefaultLangData.MessagesDefined[J] then AbortCompileFmt(SCompilerMessagesMissingDefaultMessage, [Copy(GetEnumName(TypeInfo(TSetupMessageID), Ord(J)), 4, Maxint)]); { ^ Copy(..., 4, Maxint) is to skip past "msg" } end; {$IFDEF UNICODE} procedure TSetupCompiler.ReadMessagesFromScriptPre; procedure CreateDefaultLanguageEntryPre; var NewPreLangData: TPreLangData; begin PreLangDataList.Expand; NewPreLangData := nil; try NewPreLangData := TPreLangData.Create; InitPreLangData(NewPreLangData); except NewPreLangData.Free; raise; end; PreLangDataList.Add(NewPreLangData); ReadMessagesFromFilesPre('compiler:Default.isl', PreLangDataList.Count-1); end; begin { If there were no [Languages] entries, take this opportunity to create a default language } if PreLangDataList.Count = 0 then begin CreateDefaultLanguageEntryPre; CallIdleProc; end; { Then read the [LangOptions] section in the script } AddStatus(SCompilerStatusReadingInScriptMsgs); EnumIniSection(EnumLangOptionspre, 'LangOptions', -1, False, True, '', False, True); CallIdleProc; end; {$ENDIF} procedure TSetupCompiler.ReadMessagesFromScript; procedure CreateDefaultLanguageEntry; var NewLanguageEntry: PSetupLanguageEntry; NewLangData: TLangData; begin LanguageEntries.Expand; LangDataList.Expand; NewLangData := nil; NewLanguageEntry := AllocMem(SizeOf(TSetupLanguageEntry)); try NewLangData := TLangData.Create; InitLanguageEntry(NewLanguageEntry^); except NewLangData.Free; SEFreeRec(NewLanguageEntry, SetupLanguageEntryStrings, SetupLanguageEntryAnsiStrings); raise; end; LanguageEntries.Add(NewLanguageEntry); LangDataList.Add(NewLangData); ReadMessagesFromFiles('compiler:Default.isl', LanguageEntries.Count-1); end; var I: Integer; LangData: TLangData; J: TSetupMessageID; begin { If there were no [Languages] entries, take this opportunity to create a default language } if LanguageEntries.Count = 0 then begin CreateDefaultLanguageEntry; CallIdleProc; end; { Then read the [LangOptions] & [Messages] & [CustomMessages] sections in the script } AddStatus(SCompilerStatusReadingInScriptMsgs); EnumIniSection(EnumLangOptions, 'LangOptions', -1, False, True, '', False, False); CallIdleProc; EnumIniSection(EnumMessages, 'Messages', -1, False, True, '', False, False); CallIdleProc; EnumIniSection(EnumCustomMessages, 'CustomMessages', -1, False, True, '', False, False); CallIdleProc; { Check for missing messages } for I := 0 to LanguageEntries.Count-1 do begin LangData := LangDataList[I]; for J := Low(LangData.Messages) to High(LangData.Messages) do if not LangData.MessagesDefined[J] then begin { Use the message from Default.isl } if J <> msgTranslatorNote then WarningsList.Add(Format(SCompilerMessagesMissingMessageWarning, [Copy(GetEnumName(TypeInfo(TSetupMessageID), Ord(J)), 4, Maxint), PSetupLanguageEntry(LanguageEntries[I]).Name])); { ^ Copy(..., 4, Maxint) is to skip past "msg" } LangData.Messages[J] := DefaultLangData.Messages[J]; end; end; CallIdleProc; end; procedure TSetupCompiler.PopulateLanguageEntryData; { Fills in each language entry's Data field, based on the messages in LangDataList } type PMessagesDataStructure = ^TMessagesDataStructure; TMessagesDataStructure = packed record ID: TMessagesHdrID; Header: TMessagesHeader; MsgData: array[0..0] of Byte; end; var L: Integer; LangData: TLangData; M: TMemoryStream; I: TSetupMessageID; Header: TMessagesHeader; begin for L := 0 to LanguageEntries.Count-1 do begin LangData := LangDataList[L]; M := TMemoryStream.Create; try M.WriteBuffer(MessagesHdrID, SizeOf(MessagesHdrID)); FillChar(Header, SizeOf(Header), 0); M.WriteBuffer(Header, SizeOf(Header)); { overwritten later } for I := Low(LangData.Messages) to High(LangData.Messages) do M.WriteBuffer(PChar(LangData.Messages[I])^, (Length(LangData.Messages[I]) + 1) * SizeOf(LangData.Messages[I][1])); Header.NumMessages := Ord(High(LangData.Messages)) - Ord(Low(LangData.Messages)) + 1; Header.TotalSize := M.Size; Header.NotTotalSize := not Header.TotalSize; Header.CRCMessages := GetCRC32(PMessagesDataStructure(M.Memory).MsgData, M.Size - (SizeOf(MessagesHdrID) + SizeOf(Header))); PMessagesDataStructure(M.Memory).Header := Header; SetString(PSetupLanguageEntry(LanguageEntries[L]).Data, PAnsiChar(M.Memory), M.Size); finally M.Free; end; end; end; procedure TSetupCompiler.EnumCode(const Line: PChar; const Ext: Integer); var CodeTextLineInfo: TLineInfo; begin CodeTextLineInfo := TLineInfo.Create; CodeTextLineInfo.Filename := ParseFilename; CodeTextLineInfo.FileLineNumber := LineNumber; CodeText.AddObject(Line, CodeTextLineInfo); end; procedure TSetupCompiler.ReadCode; begin { Read [Code] section } AddStatus(SCompilerStatusReadingCode); EnumIniSection(EnumCode, 'Code', 0, False, False, '', False, False); CallIdleProc; end; procedure TSetupCompiler.CodeCompilerOnLineToLineInfo(const Line: LongInt; var Filename: String; var FileLine: LongInt); var CodeTextLineInfo: TLineInfo; begin if (Line > 0) and (Line <= CodeText.Count) then begin CodeTextLineInfo := TLineInfo(CodeText.Objects[Line-1]); Filename := CodeTextLineInfo.Filename; FileLine := CodeTextLineInfo.FileLineNumber; end; end; procedure TSetupCompiler.CodeCompilerOnUsedLine(const Filename: String; const Line, Position: LongInt); var OldLineNumber: Integer; begin if FileName = '' then begin OldLineNumber := LineNumber; try LineNumber := Line; WriteDebugEntry(deCodeLine, Position); finally LineNumber := OldLineNumber; end; end; end; procedure TSetupCompiler.CodeCompilerOnUsedVariable(const Filename: String; const Line, Col, Param1, Param2, Param3: LongInt; const Param4: AnsiString); var Rec: TVariableDebugEntry; begin if (FileName = '') and (Length(Param4)+1 <= SizeOf(Rec.Param4)) then begin Rec.LineNumber := Line; Rec.Col := Col; Rec.Param1 := Param1; Rec.Param2 := Param2; Rec.Param3 := Param3; FillChar(Rec.Param4, SizeOf(Rec.Param4), 0); StrPCopy(Rec.Param4, Param4); CodeDebugInfo.WriteBuffer(Rec, SizeOf(Rec)); Inc(VariableDebugEntryCount); end; end; procedure TSetupCompiler.CodeCompilerOnError(const Msg: String; const ErrorFilename: String; const ErrorLine: LongInt); begin LineFilename := ErrorFilename; LineNumber := ErrorLine; AbortCompile(Msg); end; procedure TSetupCompiler.CodeCompilerOnWarning(const Msg: String); begin WarningsList.Add(Msg); end; procedure TSetupCompiler.CompileCode; var CodeStr: String; CompiledCodeDebugInfo: AnsiString; begin { Compile CodeText } CodeCompiler.OnLineToLineInfo := CodeCompilerOnLineToLineInfo; CodeCompiler.OnUsedLine := CodeCompilerOnUsedLine; CodeCompiler.OnUsedVariable := CodeCompilerOnUsedVariable; CodeCompiler.OnError := CodeCompilerOnError; CodeCompiler.OnWarning := CodeCompilerOnWarning; if (CodeText.Count > 0) or (CodeCompiler.ExportCount > 0) then begin if CodeText.Count > 0 then AddStatus(SCompilerStatusCompilingCode); //don't forget highlighter! CodeCompiler.AddExport('InitializeSetup', 'Boolean', False, '', 0); CodeCompiler.AddExport('DeinitializeSetup', '0', False, '', 0); CodeCompiler.AddExport('CurStepChanged', '0 @TSetupStep', False, '', 0); CodeCompiler.AddExport('NextButtonClick', 'Boolean @LongInt', False, '', 0); CodeCompiler.AddExport('BackButtonClick', 'Boolean @LongInt', False, '', 0); CodeCompiler.AddExport('CancelButtonClick', '0 @LongInt !Boolean !Boolean', False, '', 0); CodeCompiler.AddExport('ShouldSkipPage', 'Boolean @LongInt', False, '', 0); CodeCompiler.AddExport('CurPageChanged', '0 @LongInt', False, '', 0); CodeCompiler.AddExport('CheckPassword', 'Boolean @String', False, '', 0); CodeCompiler.AddExport('NeedRestart', 'Boolean', False, '', 0); CodeCompiler.AddExport('UpdateReadyMemo', 'String @String @String @String @String @String @String @String @String', False, '', 0); CodeCompiler.AddExport('RegisterPreviousData', '0 @LongInt', False, '', 0); CodeCompiler.AddExport('CheckSerial', 'Boolean @String', False, '', 0); CodeCompiler.AddExport('InitializeWizard', '0', False, '', 0); CodeCompiler.AddExport('GetCustomSetupExitCode', 'LongInt', False, '', 0); CodeCompiler.AddExport('PrepareToInstall', 'String !Boolean', False, '', 0); CodeCompiler.AddExport('RegisterExtraCloseApplicationsResources', '0', False, '', 0); CodeCompiler.AddExport('CurInstallProgressChanged', '0 @LongInt @LongInt', False, '', 0); CodeCompiler.AddExport('InitializeUninstall', 'Boolean', False, '', 0); CodeCompiler.AddExport('DeinitializeUninstall', '0', False, '', 0); CodeCompiler.AddExport('CurUninstallStepChanged', '0 @TUninstallStep', False, '', 0); CodeCompiler.AddExport('UninstallNeedRestart', 'Boolean', False, '', 0); CodeCompiler.AddExport('InitializeUninstallProgressForm', '0', False, '', 0); CodeStr := CodeText.Text; { Remove trailing CR-LF so that ROPS will never report an error on line CodeText.Count, one past the last actual line } if Length(CodeStr) >= Length(#13#10) then SetLength(CodeStr, Length(CodeStr) - Length(#13#10)); CodeCompiler.Compile(CodeStr, CompiledCodeText, CompiledCodeDebugInfo); if CodeCompiler.FunctionFound('SkipCurPage') then AbortCompileFmt(SCompilerCodeUnsupportedEventFunction, ['SkipCurPage', 'ShouldSkipPage']); WriteCompiledCodeText(CompiledCodeText); WriteCompiledCodeDebugInfo(CompiledCodeDebugInfo); end else begin CompiledCodeText := ''; { Check if there were references to [Code] functions despite there being no [Code] section } CodeCompiler.CheckExports(); end; end; procedure TSetupCompiler.AddSignTool(const Name, Command: String); var SignTool: TSignTool; begin SignToolList.Expand; SignTool := TSignTool.Create(); SignTool.Name := Name; SignTool.Command := Command; SignToolList.Add(SignTool); end; procedure TSetupCompiler.Sign(const ACommand, AParams, AExeFilename: String); function FmtCommand(S: PChar; const AParams, AExeFileName: String): String; var P: PChar; Z: String; begin Result := ''; if S = nil then Exit; while True do begin P := StrScan(S, '$'); if P = nil then begin Result := Result + S; Break; end; if P <> S then begin SetString(Z, S, P - S); Result := Result + Z; S := P; end; Inc(P); if (P^ = 'p') then begin Result := Result + AParams; Inc(S, 2); end else if (P^ = 'f') then begin Result := Result + '"' + AExeFileName + '"'; Inc(S, 2); end else if (P^ = 'q') then begin Result := Result + '"'; Inc(S, 2); end else begin Result := Result + '$'; Inc(S); if P^ = '$' then Inc(S); end; end; end; var Params, Command: String; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; LastError, ExitCode: DWORD; begin Params := FmtCommand(PChar(AParams), '', AExeFileName); Command := FmtCommand(PChar(ACommand), Params, AExeFileName); AddStatus(Format(SCompilerStatusSigning, [Command])); FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_SHOW; if not CreateProcess(nil, PChar(Command), nil, nil, False, CREATE_DEFAULT_ERROR_MODE, nil, PChar(CompilerDir), StartupInfo, ProcessInfo) then begin LastError := GetLastError; AbortCompileFmt(SCompilerSignToolCreateProcessFailed, [LastError, Win32ErrorString(LastError)]); end; CloseHandle(ProcessInfo.hThread); try while True do begin case WaitForSingleObject(ProcessInfo.hProcess, 50) of WAIT_OBJECT_0: Break; WAIT_TIMEOUT: CallIdleProc; else AbortCompile('Sign: WaitForSingleObject failed'); end; end; if not GetExitCodeProcess(ProcessInfo.hProcess, ExitCode) then AbortCompile('Sign: GetExitCodeProcess failed'); if ExitCode <> 0 then AbortCompileFmt(SCompilerSignToolNonZeroExitCode, [ExitCode]); finally CloseHandle(ProcessInfo.hProcess); end; end; procedure TSetupCompiler.Compile; procedure InitDebugInfo; var Header: TDebugInfoHeader; begin DebugEntryCount := 0; VariableDebugEntryCount := 0; DebugInfo.Clear; CodeDebugInfo.Clear; Header.ID := DebugInfoHeaderID; Header.Version := DebugInfoHeaderVersion; Header.DebugEntryCount := 0; Header.CompiledCodeTextLength := 0; Header.CompiledCodeDebugInfoLength := 0; DebugInfo.WriteBuffer(Header, SizeOf(Header)); end; procedure FinalizeDebugInfo; var Header: TDebugInfoHeader; begin DebugInfo.CopyFrom(CodeDebugInfo, 0); { Update the header } DebugInfo.Seek(0, soFromBeginning); DebugInfo.ReadBuffer(Header, SizeOf(Header)); Header.DebugEntryCount := DebugEntryCount; Header.VariableDebugEntryCount := VariableDebugEntryCount; Header.CompiledCodeTextLength := CompiledCodeTextLength; Header.CompiledCodeDebugInfoLength := CompiledCodeDebugInfoLength; DebugInfo.Seek(0, soFromBeginning); DebugInfo.WriteBuffer(Header, SizeOf(Header)); end; procedure EmptyOutputDir(const Log: Boolean); procedure DelFile(const Filename: String); begin if DeleteFile(OutputDir + Filename) and Log then AddStatus(Format(SCompilerStatusDeletingPrevious, [Filename])); end; var H: THandle; FindData: TWin32FindData; N: String; I: Integer; HasNumbers: Boolean; begin { Delete SETUP.* and SETUP-*.BIN if they existed in the output directory } DelFile(OutputBaseFilename + '.exe'); H := FindFirstFile(PChar(OutputDir + OutputBaseFilename + '-*.bin'), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat if FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0 then begin N := FindData.cFileName; if PathStartsWith(N, OutputBaseFilename) then begin I := Length(OutputBaseFilename) + 1; if (I <= Length(N)) and (N[I] = '-') then begin Inc(I); HasNumbers := False; while (I <= Length(N)) and CharInSet(N[I], ['0'..'9']) do begin HasNumbers := True; Inc(I); end; if HasNumbers then begin if (I <= Length(N)) and CharInSet(UpCase(N[I]), ['A'..'Z']) then Inc(I); if CompareText(Copy(N, I, Maxint), '.bin') = 0 then DelFile(N); end; end; end; end; until not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end; end; procedure FreeListItems(const List: TList; const NumStrings, NumAnsiStrings: Integer); var I: Integer; begin for I := List.Count-1 downto 0 do begin SEFreeRec(List[I], NumStrings, NumAnsiStrings); List.Delete(I); end; end; {$IFDEF UNICODE} procedure FreePreLangData; var I: Integer; begin for I := PreLangDataList.Count-1 downto 0 do begin TPreLangData(PreLangDataList[I]).Free; PreLangDataList.Delete(I); end; end; {$ENDIF} procedure FreeLangData; var I: Integer; begin for I := LangDataList.Count-1 downto 0 do begin TLangData(LangDataList[I]).Free; LangDataList.Delete(I); end; end; procedure FreeScriptFiles; var I: Integer; SL: TObject; begin for I := ScriptFiles.Count-1 downto 0 do begin SL := ScriptFiles.Objects[I]; ScriptFiles.Delete(I); SL.Free; end; end; procedure FreeLineInfoList(L: TStringList); var I: Integer; LineInfo: TLineInfo; begin for I := L.Count-1 downto 0 do begin LineInfo := TLineInfo(L.Objects[I]); L.Delete(I); LineInfo.Free; end; end; type PCopyBuffer = ^TCopyBuffer; TCopyBuffer = array[0..32767] of Char; var SetupFile: TFile; ExeFile: TFile; LicenseText, InfoBeforeText, InfoAfterText: AnsiString; WizardImage: TMemoryStream; WizardSmallImage: TMemoryStream; DecompressorDLL, DecryptionDLL: TMemoryStream; SetupLdrOffsetTable: TSetupLdrOffsetTable; SizeOfExe, SizeOfHeaders: Longint; function WriteSetup0(const F: TFile): Longint; procedure WriteStream(Stream: TMemoryStream; W: TCompressedBlockWriter); var Size: Longint; begin Size := Stream.Size; W.Write(Size, SizeOf(Size)); W.Write(Stream.Memory^, Size); end; var Pos: Cardinal; J: Integer; W: TCompressedBlockWriter; begin Pos := F.Position.Lo; F.WriteBuffer(SetupID, SizeOf(SetupID)); {$IFNDEF UNICODE} SetupHeader.LeadBytes := CompilerLeadBytes; {$ENDIF} SetupHeader.NumLanguageEntries := LanguageEntries.Count; SetupHeader.NumCustomMessageEntries := CustomMessageEntries.Count; SetupHeader.NumPermissionEntries := PermissionEntries.Count; SetupHeader.NumTypeEntries := TypeEntries.Count; SetupHeader.NumComponentEntries := ComponentEntries.Count; SetupHeader.NumTaskEntries := TaskEntries.Count; SetupHeader.NumDirEntries := DirEntries.Count; SetupHeader.NumFileEntries := FileEntries.Count; SetupHeader.NumFileLocationEntries := FileLocationEntries.Count; SetupHeader.NumIconEntries := IconEntries.Count; SetupHeader.NumIniEntries := IniEntries.Count; SetupHeader.NumRegistryEntries := RegistryEntries.Count; SetupHeader.NumInstallDeleteEntries := InstallDeleteEntries.Count; SetupHeader.NumUninstallDeleteEntries := UninstallDeleteEntries.Count; SetupHeader.NumRunEntries := RunEntries.Count; SetupHeader.NumUninstallRunEntries := UninstallRunEntries.Count; SetupHeader.LicenseText := LicenseText; SetupHeader.InfoBeforeText := InfoBeforeText; SetupHeader.InfoAfterText := InfoAfterText; SetupHeader.CompiledCodeText := CompiledCodeText; W := TCompressedBlockWriter.Create(F, TLZMACompressor, InternalCompressLevel, InternalCompressProps); try SECompressedBlockWrite(W, SetupHeader, SizeOf(SetupHeader), SetupHeaderStrings, SetupHeaderAnsiStrings); for J := 0 to LanguageEntries.Count-1 do SECompressedBlockWrite(W, LanguageEntries[J]^, SizeOf(TSetupLanguageEntry), SetupLanguageEntryStrings, SetupLanguageEntryAnsiStrings); for J := 0 to CustomMessageEntries.Count-1 do SECompressedBlockWrite(W, CustomMessageEntries[J]^, SizeOf(TSetupCustomMessageEntry), SetupCustomMessageEntryStrings, SetupCustomMessageEntryAnsiStrings); for J := 0 to PermissionEntries.Count-1 do SECompressedBlockWrite(W, PermissionEntries[J]^, SizeOf(TSetupPermissionEntry), SetupPermissionEntryStrings, SetupPermissionEntryAnsiStrings); for J := 0 to TypeEntries.Count-1 do SECompressedBlockWrite(W, TypeEntries[J]^, SizeOf(TSetupTypeEntry), SetupTypeEntryStrings, SetupTypeEntryAnsiStrings); for J := 0 to ComponentEntries.Count-1 do SECompressedBlockWrite(W, ComponentEntries[J]^, SizeOf(TSetupComponentEntry), SetupComponentEntryStrings, SetupComponentEntryAnsiStrings); for J := 0 to TaskEntries.Count-1 do SECompressedBlockWrite(W, TaskEntries[J]^, SizeOf(TSetupTaskEntry), SetupTaskEntryStrings, SetupTaskEntryAnsiStrings); for J := 0 to DirEntries.Count-1 do SECompressedBlockWrite(W, DirEntries[J]^, SizeOf(TSetupDirEntry), SetupDirEntryStrings, SetupDirEntryAnsiStrings); for J := 0 to FileEntries.Count-1 do SECompressedBlockWrite(W, FileEntries[J]^, SizeOf(TSetupFileEntry), SetupFileEntryStrings, SetupFileEntryAnsiStrings); for J := 0 to IconEntries.Count-1 do SECompressedBlockWrite(W, IconEntries[J]^, SizeOf(TSetupIconEntry), SetupIconEntryStrings, SetupIconEntryAnsiStrings); for J := 0 to IniEntries.Count-1 do SECompressedBlockWrite(W, IniEntries[J]^, SizeOf(TSetupIniEntry), SetupIniEntryStrings, SetupIniEntryAnsiStrings); for J := 0 to RegistryEntries.Count-1 do SECompressedBlockWrite(W, RegistryEntries[J]^, SizeOf(TSetupRegistryEntry), SetupRegistryEntryStrings, SetupRegistryEntryAnsiStrings); for J := 0 to InstallDeleteEntries.Count-1 do SECompressedBlockWrite(W, InstallDeleteEntries[J]^, SizeOf(TSetupDeleteEntry), SetupDeleteEntryStrings, SetupDeleteEntryAnsiStrings); for J := 0 to UninstallDeleteEntries.Count-1 do SECompressedBlockWrite(W, UninstallDeleteEntries[J]^, SizeOf(TSetupDeleteEntry), SetupDeleteEntryStrings, SetupDeleteEntryAnsiStrings); for J := 0 to RunEntries.Count-1 do SECompressedBlockWrite(W, RunEntries[J]^, SizeOf(TSetupRunEntry), SetupRunEntryStrings, SetupRunEntryAnsiStrings); for J := 0 to UninstallRunEntries.Count-1 do SECompressedBlockWrite(W, UninstallRunEntries[J]^, SizeOf(TSetupRunEntry), SetupRunEntryStrings, SetupRunEntryAnsiStrings); WriteStream(WizardImage, W); WriteStream(WizardSmallImage, W); if SetupHeader.CompressMethod in [cmZip, cmBzip] then WriteStream(DecompressorDLL, W); if shEncryptionUsed in SetupHeader.Options then WriteStream(DecryptionDLL, W); W.Finish; finally W.Free; end; if not DiskSpanning then W := TCompressedBlockWriter.Create(F, TLZMACompressor, InternalCompressLevel, InternalCompressProps) else W := TCompressedBlockWriter.Create(F, nil, 0, nil); { ^ When disk spanning is enabled, the Setup Compiler requires that FileLocationEntries be a fixed size, so don't compress them } try for J := 0 to FileLocationEntries.Count-1 do W.Write(FileLocationEntries[J]^, SizeOf(TSetupFileLocationEntry)); W.Finish; finally W.Free; end; Result := F.Position.Lo - Pos; end; function CreateSetup0File: Longint; var F: TFile; begin F := TFile.Create(OutputDir + OutputBaseFilename + '-0.bin', fdCreateAlways, faWrite, fsNone); try Result := WriteSetup0(F); finally F.Free; end; end; function RoundToNearestClusterSize(const L: Longint): Longint; begin Result := (L div DiskClusterSize) * DiskClusterSize; if L mod DiskClusterSize <> 0 then Inc(Result, DiskClusterSize); end; procedure CompressFiles(const FirstDestFile: String; const BytesToReserveOnFirstDisk: Longint); var CurrentTime: TSystemTime; procedure ApplyTouch(var FT: TFileTime); var ST: TSystemTime; begin if (TouchDateOption = tdNone) and (TouchTimeOption = ttNone) then Exit; { nothing to do } if not FileTimeToSystemTime(FT, ST) then AbortCompile('ApplyTouch: FileTimeToSystemTime call failed'); case TouchDateOption of tdCurrent: begin ST.wYear := CurrentTime.wYear; ST.wMonth := CurrentTime.wMonth; ST.wDay := CurrentTime.wDay; end; tdExplicit: begin ST.wYear := TouchDateYear; ST.wMonth := TouchDateMonth; ST.wDay := TouchDateDay; end; end; case TouchTimeOption of ttCurrent: begin ST.wHour := CurrentTime.wHour; ST.wMinute := CurrentTime.wMinute; ST.wSecond := CurrentTime.wSecond; ST.wMilliseconds := CurrentTime.wMilliseconds; end; ttExplicit: begin ST.wHour := TouchTimeHour; ST.wMinute := TouchTimeMinute; ST.wSecond := TouchTimeSecond; ST.wMilliseconds := 0; end; end; if not SystemTimeToFileTime(ST, FT) then AbortCompile('ApplyTouch: SystemTimeToFileTime call failed'); end; function GetCompressorClass(const UseCompression: Boolean): TCustomCompressorClass; begin if not UseCompression then Result := TStoredCompressor else begin case SetupHeader.CompressMethod of cmStored: begin Result := TStoredCompressor; end; cmZip: begin InitZipDLL; Result := TZCompressor; end; cmBzip: begin InitBzipDLL; Result := TBZCompressor; end; cmLZMA: begin Result := TLZMACompressor; end; cmLZMA2: begin Result := TLZMA2Compressor; end; else AbortCompile('GetCompressorClass: Unknown CompressMethod'); Result := nil; end; end; end; procedure FinalizeChunk(const CH: TCompressionHandler; const LastFileLocationEntry: Integer); var I: Integer; FL: PSetupFileLocationEntry; begin if CH.ChunkStarted then begin CH.EndChunk; { Set LastSlice and ChunkCompressedSize on all file location entries that are part of the chunk } for I := 0 to LastFileLocationEntry do begin FL := FileLocationEntries[I]; if (FL.StartOffset = CH.ChunkStartOffset) and (FL.FirstSlice = CH.ChunkFirstSlice) then begin FL.LastSlice := CH.CurSlice; FL.ChunkCompressedSize := CH.ChunkBytesWritten; end; end; end; end; var CH: TCompressionHandler; ChunkCompressed: Boolean; I: Integer; FL: PSetupFileLocationEntry; FT: TFileTime; SourceFile: TFile; begin if (SetupHeader.CompressMethod in [cmLZMA, cmLZMA2]) and (CompressProps.WorkerProcessFilename <> '') then AddStatus(Format(' Using separate process for LZMA compression (%s)', [PathExtractName(CompressProps.WorkerProcessFilename)])); if TimeStampsInUTC then GetSystemTime(CurrentTime) else GetLocalTime(CurrentTime); ChunkCompressed := False; { avoid warning } CH := TCompressionHandler.Create(Self, FirstDestFile); try { If encryption is used, load the encryption DLL } if shEncryptionUsed in SetupHeader.Options then begin AddStatus(SCompilerStatusFilesInitEncryption); InitCryptDLL; end; if DiskSpanning then begin if not CH.ReserveBytesOnSlice(BytesToReserveOnFirstDisk) then AbortCompile(SCompilerNotEnoughSpaceOnFirstDisk); end; CompressionStartTick := GetTickCount; CompressionInProgress := True; for I := 0 to FileLocationEntries.Count-1 do begin FL := FileLocationEntries[I]; if foVersionInfoValid in FL.Flags then AddStatus(Format(SCompilerStatusFilesCompressingVersion, [FileLocationEntryFilenames[I], LongRec(FL.FileVersionMS).Hi, LongRec(FL.FileVersionMS).Lo, LongRec(FL.FileVersionLS).Hi, LongRec(FL.FileVersionLS).Lo])) else AddStatus(Format(SCompilerStatusFilesCompressing, [FileLocationEntryFilenames[I]])); CallIdleProc; SourceFile := TFile.Create(FileLocationEntryFilenames[I], fdOpenExisting, faRead, fsRead); try if CH.ChunkStarted then begin { End the current chunk if one of the following conditions is true: - we're not using solid compression - the "solidbreak" flag was specified on this file - the compression or encryption status of this file is different from the previous file(s) in the chunk } if not UseSolidCompression or (foSolidBreak in FL.Flags) or (ChunkCompressed <> (foChunkCompressed in FL.Flags)) or (CH.ChunkEncrypted <> (foChunkEncrypted in FL.Flags)) then FinalizeChunk(CH, I-1); end; { Start a new chunk if needed } if not CH.ChunkStarted then begin ChunkCompressed := (foChunkCompressed in FL.Flags); CH.NewChunk(GetCompressorClass(ChunkCompressed), CompressLevel, CompressProps, foChunkEncrypted in FL.Flags, CryptKey); end; FL.FirstSlice := CH.ChunkFirstSlice; FL.StartOffset := CH.ChunkStartOffset; FL.ChunkSuboffset := CH.ChunkBytesRead; FL.OriginalSize := SourceFile.Size; if not GetFileTime(SourceFile.Handle, nil, nil, @FT) then AbortCompile('CompressFiles: GetFileTime failed'); if TimeStampsInUTC then begin FL.TimeStamp := FT; Include(FL.Flags, foTimeStampInUTC); end else FileTimeToLocalFileTime(FT, FL.TimeStamp); if foTouch in FL.Flags then ApplyTouch(FL.TimeStamp); if TimeStampRounding > 0 then Dec64(Integer64(FL.TimeStamp), Mod64(Integer64(FL.TimeStamp), TimeStampRounding * 10000000)); if ChunkCompressed and IsX86OrX64Executable(SourceFile) then Include(FL.Flags, foCallInstructionOptimized); CH.CompressFile(SourceFile, FL.OriginalSize, foCallInstructionOptimized in FL.Flags, FL.SHA1Sum); finally SourceFile.Free; end; end; { Finalize the last chunk } FinalizeChunk(CH, FileLocationEntries.Count-1); CH.Finish; finally CompressionInProgress := False; CH.Free; end; { Ensure progress bar is full, in case a file shrunk in size } BytesCompressedSoFar := TotalBytesToCompress; CallIdleProc; end; procedure CopyFileOrAbort(const SourceFile, DestFile: String); var ErrorCode: DWORD; begin if not CopyFile(PChar(SourceFile), PChar(DestFile), False) then begin ErrorCode := GetLastError; AbortCompileFmt(SCompilerCopyError3, [SourceFile, DestFile, ErrorCode, Win32ErrorString(ErrorCode)]); end; end; function InternalSignSetupE32(const Filename: String; var UnsignedFile: TMemoryFile; const UnsignedFileSize: Cardinal; const MismatchMessage: String): Boolean; var SignedFile, TestFile, OldFile: TMemoryFile; SignedFileSize: Cardinal; SignatureAddress, SignatureSize: Cardinal; HdrChecksum: DWORD; begin SignedFile := TMemoryFile.Create(Filename); try SignedFileSize := SignedFile.CappedSize; { Check the file for a signature } if not ReadSignatureAndChecksumFields(SignedFile, DWORD(SignatureAddress), DWORD(SignatureSize), HdrChecksum) then AbortCompile('ReadSignatureAndChecksumFields failed'); if SignatureAddress = 0 then begin { No signature found. Return False to inform the caller that the file needs to be signed, but first make sure it isn't somehow corrupted. } if (SignedFileSize = UnsignedFileSize) and CompareMem(UnsignedFile.Memory, SignedFile.Memory, UnsignedFileSize) then begin Result := False; Exit; end; AbortCompileFmt(MismatchMessage, [Filename]); end; if (SignedFileSize <= UnsignedFileSize) or (SignatureAddress <> UnsignedFileSize) or (SignatureSize <> SignedFileSize - UnsignedFileSize) or (SignatureSize >= Cardinal($100000)) then AbortCompile(SCompilerSignatureInvalid); { Sanity check: Remove the signature (in memory) and verify that the signed file is identical byte-for-byte to the original } TestFile := TMemoryFile.CreateFromMemory(SignedFile.Memory^, SignedFileSize); try { Carry checksum over from UnsignedFile to TestFile. We used to just zero it in TestFile, but that didn't work if the user modified Setup.e32 with a res-editing tool that sets a non-zero checksum. } if not ReadSignatureAndChecksumFields(UnsignedFile, DWORD(SignatureAddress), DWORD(SignatureSize), HdrChecksum) then AbortCompile('ReadSignatureAndChecksumFields failed (2)'); if not UpdateSignatureAndChecksumFields(TestFile, 0, 0, HdrChecksum) then AbortCompile('UpdateSignatureAndChecksumFields failed'); if not CompareMem(UnsignedFile.Memory, TestFile.Memory, UnsignedFileSize) then AbortCompileFmt(MismatchMessage, [Filename]); finally TestFile.Free; end; except SignedFile.Free; raise; end; { Replace UnsignedFile with the signed file } OldFile := UnsignedFile; UnsignedFile := SignedFile; OldFile.Free; Result := True; end; procedure SignSetupE32(var UnsignedFile: TMemoryFile); var UnsignedFileSize: Cardinal; ModeID: Longint; Filename, TempFilename: String; F: TFile; LastError: DWORD; SignToolIndex: Integer; begin UnsignedFileSize := UnsignedFile.CappedSize; UnsignedFile.Seek(SetupExeModeOffset); ModeID := SetupExeModeUninstaller; UnsignedFile.WriteBuffer(ModeID, SizeOf(ModeID)); SignToolIndex := FindSignToolIndexByName(SignTool); if SignToolIndex <> -1 then begin Filename := SignedUninstallerDir + 'uninst.e32.tmp'; F := TFile.Create(Filename, fdCreateAlways, faWrite, fsNone); try F.WriteBuffer(UnsignedFile.Memory^, UnsignedFileSize); finally F.Free; end; try Sign(TSignTool(SignToolList[SignToolIndex]).Command, SignToolParams, Filename); if not InternalSignSetupE32(Filename, UnsignedFile, UnsignedFileSize, SCompilerSignedFileContentsMismatch) then AbortCompile(SCompilerSignToolSucceededButNoSignature); finally DeleteFile(Filename); end; end else begin Filename := SignedUninstallerDir + Format('uninst-%s-%s.e32', [SetupVersion, Copy(SHA1DigestToString(SHA1Buf(UnsignedFile.Memory^, UnsignedFileSize)), 1, 10)]); if not NewFileExists(Filename) then begin { Create new signed uninstaller file } AddStatus(Format(SCompilerStatusSignedUninstallerNew, [Filename])); TempFilename := Filename + '.tmp'; F := TFile.Create(TempFilename, fdCreateAlways, faWrite, fsNone); try F.WriteBuffer(UnsignedFile.Memory^, UnsignedFileSize); finally F.Free; end; if not MoveFile(PChar(TempFilename), PChar(Filename)) then begin LastError := GetLastError; DeleteFile(TempFilename); TFile.RaiseError(LastError); end; end else begin { Use existing signed uninstaller file } AddStatus(Format(SCompilerStatusSignedUninstallerExisting, [Filename])); end; if not InternalSignSetupE32(Filename, UnsignedFile, UnsignedFileSize, SCompilerSignedFileContentsMismatchRetry) then AbortCompileFmt(SCompilerSignatureNeeded, [Filename]); end; end; procedure PrepareSetupE32(var M: TMemoryFile); var TempFilename, E32Filename, ConvertFilename: String; begin AddStatus(SCompilerStatusPreparingSetupExe); TempFilename := ''; try E32Filename := CompilerDir + 'SETUP.E32'; if SetupIconFilename <> '' then begin { make a copy and update icons } ConvertFilename := OutputDir + OutputBaseFilename + '.e32.tmp'; CopyFileOrAbort(E32Filename, ConvertFilename); SetFileAttributes(PChar(ConvertFilename), FILE_ATTRIBUTE_ARCHIVE); TempFilename := ConvertFilename; AddStatus(Format(SCompilerStatusUpdatingIcons, ['SETUP.E32'])); LineNumber := SetupDirectiveLines[ssSetupIconFile]; UpdateIcons(ConvertFileName, PrependSourceDirName(SetupIconFilename)); LineNumber := 0; end else ConvertFilename := E32Filename; M := TMemoryFile.Create(ConvertFilename); UpdateSetupPEHeaderFields(M, TerminalServicesAware); if shSignedUninstaller in SetupHeader.Options then SignSetupE32(M); finally if TempFilename <> '' then DeleteFile(TempFilename); end; end; procedure CompressSetupE32(const M: TMemoryFile; const DestF: TFile; var UncompressedSize: LongWord; var CRC: Longint); { Note: This modifies the contents of M. } var Writer: TCompressedBlockWriter; begin AddStatus(SCompilerStatusCompressingSetupExe); UncompressedSize := M.CappedSize; CRC := GetCRC32(M.Memory^, UncompressedSize); TransformCallInstructions(M.Memory^, UncompressedSize, True, 0); Writer := TCompressedBlockWriter.Create(DestF, TLZMACompressor, InternalCompressLevel, InternalCompressProps); try Writer.Write(M.Memory^, UncompressedSize); Writer.Finish; finally Writer.Free; end; end; procedure AddDefaultSetupType(Name: String; Options: TSetupTypeOptions; Typ: TSetupTypeType); var NewTypeEntry: PSetupTypeEntry; begin NewTypeEntry := AllocMem(SizeOf(TSetupTypeEntry)); NewTypeEntry.Name := Name; NewTypeEntry.Description := ''; //set at runtime NewTypeEntry.Check := ''; NewTypeEntry.MinVersion := SetupHeader.MinVersion; NewTypeEntry.OnlyBelowVersion := SetupHeader.OnlyBelowVersion; NewTypeEntry.Options := Options; NewTypeEntry.Typ := Typ; TypeEntries.Add(NewTypeEntry); end; procedure MkDirs(Dir: string); begin Dir := RemoveBackslashUnlessRoot(Dir); if (PathExtractPath(Dir) = Dir) or DirExists(Dir) then Exit; MkDirs(PathExtractPath(Dir)); MkDir(Dir); end; procedure CreateManifestFile; function FileTimeToString(const FileTime: TFileTime; const UTC: Boolean): String; var ST: TSystemTime; begin if FileTimeToSystemTime(FileTime, ST) then Result := Format('%.4u-%.2u-%.2u %.2u:%.2u:%.2u.%.3u', [ST.wYear, ST.wMonth, ST.wDay, ST.wHour, ST.wMinute, ST.wSecond, ST.wMilliseconds]) else Result := '(invalid)'; if UTC then Result := Result + ' UTC'; end; function SliceToString(const ASlice: Integer): String; begin Result := IntToStr(ASlice div SlicesPerDisk + 1); if SlicesPerDisk <> 1 then Result := Result + Chr(Ord('a') + ASlice mod SlicesPerDisk); end; const EncryptedStrings: array [Boolean] of String = ('no', 'yes'); var F: TTextFileWriter; FL: PSetupFileLocationEntry; S: String; I: Integer; begin F := TTextFileWriter.Create(PrependDirName(OutputManifestFile, OutputDir), fdCreateAlways, faWrite, fsRead); try S := 'Index' + #9 + 'SourceFilename' + #9 + 'TimeStamp' + #9 + 'Version' + #9 + 'SHA1Sum' + #9 + 'OriginalSize' + #9 + 'FirstSlice' + #9 + 'LastSlice' + #9 + 'StartOffset' + #9 + 'ChunkSuboffset' + #9 + 'ChunkCompressedSize' + #9 + 'Encrypted'; F.WriteLine(S); for I := 0 to FileLocationEntries.Count-1 do begin FL := FileLocationEntries[I]; S := IntToStr(I) + #9 + FileLocationEntryFilenames[I] + #9 + FileTimeToString(FL.TimeStamp, foTimeStampInUTC in FL.Flags) + #9; if foVersionInfoValid in FL.Flags then S := S + Format('%u.%u.%u.%u', [FL.FileVersionMS shr 16, FL.FileVersionMS and $FFFF, FL.FileVersionLS shr 16, FL.FileVersionLS and $FFFF]); S := S + #9 + SHA1DigestToString(FL.SHA1Sum) + #9 + Integer64ToStr(FL.OriginalSize) + #9 + SliceToString(FL.FirstSlice) + #9 + SliceToString(FL.LastSlice) + #9 + IntToStr(FL.StartOffset) + #9 + Integer64ToStr(FL.ChunkSuboffset) + #9 + Integer64ToStr(FL.ChunkCompressedSize) + #9 + EncryptedStrings[foChunkEncrypted in FL.Flags]; F.WriteLine(S); end; finally F.Free; end; end; procedure CallPreprocessorCleanupProc; var ResultCode: Integer; begin if Assigned(PreprocCleanupProc) then begin ResultCode := PreprocCleanupProc(PreprocCleanupProcData); if ResultCode <> 0 then AddStatusFmt(SCompilerStatusWarning + 'Preprocessor cleanup function failed with code %d.', [ResultCode]); end; end; var SetupE32: TMemoryFile; I, SignToolIndex: Integer; AppNameHasConsts, AppVersionHasConsts, AppPublisherHasConsts, AppCopyrightHasConsts, AppIdHasConsts, Uninstallable: Boolean; begin { Sanity check: A single TSetupCompiler instance cannot be used to do multiple compiles. A separate instance must be used for each compile, otherwise some settings (e.g. DefaultLangData, VersionInfo*) would be carried over from one compile to another. } if CompileWasAlreadyCalled then AbortCompile('Compile was already called'); CompileWasAlreadyCalled := True; CompilerDir := AddBackslash(PathExpand(CompilerDir)); InitPreprocessor; InitLZMADLL; WizardImage := nil; WizardSmallImage := nil; SetupE32 := nil; DecompressorDLL := nil; DecryptionDLL := nil; try Finalize(SetupHeader); FillChar(SetupHeader, SizeOf(SetupHeader), 0); InitDebugInfo; { Initialize defaults } OriginalSourceDir := AddBackslash(PathExpand(SourceDir)); if not FixedOutputDir then OutputDir := 'Output'; if not FixedOutputBaseFilename then OutputBaseFilename := 'setup'; InternalCompressLevel := clLZMANormal; InternalCompressProps := TLZMACompressorProps.Create; CompressMethod := cmLZMA2; CompressLevel := clLZMAMax; CompressProps := TLZMACompressorProps.Create; UseSetupLdr := True; TerminalServicesAware := True; DiskSliceSize := MaxDiskSliceSize; DiskClusterSize := 512; SlicesPerDisk := 1; ReserveBytes := 0; TimeStampRounding := 2; SetupHeader.MinVersion.WinVersion := 0; SetupHeader.MinVersion.NTVersion := $05000000; SetupHeader.Options := [shDisableStartupPrompt, shCreateAppDir, shWindowStartMaximized, shWindowShowCaption, shWindowResizable, shUsePreviousAppDir, shUsePreviousGroup, shUsePreviousSetupType, shAlwaysShowComponentsList, shFlatComponentsList, shShowComponentSizes, shUsePreviousTasks, shUpdateUninstallLogAppName, shAllowUNCPath, shUsePreviousUserInfo, shRestartIfNeededByRun, shAllowCancelDuringInstall, shWizardImageStretch, shAppendDefaultDirName, shAppendDefaultGroupName, shUsePreviousLanguage, shCloseApplications, shRestartApplications, shAllowNetworkDrive]; SetupHeader.PrivilegesRequired := prAdmin; SetupHeader.UninstallFilesDir := '{app}'; SetupHeader.DefaultUserInfoName := '{sysuserinfoname}'; SetupHeader.DefaultUserInfoOrg := '{sysuserinfoorg}'; SetupHeader.BackColor := clBlue; SetupHeader.BackColor2 := clBlack; SetupHeader.DisableDirPage := dpNo; SetupHeader.DisableProgramGroupPage := dpNo; SetupHeader.CreateUninstallRegKey := 'yes'; SetupHeader.Uninstallable := 'yes'; BackSolid := False; SetupHeader.WizardImageBackColor := $400000; WizardImageFile := 'compiler:WIZMODERNIMAGE.BMP'; WizardSmallImageFile := 'compiler:WIZMODERNSMALLIMAGE.BMP'; DefaultDialogFontName := 'Tahoma'; SignTool := ''; SetupHeader.CloseApplicationsFilter := '*.exe,*.dll,*.chm'; { Read [Setup] section } EnumIniSection(EnumSetup, 'Setup', 0, True, True, '', False, False); CallIdleProc; { Verify settings set in [Setup] section } if SetupDirectiveLines[ssAppName] = 0 then AbortCompileFmt(SCompilerEntryMissing2, ['Setup', 'AppName']); if (SetupHeader.AppVerName = '') and (SetupHeader.AppVersion = '') then AbortCompile(SCompilerAppVersionOrAppVerNameRequired); LineNumber := SetupDirectiveLines[ssAppName]; AppNameHasConsts := CheckConst(SetupHeader.AppName, SetupHeader.MinVersion, []); if AppNameHasConsts and not(shDisableStartupPrompt in SetupHeader.Options) then begin { AppName has contants so DisableStartupPrompt must be used } LineNumber := SetupDirectiveLines[ssDisableStartupPrompt]; AbortCompile(SCompilerMustUseDisableStartupPrompt); end; if SetupHeader.AppId = '' then SetupHeader.AppId := SetupHeader.AppName else LineNumber := SetupDirectiveLines[ssAppId]; AppIdHasConsts := CheckConst(SetupHeader.AppId, SetupHeader.MinVersion, []); if AppIdHasConsts and (shUsePreviousLanguage in SetupHeader.Options) then begin { AppId has contants so UsePreviousLanguage must not be used } LineNumber := SetupDirectiveLines[ssUsePreviousLanguage]; AbortCompile(SCompilerMustNotUsePreviousLanguage); end; LineNumber := SetupDirectiveLines[ssAppVerName]; CheckConst(SetupHeader.AppVerName, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppComments]; CheckConst(SetupHeader.AppComments, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppContact]; CheckConst(SetupHeader.AppContact, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppCopyright]; AppCopyrightHasConsts := CheckConst(SetupHeader.AppCopyright, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppModifyPath]; CheckConst(SetupHeader.AppModifyPath, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppPublisher]; AppPublisherHasConsts := CheckConst(SetupHeader.AppPublisher, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppPublisherURL]; CheckConst(SetupHeader.AppPublisherURL, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppReadmeFile]; CheckConst(SetupHeader.AppReadmeFile, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppSupportPhone]; CheckConst(SetupHeader.AppSupportPhone, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppSupportURL]; CheckConst(SetupHeader.AppSupportURL, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppUpdatesURL]; CheckConst(SetupHeader.AppUpdatesURL, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppVersion]; AppVersionHasConsts := CheckConst(SetupHeader.AppVersion, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssAppMutex]; CheckConst(SetupHeader.AppMutex, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssDefaultDirName]; CheckConst(SetupHeader.DefaultDirName, SetupHeader.MinVersion, []); if SetupHeader.DefaultDirName = '' then begin if shCreateAppDir in SetupHeader.Options then AbortCompileFmt(SCompilerEntryMissing2, ['Setup', 'DefaultDirName']) else SetupHeader.DefaultDirName := '?ERROR?'; end; LineNumber := SetupDirectiveLines[ssDefaultGroupName]; CheckConst(SetupHeader.DefaultGroupName, SetupHeader.MinVersion, []); if SetupHeader.DefaultGroupName = '' then SetupHeader.DefaultGroupName := '(Default)'; LineNumber := SetupDirectiveLines[ssUninstallDisplayName]; CheckConst(SetupHeader.UninstallDisplayName, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssUninstallDisplayIcon]; CheckConst(SetupHeader.UninstallDisplayIcon, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssUninstallFilesDir]; CheckConst(SetupHeader.UninstallFilesDir, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssDefaultUserInfoName]; CheckConst(SetupHeader.DefaultUserInfoName, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssDefaultUserInfoOrg]; CheckConst(SetupHeader.DefaultUserInfoOrg, SetupHeader.MinVersion, []); LineNumber := SetupDirectiveLines[ssDefaultUserInfoSerial]; CheckConst(SetupHeader.DefaultUserInfoSerial, SetupHeader.MinVersion, []); if BackSolid then SetupHeader.BackColor2 := SetupHeader.BackColor; if not DiskSpanning then begin DiskSliceSize := MaxDiskSliceSize; DiskClusterSize := 1; SlicesPerDisk := 1; ReserveBytes := 0; end; SetupHeader.SlicesPerDisk := SlicesPerDisk; if SetupDirectiveLines[ssVersionInfoDescription] = 0 then begin { Use AppName as VersionInfoDescription if possible. If not possible, warn about this since AppName is a required directive } if not AppNameHasConsts then VersionInfoDescription := UnescapeBraces(SetupHeader.AppName) + ' Setup' else WarningsList.Add(Format(SCompilerDirectiveNotUsingDefault, ['VersionInfoDescription', 'AppName'])); end; if SetupDirectiveLines[ssVersionInfoCompany] = 0 then begin { Use AppPublisher as VersionInfoCompany if possible, otherwise warn } if not AppPublisherHasConsts then VersionInfoCompany := UnescapeBraces(SetupHeader.AppPublisher) else WarningsList.Add(Format(SCompilerDirectiveNotUsingDefault, ['VersionInfoCompany', 'AppPublisher'])); end; if SetupDirectiveLines[ssVersionInfoCopyright] = 0 then begin { Use AppCopyright as VersionInfoCopyright if possible, otherwise warn } if not AppCopyrightHasConsts then VersionInfoCopyright := UnescapeBraces(SetupHeader.AppCopyright) else WarningsList.Add(Format(SCompilerDirectiveNotUsingDefault, ['VersionInfoCopyright', 'AppCopyright'])); end; if SetupDirectiveLines[ssVersionInfoTextVersion] = 0 then VersionInfoTextVersion := VersionInfoVersionOriginalValue; if SetupDirectiveLines[ssVersionInfoProductName] = 0 then begin { Use AppName as VersionInfoProductName if possible, otherwise warn } if not AppNameHasConsts then VersionInfoProductName := UnescapeBraces(SetupHeader.AppName) else WarningsList.Add(Format(SCompilerDirectiveNotUsingDefault, ['VersionInfoProductName', 'AppName'])); end; if VersionInfoProductVersionOriginalValue = '' then VersionInfoProductVersion := VersionInfoVersion; if SetupDirectiveLines[ssVersionInfoProductTextVersion] = 0 then begin { Note: This depends on the initialization of VersionInfoTextVersion above } if VersionInfoProductVersionOriginalValue = '' then begin VersionInfoProductTextVersion := VersionInfoTextVersion; if SetupHeader.AppVersion <> '' then begin if not AppVersionHasConsts then VersionInfoProductTextVersion := UnescapeBraces(SetupHeader.AppVersion) else WarningsList.Add(Format(SCompilerDirectiveNotUsingPreferredDefault, ['VersionInfoProductTextVersion', 'VersionInfoTextVersion', 'AppVersion'])); end; end else VersionInfoProductTextVersion := VersionInfoProductVersionOriginalValue; end; if (shEncryptionUsed in SetupHeader.Options) and (CryptKey = '') then begin LineNumber := SetupDirectiveLines[ssEncryption]; AbortCompileFmt(SCompilerEntryMissing2, ['Setup', 'Password']); end; if (SetupDirectiveLines[ssSignedUninstaller] = 0) and (SignTool <> '') then Include(SetupHeader.Options, shSignedUninstaller); if not UseSetupLdr and ((SignTool <> '') or (shSignedUninstaller in SetupHeader.Options)) then AbortCompile(SCompilerNoSetupLdrSignError); LineNumber := SetupDirectiveLines[ssCreateUninstallRegKey]; CheckCheckOrInstall('CreateUninstallRegKey', SetupHeader.CreateUninstallRegKey, cikDirectiveCheck); LineNumber := SetupDirectiveLines[ssUninstallable]; CheckCheckOrInstall('Uninstallable', SetupHeader.Uninstallable, cikDirectiveCheck); LineNumber := 0; SourceDir := AddBackslash(PathExpand(SourceDir)); if not FixedOutputDir then OutputDir := PrependSourceDirName(OutputDir); OutputDir := RemoveBackslashUnlessRoot(PathExpand(OutputDir)); if not DirExists(OutputDir) then begin AddStatus(Format(SCompilerStatusCreatingOutputDir, [OutputDir])); MkDirs(OutputDir); end; OutputDir := AddBackslash(OutputDir); if SignedUninstallerDir = '' then SignedUninstallerDir := OutputDir else begin SignedUninstallerDir := RemoveBackslashUnlessRoot(PathExpand(PrependSourceDirName(SignedUninstallerDir))); if not DirExists(SignedUninstallerDir) then begin AddStatus(Format(SCompilerStatusCreatingSignedUninstallerDir, [SignedUninstallerDir])); MkDirs(SignedUninstallerDir); end; SignedUninstallerDir := AddBackslash(SignedUninstallerDir); end; { Read text files } if LicenseFile <> '' then begin LineNumber := SetupDirectiveLines[ssLicenseFile]; AddStatus(Format(SCompilerStatusReadingFile, ['LicenseFile'])); ReadTextFile(PrependSourceDirName(LicenseFile), -1, LicenseText); end; if InfoBeforeFile <> '' then begin LineNumber := SetupDirectiveLines[ssInfoBeforeFile]; AddStatus(Format(SCompilerStatusReadingFile, ['InfoBeforeFile'])); ReadTextFile(PrependSourceDirName(InfoBeforeFile), -1, InfoBeforeText); end; if InfoAfterFile <> '' then begin LineNumber := SetupDirectiveLines[ssInfoAfterFile]; AddStatus(Format(SCompilerStatusReadingFile, ['InfoAfterFile'])); ReadTextFile(PrependSourceDirName(InfoAfterFile), -1, InfoAfterText); end; LineNumber := 0; CallIdleProc; { Read wizard image } LineNumber := SetupDirectiveLines[ssWizardImageFile]; AddStatus(Format(SCompilerStatusReadingFile, ['WizardImageFile'])); AddStatus(Format(SCompilerStatusReadingInFile, [PrependSourceDirName(WizardImageFile)])); WizardImage := CreateMemoryStreamFromFile(PrependSourceDirName(WizardImageFile)); LineNumber := SetupDirectiveLines[ssWizardSmallImageFile]; AddStatus(Format(SCompilerStatusReadingFile, ['WizardSmallImageFile'])); AddStatus(Format(SCompilerStatusReadingInFile, [PrependSourceDirName(WizardSmallImageFile)])); WizardSmallImage := CreateMemoryStreamFromFile(PrependSourceDirName(WizardSmallImageFile)); LineNumber := 0; { Prepare Setup executable & signed uninstaller data } PrepareSetupE32(SetupE32); { Read languages: Non Unicode: 1. Read Default.isl messages: ReadDefaultMessages calls EnumMessages for Default.isl's [Messages], with Ext set to -2. These messages are stored in DefaultLangData to be used as defaults for missing messages later on. EnumLangOptions isn't called, the defaults will (at run-time) be displayed using the code page of the language with the missing messages. EnumMessages for Default.isl's [CustomMessages] also isn't called at this point, missing custom messages are handled differently. 2. Read [Languages] section and the .isl files the entries reference: EnumLanguages is called for the script. For each [Languages] entry its parameters are read and for the MessagesFiles parameter ReadMessagesFromFiles is called. For each file ReadMessagesFromFiles first calls EnumLangOptions, then EnumMessages for [Messages], and finally another EnumMessages for [CustomMessages], all with Ext set to the index of the language. All the [LangOptions] and [Messages] data is stored in single structures per language, namely LanguageEntries[Ext] (langoptions) and LangDataList[Ext] (messages), any 'double' directives or messages overwrite each other. This means if that for example the first messages file does not specify a code page, but the second does, the language will automatically use the code page of the second file. And vice versa. The [CustomMessages] data is stored in a single list for all languages, with each entry having a LangIndex property saying to which language it belongs. If a 'double' custom message is found, the existing one is removed from the list. 3. Read [LangOptions] & [Messages] & [CustomMessages] in the script: ReadMessagesFromScript is called and this will first call CreateDefaultLanguageEntry if no languages have been defined. CreateDefaultLanguageEntry first creates a language with all settings set to the default, and then it calles ReadMessagesFromFiles for Default.isl for this language. ReadMessagesFromFiles works as described above. Note this is just like the script creator creating an entry for Default.isl. ReadMessagesFromScript then first calls EnumLangOptions, then EnumMessages for [Messages], and finally another EnumMessages for [CustomMessages] for the script. Note this is just like ReadMessagesFromFiles does for files, except that Ext is set to -1. This causes it to accept language identifiers ('en.LanguageCodePage=...'): if the identifier is set the read data is stored only for that language in the structures described above. If the identifier is not set, the read data is stored for all languages either by writing to all structures (langoptions/messages) or by adding an entry with LangIndex set to -1 (custommessages). This for example means all language code pages read so far could be overwritten from the script. ReadMessagesFromScript then checks for any missing messages and uses the messages read in the very beginning to provide defaults. After ReadMessagesFromScript returns, the read messages stored in the LangDataList entries are streamed into the LanguageEntry.Data fields by PopulateLanguageEntryData. 4. Check 'language completeness' of custom message constants: CheckCustomMessageDefinitions is used to check for missing custom messages and where necessary it 'promotes' a custom message by resetting its LangIndex property to -1. 5. Display the language at run time: Setup checks if the system code page matches the language code page, and only shows the language if it does. The system code page is then used to display all text, this does not only include messages and custom messages, but also any readme and info files. Unicode: Unicode works exactly like above with one exception: 0. Determine final code pages: Unicode Setup uses Unicode text and does not depend on the system code page. To provide Setup with Unicode text without requiring Unicode .isl files (but still supporting Unicode .iss, license and info files), the compiler converts the .isl files to Unicode during compilation. It also does this if it finds ANSI plain text license and info files. To be able to do this it needs to know the language's code page but as seen above it can't simply take this from the current .isl. And license and info files do not even have a language code page setting. This means the Unicode compiler has to do an extra phase: following the logic above it first determines the final language code page for each language, storing these into an extra list called PreDataList, and then it continues as normal while using the final language code page for any conversions needed. Note: it must avoid caching the .isl files while determining the code pages, since the conversion is done *before* the caching. } {$IFDEF UNICODE} { 0. Determine final language code pages } AddStatus(SCompilerStatusDeterminingCodePages); { 0.1. Read [Languages] section and [LangOptions] in the .isl files the entries reference } EnumIniSection(EnumLanguagesPre, 'Languages', 0, True, True, '', False, True); CallIdleProc; { 0.2. Read [LangOptions] in the script } ReadMessagesFromScriptPre; {$ENDIF} { 1. Read Default.isl messages } AddStatus(SCompilerStatusReadingDefaultMessages); ReadDefaultMessages; { 2. Read [Languages] section and the .isl files the entries reference } EnumIniSection(EnumLanguages, 'Languages', 0, True, True, '', False, False); CallIdleProc; { 3. Read [LangOptions] & [Messages] & [CustomMessages] in the script } AddStatus(SCompilerStatusParsingMessages); ReadMessagesFromScript; PopulateLanguageEntryData; { 4. Check 'language completeness' of custom message constants } CheckCustomMessageDefinitions; { Read (but not compile) [Code] section } ReadCode; { Read [Types] section } EnumIniSection(EnumTypes, 'Types', 0, True, True, '', False, False); CallIdleProc; { Read [Components] section } EnumIniSection(EnumComponents, 'Components', 0, True, True, '', False, False); CallIdleProc; { Read [Tasks] section } EnumIniSection(EnumTasks, 'Tasks', 0, True, True, '', False, False); CallIdleProc; { Read [Dirs] section } EnumIniSection(EnumDirs, 'Dirs', 0, True, True, '', False, False); CallIdleProc; { Read [Icons] section } EnumIniSection(EnumIcons, 'Icons', 0, True, True, '', False, False); CallIdleProc; { Read [INI] section } EnumIniSection(EnumINI, 'INI', 0, True, True, '', False, False); CallIdleProc; { Read [Registry] section } EnumIniSection(EnumRegistry, 'Registry', 0, True, True, '', False, False); CallIdleProc; { Read [InstallDelete] section } EnumIniSection(EnumDelete, 'InstallDelete', 0, True, True, '', False, False); CallIdleProc; { Read [UninstallDelete] section } EnumIniSection(EnumDelete, 'UninstallDelete', 1, True, True, '', False, False); CallIdleProc; { Read [Run] section } EnumIniSection(EnumRun, 'Run', 0, True, True, '', False, False); CallIdleProc; { Read [UninstallRun] section } EnumIniSection(EnumRun, 'UninstallRun', 1, True, True, '', False, False); CallIdleProc; { Read [Files] section } if not TryStrToBoolean(SetupHeader.Uninstallable, Uninstallable) or Uninstallable then EnumFiles('', 1); EnumIniSection(EnumFiles, 'Files', 0, True, True, '', False, False); CallIdleProc; { Read decompressor DLL. Must be done after [Files] is parsed, since SetupHeader.CompressMethod isn't set until then } case SetupHeader.CompressMethod of cmZip: begin AddStatus(Format(SCompilerStatusReadingFile, ['isunzlib.dll'])); DecompressorDLL := CreateMemoryStreamFromFile(CompilerDir + 'isunzlib.dll'); end; cmBzip: begin AddStatus(Format(SCompilerStatusReadingFile, ['isbunzip.dll'])); DecompressorDLL := CreateMemoryStreamFromFile(CompilerDir + 'isbunzip.dll'); end; end; { Read decryption DLL } if shEncryptionUsed in SetupHeader.Options then begin AddStatus(Format(SCompilerStatusReadingFile, ['iscrypt.dll'])); if not NewFileExists(CompilerDir + 'iscrypt.dll') then AbortCompile(SCompilerISCryptMissing); DecryptionDLL := CreateMemoryStreamFromFile(CompilerDir + 'iscrypt.dll'); end; { Add default types if necessary } if (ComponentEntries.Count > 0) and (TypeEntries.Count = 0) then begin AddDefaultSetupType(DefaultTypeEntryNames[0], [], ttDefaultFull); AddDefaultSetupType(DefaultTypeEntryNames[1], [], ttDefaultCompact); AddDefaultSetupType(DefaultTypeEntryNames[2], [toIsCustom], ttDefaultCustom); end; { Check existance of expected custom message constants } CheckCustomMessageReferences; { Compile CodeText } CompileCode; CallIdleProc; { Clear any existing setup* files out of the output directory first } EmptyOutputDir(True); if OutputManifestFile <> '' then DeleteFile(PrependDirName(OutputManifestFile, OutputDir)); { Create setup files } AddStatus(SCompilerStatusCreateSetupFiles); ExeFilename := OutputDir + OutputBaseFilename + '.exe'; try if not UseSetupLdr then begin SetupFile := TFile.Create(ExeFilename, fdCreateAlways, faWrite, fsNone); try SetupFile.WriteBuffer(SetupE32.Memory^, SetupE32.Size.Lo); SizeOfExe := SetupFile.Size.Lo; finally SetupFile.Free; end; CallIdleProc; if not DiskSpanning then begin { Create SETUP-0.BIN and SETUP-1.BIN } CompressFiles('', 0); CreateSetup0File; end else begin { Create SETUP-0.BIN and SETUP-*.BIN } SizeOfHeaders := CreateSetup0File; CompressFiles('', RoundToNearestClusterSize(SizeOfExe) + RoundToNearestClusterSize(SizeOfHeaders) + RoundToNearestClusterSize(ReserveBytes)); { CompressFiles modifies setup header data, so go back and rewrite it } if CreateSetup0File <> SizeOfHeaders then { Make sure new and old size match. No reason why they shouldn't but check just in case } AbortCompile(SCompilerSetup0Mismatch); end; end else begin CopyFileOrAbort(CompilerDir + 'SETUPLDR.E32', ExeFilename); { if there was a read-only attribute, remove it } SetFileAttributes(PChar(ExeFilename), FILE_ATTRIBUTE_ARCHIVE); if SetupIconFilename <> '' then begin { update icons } AddStatus(Format(SCompilerStatusUpdatingIcons, ['SETUP.EXE'])); LineNumber := SetupDirectiveLines[ssSetupIconFile]; UpdateIcons(ExeFilename, PrependSourceDirName(SetupIconFilename)); LineNumber := 0; end; SetupFile := TFile.Create(ExeFilename, fdOpenExisting, faReadWrite, fsNone); try UpdateSetupPEHeaderFields(SetupFile, TerminalServicesAware); SizeOfExe := SetupFile.Size.Lo; finally SetupFile.Free; end; CallIdleProc; { When disk spanning isn't used, place the compressed files inside SETUP.EXE } if not DiskSpanning then CompressFiles(ExeFilename, 0); ExeFile := TFile.Create(ExeFilename, fdOpenExisting, faReadWrite, fsNone); try ExeFile.SeekToEnd; { Move the data from SETUP.E?? into the SETUP.EXE, and write header data } FillChar(SetupLdrOffsetTable, SizeOf(SetupLdrOffsetTable), 0); SetupLdrOffsetTable.ID := SetupLdrOffsetTableID; SetupLdrOffsetTable.Version := SetupLdrOffsetTableVersion; SetupLdrOffsetTable.Offset0 := ExeFile.Position.Lo; SizeOfHeaders := WriteSetup0(ExeFile); SetupLdrOffsetTable.OffsetEXE := ExeFile.Position.Lo; CompressSetupE32(SetupE32, ExeFile, SetupLdrOffsetTable.UncompressedSizeEXE, SetupLdrOffsetTable.CRCEXE); SetupLdrOffsetTable.TotalSize := ExeFile.Size.Lo; if DiskSpanning then begin SetupLdrOffsetTable.Offset1 := 0; { Compress the files in SETUP-*.BIN after we know the size of SETUP.EXE } CompressFiles('', RoundToNearestClusterSize(SetupLdrOffsetTable.TotalSize) + RoundToNearestClusterSize(ReserveBytes)); { CompressFiles modifies setup header data, so go back and rewrite it } ExeFile.Seek(SetupLdrOffsetTable.Offset0); if WriteSetup0(ExeFile) <> SizeOfHeaders then { Make sure new and old size match. No reason why they shouldn't but check just in case } AbortCompile(SCompilerSetup0Mismatch); end else SetupLdrOffsetTable.Offset1 := SizeOfExe; SetupLdrOffsetTable.TableCRC := GetCRC32(SetupLdrOffsetTable, SizeOf(SetupLdrOffsetTable) - SizeOf(SetupLdrOffsetTable.TableCRC)); { Write SetupLdrOffsetTable to SETUP.EXE } if SeekToResourceData(ExeFile, Cardinal(RT_RCDATA), SetupLdrOffsetTableResID) <> SizeOf(SetupLdrOffsetTable) then AbortCompile('Wrong offset table resource size'); ExeFile.WriteBuffer(SetupLdrOffsetTable, SizeOf(SetupLdrOffsetTable)); { Update version info } AddStatus(SCompilerStatusUpdatingVersionInfo); UpdateVersionInfo(ExeFile, VersionInfoVersion, VersionInfoProductVersion, VersionInfoCompany, VersionInfoDescription, VersionInfoTextVersion, VersionInfoCopyright, VersionInfoProductName, VersionInfoProductTextVersion); { For some reason, on Win95 the date/time of the EXE sometimes doesn't get updated after it's been written to so it has to manually set it. (I don't get it!!) } UpdateTimeStamp(ExeFile.Handle); finally ExeFile.Free; end; end; { Sign } SignToolIndex := FindSignToolIndexByName(SignTool); if SignToolIndex <> -1 then begin AddStatus(SCompilerStatusSigningSetup); Sign(TSignTool(SignToolList[SignToolIndex]).Command, SignToolParams, ExeFilename); end; except EmptyOutputDir(False); raise; end; CallIdleProc; { Create manifest file } if OutputManifestFile <> '' then begin AddStatus(SCompilerStatusCreateManifestFile); CreateManifestFile; CallIdleProc; end; { Finalize debug info } FinalizeDebugInfo; { Done } AddStatus(''); for I := 0 to WarningsList.Count-1 do AddStatus(SCompilerStatusWarning + WarningsList[I]); asm jmp @1; db 0,'Inno Setup Compiler, Copyright (C) 1997-2010 Jordan Russell, ' db 'Portions Copyright (C) 2000-2010 Martijn Laan',0; @1: end; { Note: Removing or modifying the copyright text is a violation of the Inno Setup license agreement; see LICENSE.TXT. } finally CallPreprocessorCleanupProc; WarningsList.Clear; { Free all the data } DecryptionDLL.Free; DecompressorDLL.Free; SetupE32.Free; WizardSmallImage.Free; WizardImage.Free; FreeListItems(LanguageEntries, SetupLanguageEntryStrings, SetupLanguageEntryAnsiStrings); FreeListItems(CustomMessageEntries, SetupCustomMessageEntryStrings, SetupCustomMessageEntryAnsiStrings); FreeListItems(PermissionEntries, SetupPermissionEntryStrings, SetupPermissionEntryAnsiStrings); FreeListItems(TypeEntries, SetupTypeEntryStrings, SetupTypeEntryAnsiStrings); FreeListItems(ComponentEntries, SetupComponentEntryStrings, SetupComponentEntryAnsiStrings); FreeListItems(TaskEntries, SetupTaskEntryStrings, SetupTaskEntryAnsiStrings); FreeListItems(DirEntries, SetupDirEntryStrings, SetupDirEntryAnsiStrings); FreeListItems(FileEntries, SetupFileEntryStrings, SetupFileEntryAnsiStrings); FreeListItems(FileLocationEntries, SetupFileLocationEntryStrings, SetupFileLocationEntryAnsiStrings); FreeListItems(IconEntries, SetupIconEntryStrings, SetupIconEntryAnsiStrings); FreeListItems(IniEntries, SetupIniEntryStrings, SetupIniEntryAnsiStrings); FreeListItems(RegistryEntries, SetupRegistryEntryStrings, SetupRegistryEntryAnsiStrings); FreeListItems(InstallDeleteEntries, SetupDeleteEntryStrings, SetupDeleteEntryAnsiStrings); FreeListItems(UninstallDeleteEntries, SetupDeleteEntryStrings, SetupDeleteEntryAnsiStrings); FreeListItems(RunEntries, SetupRunEntryStrings, SetupRunEntryAnsiStrings); FreeListItems(UninstallRunEntries, SetupRunEntryStrings, SetupRunEntryAnsiStrings); FileLocationEntryFilenames.Clear; FreeLineInfoList(ExpectedCustomMessageNames); FreeLangData; {$IFDEF UNICODE} FreePreLangData; {$ENDIF} FreeScriptFiles; FreeLineInfoList(CodeText); FreeAndNil(CompressProps); FreeAndNil(InternalCompressProps); end; end; { Interface functions } function ISCompileScript(const Params: TCompileScriptParamsEx; const PropagateExceptions: Boolean): Integer; var SetupCompiler: TSetupCompiler; P: PChar; Data: TCompilerCallbackData; S: String; P2: Integer; begin if ((Params.Size <> SizeOf(Params)) and (Params.Size <> SizeOf(TCompileScriptParams))) or not Assigned(Params.CallbackProc) then begin Result := isceInvalidParam; Exit; end; SetupCompiler := TSetupCompiler.Create(nil); try SetupCompiler.AppData := Params.AppData; SetupCompiler.CallbackProc := Params.CallbackProc; if Assigned(Params.CompilerPath) then SetupCompiler.CompilerDir := Params.CompilerPath else SetupCompiler.CompilerDir := PathExtractPath(GetSelfFilename); SetupCompiler.SourceDir := Params.SourcePath; { Parse Options (only present in TCompileScriptParamsEx) } if (Params.Size <> SizeOf(TCompileScriptParams)) and Assigned(Params.Options) then begin P := Params.Options; while P^ <> #0 do begin if StrLIComp(P, 'OutputDir=', Length('OutputDir=')) = 0 then begin Inc(P, Length('OutputDir=')); SetupCompiler.OutputDir := P; SetupCompiler.FixedOutputDir := True; end else if StrLIComp(P, 'OutputBaseFilename=', Length('OutputBaseFilename=')) = 0 then begin Inc(P, Length('OutputBaseFilename=')); SetupCompiler.OutputBaseFilename := P; SetupCompiler.FixedOutputBaseFilename := True; end else if StrLIComp(P, 'SignTool-', Length('SignTool-')) = 0 then begin Inc(P, Length('SignTool-')); P2 := Pos('=', P); if (P2 <> 0) then SetupCompiler.AddSignTool(Copy(P, 1, P2-1), Copy(P, P2+1, MaxInt)) else begin { Bad option } Result := isceInvalidParam; Exit; end; end else if StrLIComp(P, 'ISPP:', Length('ISPP:')) = 0 then begin SetupCompiler.PreprocOptionsString := SetupCompiler.PreprocOptionsString + P + #0; end else begin { Unknown option } Result := isceInvalidParam; Exit; end; Inc(P, StrLen(P) + 1); end; end; Result := isceNoError; try SetupCompiler.Compile; except Result := isceCompileFailure; Data.ErrorMsg := nil; Data.ErrorFilename := nil; Data.ErrorLine := 0; if not(ExceptObject is EAbort) then begin S := GetExceptMessage; Data.ErrorMsg := PChar(S); { use a Pointer cast instead of PChar so that we'll get a null pointer if the string is empty } Data.ErrorFilename := Pointer(SetupCompiler.ParseFilename); Data.ErrorLine := SetupCompiler.LineNumber; end; Params.CallbackProc(iscbNotifyError, Data, Params.AppData); if PropagateExceptions then raise; Exit; end; Data.OutputExeFilename := PChar(SetupCompiler.ExeFilename); Data.DebugInfo := SetupCompiler.DebugInfo.Memory; Data.DebugInfoSize := SetupCompiler.DebugInfo.Size; Params.CallbackProc(iscbNotifySuccess, Data, Params.AppData); finally SetupCompiler.Free; end; end; function ISGetVersion: PCompilerVersionInfo; const Ver: TCompilerVersionInfo = (Title: SetupTitle; Version: SetupVersion; BinVersion: SetupBinVersion); begin Result := @Ver; end; initialization {$IFNDEF UNICODE} GetLeadBytes(CompilerLeadBytes); ConstLeadBytes := @CompilerLeadBytes; {$ENDIF} finalization if CryptProv <> 0 then begin CryptReleaseContext(CryptProv, 0); CryptProv := 0; end; end.
unit BitFonts; // Bitmapped Fonts. Copyright (c) 1997 Jorge Romero Gomez, Merchise. interface uses SysUtils, Classes, Windows, Graphics, Buffer; type TBitFontChar = class; PCharList = ^TCharList; TCharList = array[0..0] of TBitFontChar; TBitFont = class( TPersistent ) private fProportional : boolean; //fBitmap : TBuffer; fFirstIndx : integer; fCount : integer; fCharacters : PCharList; fCTT : pointer; protected function GetCharacter( Ch : char ) : TBitFontChar; procedure SelectCTT( Value : pointer ); public property CTT : pointer read fCTT write SelectCTT; property Count : integer read fCount; property FirstIndx : integer read fFirstIndx; property Character[ Ch : char ] : TBitFontChar read GetCharacter; default; property Proportional : boolean read fProportional; constructor Create; constructor CreateFromTrueType( aFont : TFont; aProportional : boolean; aFirstIndx, aCount : integer ); destructor Destroy; override; procedure SaveToStream( Stream : TStream ); virtual; procedure SaveToFile( const Filename : string ); virtual; procedure LoadFromStream( Stream : TStream ); virtual; procedure LoadFromFile( const Filename : string ); virtual; procedure LoadFromResourceName( Instance : THandle; const ResourceName : string ); procedure LoadFromResourceID( Instance : THandle; ResourceId : Integer ); procedure TextOut( x, y : integer; const Text : string ); end; TBitFontChar = class( TPersistent ) private fImageAddr : pointer; fImageCoord : TPoint; fWidth : integer; fHeight : integer; fVertOffset : integer; fFont : TBitFont; protected public constructor Create; destructor Destroy; override; procedure LoadFromStream( Stream : TStream ); virtual; function Draw( x, y : integer ) : integer; property Font : TBitFont read fFont; property ImageAddr : pointer read fImageAddr; property ImageCoord : TPoint read fImageCoord; property Width : integer read fWidth; property Height : integer read fHeight; property VertOffset : integer read fVertOffset; end; implementation uses StreamUtils; // TBitFont procedure TBitFont.SelectCTT( Value : pointer ); begin fCTT := Value; end; constructor TBitFont.CreateFromTrueType( aFont : TFont; aProportional : boolean; aFirstIndx, aCount : integer ); begin Create; end; constructor TBitFont.Create; begin inherited; // end; destructor TBitFont.Destroy; begin // inherited; end; function TBitFont.GetCharacter( Ch : char ) : TBitFontChar; begin assert( Ch in [char(FirstIndx)..char(FirstIndx + Count)], 'Index out of bounds in BitFonts.TBitFont.GetCharacter!!' ); Result := fCharacters[ord(Ch) - FirstIndx]; end; procedure TBitFont.SaveToStream( Stream : TStream ); begin try // except // raise; end; end; procedure TBitFont.SaveToFile( const Filename : string ); begin StreamObject( TFileStream.Create( Filename, fmCreate or fmShareExclusive ), SaveToStream ); end; procedure TBitFont.LoadFromStream( Stream : TStream ); begin try // except // raise; end; end; procedure TBitFont.LoadFromFile( const Filename : string ); begin StreamObject( TFileStream.Create( Filename, fmOpenRead or fmShareDenyWrite ), LoadFromStream ); end; procedure TBitFont.LoadFromResourceName( Instance : THandle; const ResourceName : string ); begin StreamObject( TResourceStream.Create( Instance, ResourceName, RT_BITMAP ), LoadFromStream ); end; procedure TBitFont.LoadFromResourceID( Instance : THandle; ResourceId : Integer ); begin StreamObject( TResourceStream.CreateFromID( Instance, ResourceId, RT_BITMAP ), LoadFromStream ); end; procedure TBitFont.TextOut( x, y : integer; const Text : string ); var i : integer; begin for i := 1 to length( Text ) do Inc( x, Character[Text[i]].Draw( x, y ) ); end; // TBitFontChar function TBitFontChar.Draw( x, y : integer ) : integer; begin with Font do begin // end; Result := Width; end; constructor TBitFontChar.Create; begin inherited Create; // end; destructor TBitFontChar.Destroy; begin // inherited; end; procedure TBitFontChar.LoadFromStream( Stream : TStream ); begin try // except // raise; end; end; end.
unit UnitDemo2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) btnCopy: TButton; btnWrite: TButton; btnRead: TButton; mmoDisplay: TMemo; btnLoad: TButton; procedure btnCopyClick(Sender: TObject); procedure btnWriteClick(Sender: TObject); procedure btnReadClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; const SOURCE_FILE = 'D:\test\Demo3.txt'; implementation {$R *.dfm} procedure TForm1.btnCopyClick(Sender: TObject); var readFileStream,writeFileStream:TFileStream; begin try // 创建对象 readFileStream:=TFileStream.Create('D:\test\Demo2.txt',fmOpenRead); writeFileStream:=TFileStream.Create('D:\test\Demo2Copy.txt',fmCreate); // 设置读取的位置 readFileStream.Position:=0; writeFileStream.CopyFrom(readFileStream,readFileStream.Size); // 显示读写大小 ShowMessage(IntToStr(writeFileStream.Size)); finally // 释放资源 FreeAndNil(readFileStream); FreeAndNil(writeFileStream); end; end; procedure TForm1.btnLoadClick(Sender: TObject); var FileStream:TFileStream; strRead:UTF8String; begin try // 创建对象 FileStream:=TFileStream.Create(SOURCE_FILE,fmOpenRead); // 设置开始读位置 FileStream.Position:=0; // 设置字符串长度 SetLength(strRead,FileStream.Size); // 读入数据到字符串 FileStream.Read(PChar(strRead)^,FileStream.Size); Self.mmoDisplay.Lines.Add(strRead); finally // 释放资源 FreeAndNil(FileStream); end; end; procedure TForm1.btnReadClick(Sender: TObject); var FileStream:TFileStream; strRead:UTF8String; begin try // 创建对象 FileStream:=TFileStream.Create(SOURCE_FILE,fmOpenRead); // 设置开始读位置 FileStream.Position:=0; // 设置字符串长度 SetLength(strRead,FileStream.Size); // 读入数据到字符串 FileStream.Read(PChar(strRead)^,FileStream.Size); ShowMessage(strRead); finally FreeAndNil(FileStream); end; end; procedure TForm1.btnWriteClick(Sender: TObject); var FileStream:TFileStream; str:string; strByte:TBytes; begin // 字符串注意 1、长度 2、编码 unicode,utf-8,GBK str:='Hello,World.I am 陈怡彬.'; try // 创建对象 FileStream:=TFileStream.Create(SOURCE_FILE,fmCreate); // 将string转换为指定编码的字节数组 strByte:=TEncoding.UTF8.GetBytes(str); // ^在右边解除指针引用,从而获取其中数据 FileStream.WriteBuffer(strByte,Length(strByte)); finally FreeAndNil(FileStream); end; end; end.
unit fmScriptButton; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ADC.Types, ADC.ScriptBtn, Vcl.ExtCtrls; type TForm_ScriptButton = class(TForm) Label_Title: TLabel; Label1: TLabel; Label2: TLabel; Edit_Title: TEdit; Edit_Description: TEdit; Edit_Path: TEdit; Button_Cancel: TButton; Button_OK: TButton; Label_Parameters: TLabel; Edit_Parameters: TEdit; Label_dn: TLabel; Label_h: TLabel; Label_a: TLabel; Label_h_Hint: TLabel; Label_a_Hint: TLabel; Label3: TLabel; Bevel1: TBevel; Button_Browse: TButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button_CancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button_OKClick(Sender: TObject); procedure Button_BrowseClick(Sender: TObject); private FCallingForm: TForm; FObj: PADScriptButton; FMode: Byte; FOnScriptButtonCreate: TCreateScriptButtonProc; FOnScriptButtonChange: TChangeScriptButtonProc; procedure SetCallingForm(const Value: TForm); procedure SetObject(const Value: PADScriptButton); procedure SetMode(const Value: Byte); procedure ClearTextFields; public property CallingForm: TForm write SetCallingForm; property Mode: Byte read FMode write SetMode; property ScriptButton: PADScriptButton read FObj write SetObject; property OnScriptButtonCreate: TCreateScriptButtonProc read FOnScriptButtonCreate write FOnScriptButtonCreate; property OnScriptButtonChange: TChangeScriptButtonProc read FOnScriptButtonChange write FOnScriptButtonChange; end; var Form_ScriptButton: TForm_ScriptButton; implementation {$R *.dfm} uses dmDataModule; { TForm_ScriptButton } procedure TForm_ScriptButton.Button_BrowseClick(Sender: TObject); begin with DM1.OpenDialog do begin FileName := ''; Filter := 'Файлы сценария VBScript (*.vbs)|*.vbs' + '|Файлы сценария JavaScript (*.js)|*.js' + '|Все файлы (*.*)|*.*'; FilterIndex := 1; Options := Options - [ofAllowMultiSelect]; if Execute then begin Edit_Path.Text := FileName; end; end; end; procedure TForm_ScriptButton.Button_CancelClick(Sender: TObject); begin Close; end; procedure TForm_ScriptButton.Button_OKClick(Sender: TObject); var sb: TADScriptButton; begin case FMode of ADC_EDIT_MODE_CREATE: begin with sb do begin Title := Edit_Title.Text; Description := Edit_Description.Text; Path := Edit_Path.Text; Parameters := Edit_Parameters.Text; end; if Assigned(FOnScriptButtonCreate) then FOnScriptButtonCreate(Self, sb); end; ADC_EDIT_MODE_CHANGE: begin if Assigned(FObj) then with FObj^ do begin Title := Edit_Title.Text; Description := Edit_Description.Text; Path := Edit_Path.Text; Parameters := Edit_Parameters.Text; end; if Assigned(FOnScriptButtonChange) then FOnScriptButtonChange(Self, FObj); end; end; Close; end; procedure TForm_ScriptButton.ClearTextFields; var i: Integer; begin for i := 0 to Self.ControlCount - 1 do if Self.Controls[i] is TEdit then TEdit(Self.Controls[i]).Clear; Edit_Parameters.Text := '-dn' end; procedure TForm_ScriptButton.FormClose(Sender: TObject; var Action: TCloseAction); begin ClearTextFields; FMode := ADC_EDIT_MODE_CREATE; FObj := nil; FOnScriptButtonCreate := nil; FOnScriptButtonChange := nil; if FCallingForm <> nil then begin FCallingForm.Enabled := True; FCallingForm.Show; FCallingForm := nil; end; end; procedure TForm_ScriptButton.FormCreate(Sender: TObject); begin ClearTextFields; end; procedure TForm_ScriptButton.SetCallingForm(const Value: TForm); begin FCallingForm := Value; if FCallingForm <> nil then FCallingForm.Enabled := False; end; procedure TForm_ScriptButton.SetMode(const Value: Byte); begin FMode := Value; SetObject(FObj); end; procedure TForm_ScriptButton.SetObject(const Value: PADScriptButton); begin FObj := Value; if FMode = ADC_EDIT_MODE_CREATE then ClearTextFields else begin if Assigned(FObj) then begin Edit_Title.Text := FObj^.Title; Edit_Description.Text := FObj^.Description; Edit_Path.Text := FObj^.Path; Edit_Parameters.Text := FObj^.Parameters; end; end; end; end.
{****************************************************************} { TWebImage component } { for Delphi & C++Builder } { version 1.1 } { } { written by } { TMS Software } { copyright © 2000-2004 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } {****************************************************************} unit WebImgR; interface uses WebImage, Classes; procedure Register; implementation procedure Register; begin RegisterComponents('TMS Web', [TWebImage]); end; end.
{$I ATStreamSearchOptions.inc} unit UFormMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, TntStdCtrls, TntDialogs, ATBinHex, ATStreamSearch; type TFormMain = class(TForm) Panel1: TPanel; Search: TATStreamSearch; OpenDialog1: TTntOpenDialog; GroupBox1: TGroupBox; labFN: TLabel; edFilename: TTntEdit; btnBrowse: TButton; chkOEM: TCheckBox; chkUnicode: TCheckBox; chkUnicodeBE: TCheckBox; GroupBox2: TGroupBox; labString: TLabel; edString: TTntEdit; btnFind: TButton; btnFindNext: TButton; labOptions: TLabel; chkCase: TCheckBox; chkWords: TCheckBox; chkRegex: TCheckBox; chkBack: TCheckBox; Label1: TLabel; GroupBoxViewer: TGroupBox; Viewer: TATBinHex; Panel2: TPanel; Label2: TLabel; edSelection: TTntEdit; Label3: TLabel; edOffset: TTntEdit; Label4: TLabel; edLength: TTntEdit; procedure btnBrowseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnFindClick(Sender: TObject); procedure edStringChange(Sender: TObject); procedure btnFindNextClick(Sender: TObject); procedure chkUnicodeClick(Sender: TObject); procedure SearchProgress(const ACurrentPos, AMaximalPos: Int64; var AContinueSearching: Boolean); procedure chkOEMClick(Sender: TObject); procedure chkRegexClick(Sender: TObject); private { Private declarations } FFileName: WideString; public { Public declarations } procedure Find(AFindFirst: Boolean); end; var FormMain: TFormMain; implementation uses ATxCodepages, UFormProgress; {$R *.DFM} procedure TFormMain.FormCreate(Sender: TObject); begin FFileName := ''; {$IFNDEF REGEX} chkRegex.Checked := False; chkRegex.Enabled := False; chkRegex.Caption := chkRegex.Caption + ' (RegEx library not compiled in)'; {$ENDIF} end; procedure TFormMain.btnBrowseClick(Sender: TObject); begin with OpenDialog1 do if Execute then begin FFileName := FileName; edFilename.Text := FFileName; edStringChange(Self); if Viewer.Open(FFileName) then begin chkUnicodeBE.Checked := Viewer.FileUnicodeFormat = vbUnicodeFmtBE; end else begin WideMessageDlg('Could not open "' + FFileName + '"', mtError, [mbOK], 0); { Application.MessageBox( PChar('Could not open "' + FFileName + '"'), 'Error', MB_OK or MB_ICONERROR); } end; end; end; procedure TFormMain.edStringChange(Sender: TObject); begin btnFind.Enabled := (edString.Text <> '') and (edFilename.Text <> ''); btnFindNext.Enabled := btnFind.Enabled and (Search.FoundStart >= 0); end; procedure TFormMain.Find(AFindFirst: Boolean); var OK: Boolean; Encoding: TATEncoding; Options: TATStreamSearchOptions; begin if AFindFirst then begin Viewer.SetSelection(0, 0, True); edSelection.Text := ''; edOffset.Text := ''; edLength.Text := ''; end; OK := False; try try Self.Enabled := False; FormProgress.Show; if chkUnicode.Checked then begin if chkUnicodeBE.Checked then Encoding := vencUnicodeBE else Encoding := vencUnicodeLE; end else begin if chkOEM.Checked then Encoding := vencOEM else Encoding := vencANSI; end; Options := []; {$IFDEF REGEX} if chkRegex.Checked then Include(Options, asoRegEx); {$ENDIF} if chkCase.Checked then Include(Options, asoCaseSens); if chkWords.Checked then Include(Options, asoWholeWords); if chkBack.Checked then Include(Options, asoBackward); if AFindFirst then begin try Search.FileName := FFileName; except Application.MessageBox('Cannot open filename specified', 'Error', MB_OK or MB_ICONERROR); Exit; end; OK := Search.FindFirst(edString.Text, 0, Encoding, Options); end else begin OK := Search.FindNext; end; finally FormProgress.Hide; Self.Enabled := True; end; except on E: Exception do if E.Message <> '' then begin Application.MessageBox(PChar(E.Message), 'Search failed', MB_OK or MB_ICONERROR); Exit; end; end; if OK then begin Viewer.SetSelection(Search.FoundStart, Search.FoundLength, True); if Viewer.Mode = vbmodeUnicode then edSelection.Text := Viewer.SelTextW else edSelection.Text := Viewer.SelText; edOffset.Text := IntToStr(Search.FoundStart); edLength.Text := IntToStr(Search.FoundLength); end else Application.MessageBox('Search string not found', 'Search failed', MB_OK or MB_ICONERROR); edStringChange(Self); end; procedure TFormMain.btnFindClick(Sender: TObject); begin Find(True); end; procedure TFormMain.btnFindNextClick(Sender: TObject); begin Find(False); end; procedure TFormMain.chkUnicodeClick(Sender: TObject); begin if chkUnicode.Checked then Viewer.Mode := vbmodeUnicode else Viewer.Mode := vbmodeText; chkUnicodeBE.Checked := Viewer.FileUnicodeFormat = vbUnicodeFmtBE; chkOEM.Enabled := not chkUnicode.Checked; edStringChange(Self); end; procedure TFormMain.chkOEMClick(Sender: TObject); begin if chkOEM.Checked then Viewer.TextEncoding := vencOEM else Viewer.TextEncoding := vencANSI; edStringChange(Self); end; procedure TFormMain.SearchProgress(const ACurrentPos, AMaximalPos: Int64; var AContinueSearching: Boolean); begin AContinueSearching := FormProgress.Progress(ACurrentPos, AMaximalPos); end; procedure TFormMain.chkRegexClick(Sender: TObject); begin chkBack.Enabled := not chkRegex.Checked; end; end.
unit pacman_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,namco_snd,controls_engine,gfx_engine,rom_engine, misc_functions,pal_engine,sound_engine,qsnapshot; function iniciar_pacman:boolean; implementation const //Pacman pacman_rom:array[0..3] of tipo_roms=( (n:'pacman.6e';l:$1000;p:0;crc:$c1e6ab10),(n:'pacman.6f';l:$1000;p:$1000;crc:$1a6fb2d4), (n:'pacman.6h';l:$1000;p:$2000;crc:$bcdd1beb),(n:'pacman.6j';l:$1000;p:$3000;crc:$817d94e3)); pacman_pal:array[0..1] of tipo_roms=( (n:'82s123.7f';l:$20;p:0;crc:$2fc650bd),(n:'82s126.4a';l:$100;p:$20;crc:$3eb3a8e4)); pacman_char:tipo_roms=(n:'pacman.5e';l:$1000;p:0;crc:$0c944964); pacman_sound:tipo_roms=(n:'82s126.1m';l:$100;p:0;crc:$a9cc86bf); pacman_sprites:tipo_roms=(n:'pacman.5f';l:$1000;p:0;crc:$958fedf9); //MS-Pacman mspacman_rom:array[0..6] of tipo_roms=( (n:'pacman.6e';l:$1000;p:0;crc:$c1e6ab10),(n:'pacman.6f';l:$1000;p:$1000;crc:$1a6fb2d4), (n:'pacman.6h';l:$1000;p:$2000;crc:$bcdd1beb),(n:'pacman.6j';l:$1000;p:$3000;crc:$817d94e3), (n:'u5';l:$800;p:$8000;crc:$f45fbbcd),(n:'u6';l:$1000;p:$9000;crc:$a90e7000), (n:'u7';l:$1000;p:$b000;crc:$c82cd714)); mspacman_char:tipo_roms=(n:'5e';l:$1000;p:0;crc:$5c281d01); mspacman_sprites:tipo_roms=(n:'5f';l:$1000;p:0;crc:$615af909); //Crush Roller crush_rom:array[0..3] of tipo_roms=( (n:'crushkrl.6e';l:$1000;p:0;crc:$a8dd8f54),(n:'crushkrl.6f';l:$1000;p:$1000;crc:$91387299), (n:'crushkrl.6h';l:$1000;p:$2000;crc:$d4455f27),(n:'crushkrl.6j';l:$1000;p:$3000;crc:$d59fc251)); crush_char:tipo_roms=(n:'maketrax.5e';l:$1000;p:0;crc:$91bad2da); crush_sprites:tipo_roms=(n:'maketrax.5f';l:$1000;p:0;crc:$aea79f55); crush_pal:array[0..1] of tipo_roms=( (n:'82s123.7f';l:$20;p:0;crc:$2fc650bd),(n:'2s140.4a';l:$100;p:$20;crc:$63efb927)); //Ms Pac Man Twin mspactwin_rom:tipo_roms=(n:'m27256.bin';l:$8000;p:0;crc:$77a99184); mspactwin_char:array[0..1] of tipo_roms=( (n:'4__2716.5d';l:$800;p:0;crc:$483c1d1c),(n:'2__2716.5g';l:$800;p:$800;crc:$c08d73a2)); mspactwin_sprites:array[0..1] of tipo_roms=( (n:'3__2516.5f';l:$800;p:$0;crc:$22b0188a),(n:'1__2516.5j';l:$800;p:$800;crc:$0a8c46a0)); mspactwin_pal:array[0..1] of tipo_roms=( (n:'mb7051.8h';l:$20;p:0;crc:$ff344446),(n:'82s129.4a';l:$100;p:$20;crc:$a8202d0d)); //DIP pacman_dip_a:array [0..5] of def_dip=( (mask:$3;name:'Coinage';number:4;dip:((dip_val:$3;dip_name:'2C 1C'),(dip_val:$1;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'1'),(dip_val:$4;dip_name:'2'),(dip_val:$8;dip_name:'3'),(dip_val:$c;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:3;dip:((dip_val:$0;dip_name:'10000'),(dip_val:$10;dip_name:'15000'),(dip_val:$20;dip_name:'20000'),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Difficulty';number:2;dip:((dip_val:$40;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Ghost Names';number:2;dip:((dip_val:$80;dip_name:'Normal'),(dip_val:$0;dip_name:'Alternate'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); pacman_dip_b:array [0..1] of def_dip=( (mask:$10;name:'Rack Test';number:2;dip:((dip_val:$10;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); pacman_dip_c:array [0..1] of def_dip=( (mask:$80;name:'Cabinet';number:2;dip:((dip_val:$80;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); mspacman_dip:array [0..4] of def_dip=( (mask:$3;name:'Coinage';number:4;dip:((dip_val:$3;dip_name:'2C 1C'),(dip_val:$1;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'1'),(dip_val:$4;dip_name:'2'),(dip_val:$8;dip_name:'3'),(dip_val:$c;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'10000'),(dip_val:$10;dip_name:'15000'),(dip_val:$20;dip_name:'20000'),(dip_val:$30;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Difficulty';number:2;dip:((dip_val:$40;dip_name:'Normal'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); crush_dip_a:array [0..4] of def_dip=( (mask:$3;name:'Coinage';number:4;dip:((dip_val:$3;dip_name:'2C 1C'),(dip_val:$1;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'3'),(dip_val:$4;dip_name:'4'),(dip_val:$8;dip_name:'5'),(dip_val:$c;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'First Pattern';number:2;dip:((dip_val:$10;dip_name:'Easy'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Teleport Holes';number:2;dip:((dip_val:$20;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); crush_dip_b:array [0..1] of def_dip=( (mask:$10;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$10;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); mspactwin_dip_a:array [0..3] of def_dip=( (mask:$3;name:'Coinage';number:4;dip:((dip_val:$3;dip_name:'2C 1C'),(dip_val:$1;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(dip_val:$0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'1'),(dip_val:$4;dip_name:'2'),(dip_val:$8;dip_name:'3'),(dip_val:$c;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'10000'),(dip_val:$10;dip_name:'15000'),(dip_val:$20;dip_name:'20000'),(dip_val:$30;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())),()); mspactwin_dip_b:array [0..1] of def_dip=( (mask:$10;name:'Jama';number:2;dip:((dip_val:$10;dip_name:'Slow'),(dip_val:$0;dip_name:'Fast'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); mspactwin_dip_c:array [0..1] of def_dip=( (mask:$80;name:'Skip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var irq_vblank,dec_enable,croller_disable_protection:boolean; rom_decode:array[0..$bfff] of byte; read_events:procedure; croller_counter,croller_offset,unk_latch:byte; procedure update_video_pacman; var color,offs:word; nchar,f,sx,sy,atrib,x,y:byte; flip_x,flip_y:boolean; begin for x:=0 to 27 do begin for y:=0 to 35 do begin sx:=29-x; sy:=y-2; if (sy and $20)<>0 then offs:=sx+((sy and $1f) shl 5) else offs:=sy+(sx shl 5); if gfx[0].buffer[offs] then begin color:=((memoria[$4400+offs]) and $1f) shl 2; put_gfx(x*8,y*8,memoria[$4000+offs],color,1,0); gfx[0].buffer[offs]:=false; end; end; end; actualiza_trozo(0,0,224,288,1,0,0,224,288,2); //sprites pacman posicion $5060 //byte 0 --> x //byte 1 --> y //sprites pacman atributos $4FF0 //byte 0 // bit 0 --> flipy // bit 1 --> flipx // bits 2..7 --> numero char for f:=7 downto 0 do begin atrib:=memoria[$4ff0+(f*2)]; nchar:=atrib shr 2; color:=(memoria[$4ff1+(f*2)] and $1f) shl 2; if main_screen.flip_main_screen then begin x:=memoria[$5060+(f*2)]-32; y:=memoria[$5061+(f*2)]; flip_y:=(atrib and 1)=0; flip_x:=(atrib and 2)=0; end else begin x:=240-memoria[$5060+(f*2)]-1; y:=272-memoria[$5061+(f*2)]; flip_y:=(atrib and 1)<>0; flip_x:=(atrib and 2)<>0; end; put_gfx_sprite_mask(nchar,color,flip_x,flip_y,1,0,$f); if (f<2) then actualiza_gfx_sprite((x-1) and $ff,y,2,1) else actualiza_gfx_sprite(x and $ff,y,2,1) end; actualiza_trozo_final(0,0,224,288,2); end; procedure eventos_pacman; begin if event.arcade then begin //in 0 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); //in 1 if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.but0[0] then begin if (memoria[$180b]<>$01) then begin memoria[$180b]:=$01; memoria[$1ffd]:=$bd; end end else begin if (memoria[$180b]<>$be) then begin memoria[$180b]:=$be; memoria[$1ffd]:=$00; end end; end; end; procedure pacman_principal; var frame:single; f:word; begin init_controls(false,false,false,true); frame:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin z80_0.run(frame); frame:=frame+z80_0.tframes-z80_0.contador; //Si no pinto la pantalla aqui, Ms Pac Man Twin no hace el efecto de la pantalla... //Los timings del Z80 estan bien, supongo que es correcto (parece que no hay daņos colaterales!) if f=95 then update_video_pacman; if ((f=223) and irq_vblank) then z80_0.change_irq(ASSERT_LINE); end; read_events; video_sync; end; end; function pacman_getbyte(direccion:word):byte; begin direccion:=direccion and $7fff; case direccion of 0..$3fff:pacman_getbyte:=memoria[direccion]; $4000..$47ff,$6000..$67ff:pacman_getbyte:=memoria[(direccion and $7ff)+$4000]; $4800..$4bff,$6800..$6bff:pacman_getbyte:=$bf; $4c00..$4fff,$6c00..$6fff:pacman_getbyte:=memoria[(direccion and $3ff)+$4c00]; $5000..$5fff,$7000..$7fff:case (direccion and $ff) of $00..$3f:pacman_getbyte:=marcade.in0 or marcade.dswb; $40..$7f:pacman_getbyte:=marcade.in1 or marcade.dswc; $80..$bf:pacman_getbyte:=marcade.dswa; $c0..$ff:pacman_getbyte:=$0; end; end; end; procedure pacman_putbyte(direccion:word;valor:byte); begin direccion:=direccion and $7fff; case direccion of 0..$3fff:; //ROM $4000..$47ff,$6000..$67ff:if memoria[(direccion and $7ff)+$4000]<>valor then begin memoria[(direccion and $7ff)+$4000]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $4c00..$4fff,$6c00..$6fff:memoria[(direccion and $3ff)+$4c00]:=valor; $5000..$5fff,$7000..$7fff:case (direccion and $ff) of 0:begin irq_vblank:=valor<>0; if not(irq_vblank) then z80_0.change_irq(CLEAR_LINE); end; 1:namco_snd_0.enabled:=valor<>0; 3:main_screen.flip_main_screen:=(valor and 1)<>0; $40..$5f:namco_snd_0.regs[direccion and $1f]:=valor; $60..$6f:memoria[(direccion and $ff)+$5000]:=valor; end; end; end; procedure pacman_outbyte(puerto:word;valor:byte); begin if (puerto and $ff)=0 then z80_0.im2_lo:=valor; end; procedure pacman_sound_update; begin namco_snd_0.update; end; //MS Pacman procedure eventos_mspacman; begin if event.arcade then begin //in 0 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); //in 1 if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.start[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); end; end; function mspacman_getbyte(direccion:word):byte; begin case direccion of $38..$3f,$3b0..$3b7,$1600..$1607,$2120..$2127,$3ff0..$3ff7,$8000..$8007,$97f0..$97f7:dec_enable:=false; $3ff8..$3fff:dec_enable:=true; end; case direccion of $0..$3fff,$8000..$bfff:if dec_enable then mspacman_getbyte:=rom_decode[direccion] else mspacman_getbyte:=memoria[direccion and $3fff]; else mspacman_getbyte:=pacman_getbyte(direccion); end; end; procedure mspacman_putbyte(direccion:word;valor:byte); begin case direccion of $38..$3f,$3b0..$3b7,$1600..$1607,$2120..$2127,$3ff0..$3ff7,$8000..$8007,$97f0..$97f7:dec_enable:=false; $3ff8..$3fff:dec_enable:=true; else pacman_putbyte(direccion,valor); end; end; //Crush Roller function crush_getbyte(direccion:word):byte; const protdata_odd:array[0..$1d] of byte=( // table at $ebd (odd entries) $00, $c0, $00, $40, $c0, $40, $00, $c0, $00, $40, $00, $c0, $00, $40, $c0, $40, $00, $c0, $00, $40, $00, $c0, $00, $40, $c0, $40, $00, $c0, $00, $40); protdata_even:array[0..$1d] of byte=( // table at $ebd (even entries) $1f, $3f, $2f, $2f, $0f, $0f, $0f, $3f, $0f, $0f, $1c, $3c, $2c, $2c, $0c, $0c, $0c, $3c, $0c, $0c, $11, $31, $21, $21, $01, $01, $01, $31, $01, $01); var tempb:byte; begin direccion:=direccion and $7fff; case direccion of $5000..$5fff,$7000..$7fff:case (direccion and $ff) of $00..$3f:crush_getbyte:=marcade.in0+marcade.dswb; $40..$7f:crush_getbyte:=marcade.in1; $80..$bf:begin //proteccion 1 tempb:=marcade.dswa and $3f; if not(croller_disable_protection) then begin crush_getbyte:=protdata_odd[croller_offset] or tempb; exit; end; case (direccion and $3f) of $01,$04:crush_getbyte:=tempb or $40; $05,$0e,$10:crush_getbyte:=tempb or $c0; else crush_getbyte:=tempb; end; end; $c0..$cf:begin //proteccion 2 if not(croller_disable_protection) then begin crush_getbyte:=protdata_even[croller_offset]; exit; end; case (direccion and $f) of $0:crush_getbyte:=$1f; $9:crush_getbyte:=$30; $c:crush_getbyte:=0; else crush_getbyte:=$20; end; end; $d0..$ff:crush_getbyte:=$0; end; else crush_getbyte:=pacman_getbyte(direccion); end; end; procedure crush_putbyte(direccion:word;valor:byte); begin direccion:=direccion and $7fff; case direccion of $5000..$5fff,$7000..$7fff:case (direccion and $ff) of 0:begin irq_vblank:=valor<>0; if not(irq_vblank) then z80_0.change_irq(CLEAR_LINE); end; 1:namco_snd_0.enabled:=valor<>0; 3:main_screen.flip_main_screen:=(valor and 1)<>0; 4:case valor of //proteccion 0:begin // disable protection / reset? croller_counter:=0; croller_offset:=0; croller_disable_protection:=true; end; 1:begin croller_disable_protection:=false; croller_counter:=croller_counter+1; if (croller_counter=$3c) then begin croller_counter:=0; croller_offset:=croller_offset+1; if (croller_offset=$1e) then croller_offset:=0; end; end; end; $40..$5f:namco_snd_0.regs[direccion and $1f]:=valor; $60..$6f:memoria[(direccion and $ff)+$5000]:=valor; end; else pacman_putbyte(direccion,valor); end; end; //Ms Pac Man Twin function mspactwin_getbyte(direccion:word):byte; begin case direccion of $0..$3fff,$8000..$bfff:if z80_0.opcode then mspactwin_getbyte:=rom_decode[direccion] else mspactwin_getbyte:=memoria[direccion]; $6000..$67ff:if z80_0.opcode then mspactwin_getbyte:=rom_decode[(direccion and $1fff)+$2000] else mspactwin_getbyte:=memoria[(direccion and $1fff)+$2000]; $4000..$47ff,$c000..$c7ff:mspactwin_getbyte:=memoria[(direccion and $7ff)+$4000]; $4800..$4bff,$6800..$6bff,$c800..$cbff:mspactwin_getbyte:=0; $4c00..$4fff,$6c00..$6fff,$cc00..$cfff,$ec00..$efff:mspactwin_getbyte:=memoria[(direccion and $3ff)+$4c00]; $5000..$5fff,$7000..$7fff,$d000..$dfff,$f000..$ffff:case (direccion and $ff) of $00..$3f:mspactwin_getbyte:=marcade.in0 or marcade.dswb; $40..$7f:mspactwin_getbyte:=marcade.in1 or marcade.dswc; $80..$bf:mspactwin_getbyte:=marcade.dswa; $c0..$ff:mspactwin_getbyte:=unk_latch; end; end; end; procedure mspactwin_putbyte(direccion:word;valor:byte); begin case direccion of 0..$3fff,$6000..$67ff,$8000..$bfff:; $4000..$47ff,$c000..$c7ff:if memoria[(direccion and $7ff)+$4000]<>valor then begin memoria[(direccion and $7ff)+$4000]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $4c00..$4fff,$6c00..$6fff,$cc00..$cfff,$ec00..$efff:memoria[(direccion and $3ff)+$4c00]:=valor; $5000..$5fff,$7000..$7fff,$d000..$dfff,$f000..$ffff:case (direccion and $ff) of 0:begin irq_vblank:=valor<>0; if not(irq_vblank) then z80_0.change_irq(CLEAR_LINE); end; 1:namco_snd_0.enabled:=valor<>0; 3:main_screen.flip_main_screen:=(valor and 1)<>0; $40..$5f:namco_snd_0.regs[direccion and $1f]:=valor; $60..$6f:memoria[(direccion and $ff)+$5000]:=valor; $80..$bf:unk_latch:=valor; $c0..$ff:; //WD end; end; end; procedure pacman_qsave(nombre:string); var data:pbyte; size:word; buffer:array[0..5] of byte; begin case main_vars.tipo_maquina of 10:open_qsnapshot_save('pacman'+nombre); 88:open_qsnapshot_save('mspacman'+nombre); 234:open_qsnapshot_save('crushroller'+nombre); 305:open_qsnapshot_save('mspactwin'+nombre); end; getmem(data,2000); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=namco_snd_0.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria[$4000],$4000); if main_vars.tipo_maquina=88 then savedata_com_qsnapshot(@memoria[$c000],$4000); //MISC buffer[0]:=byte(irq_vblank); buffer[1]:=byte(dec_enable); buffer[2]:=croller_counter; buffer[3]:=croller_offset; buffer[4]:=byte(croller_disable_protection); buffer[5]:=unk_latch; savedata_qsnapshot(@buffer,6); freemem(data); close_qsnapshot; end; procedure pacman_qload(nombre:string); var data:pbyte; buffer:array[0..5] of byte; begin case main_vars.tipo_maquina of 10:if not(open_qsnapshot_load('pacman'+nombre)) then exit; 88:if not(open_qsnapshot_load('mspacman'+nombre)) then exit; 234:if not(open_qsnapshot_load('crushroller'+nombre)) then exit; 305:if not(open_qsnapshot_load('mspactwin'+nombre)) then exit; end; getmem(data,2000); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND loaddata_qsnapshot(data); namco_snd_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria[$4000]); if main_vars.tipo_maquina=88 then loaddata_qsnapshot(@memoria[$c000]); //MISC loaddata_qsnapshot(@buffer); irq_vblank:=buffer[0]<>0; dec_enable:=buffer[1]<>0; croller_counter:=buffer[2]; croller_offset:=buffer[3]; croller_disable_protection:=buffer[4]<>0; unk_latch:=buffer[5]; freemem(data); close_qsnapshot; fillchar(gfx[0].buffer,$400,1); end; //Main procedure reset_pacman; begin z80_0.reset; namco_snd_0.reset; reset_audio; irq_vblank:=false; dec_enable:=false; marcade.in0:=$ef; marcade.in1:=$7f; croller_counter:=0; croller_offset:=0; croller_disable_protection:=false; unk_latch:=0; end; procedure mspacman_install_patches; var i:byte; begin // copy forty 8-byte patches into Pac-Man code for i:=0 to 7 do begin rom_decode[$0410+i]:=rom_decode[$8008+i]; rom_decode[$08E0+i]:=rom_decode[$81D8+i]; rom_decode[$0A30+i]:=rom_decode[$8118+i]; rom_decode[$0BD0+i]:=rom_decode[$80D8+i]; rom_decode[$0C20+i]:=rom_decode[$8120+i]; rom_decode[$0E58+i]:=rom_decode[$8168+i]; rom_decode[$0EA8+i]:=rom_decode[$8198+i]; rom_decode[$1000+i]:=rom_decode[$8020+i]; rom_decode[$1008+i]:=rom_decode[$8010+i]; rom_decode[$1288+i]:=rom_decode[$8098+i]; rom_decode[$1348+i]:=rom_decode[$8048+i]; rom_decode[$1688+i]:=rom_decode[$8088+i]; rom_decode[$16B0+i]:=rom_decode[$8188+i]; rom_decode[$16D8+i]:=rom_decode[$80C8+i]; rom_decode[$16F8+i]:=rom_decode[$81C8+i]; rom_decode[$19A8+i]:=rom_decode[$80A8+i]; rom_decode[$19B8+i]:=rom_decode[$81A8+i]; rom_decode[$2060+i]:=rom_decode[$8148+i]; rom_decode[$2108+i]:=rom_decode[$8018+i]; rom_decode[$21A0+i]:=rom_decode[$81A0+i]; rom_decode[$2298+i]:=rom_decode[$80A0+i]; rom_decode[$23E0+i]:=rom_decode[$80E8+i]; rom_decode[$2418+i]:=rom_decode[$8000+i]; rom_decode[$2448+i]:=rom_decode[$8058+i]; rom_decode[$2470+i]:=rom_decode[$8140+i]; rom_decode[$2488+i]:=rom_decode[$8080+i]; rom_decode[$24B0+i]:=rom_decode[$8180+i]; rom_decode[$24D8+i]:=rom_decode[$80C0+i]; rom_decode[$24F8+i]:=rom_decode[$81C0+i]; rom_decode[$2748+i]:=rom_decode[$8050+i]; rom_decode[$2780+i]:=rom_decode[$8090+i]; rom_decode[$27B8+i]:=rom_decode[$8190+i]; rom_decode[$2800+i]:=rom_decode[$8028+i]; rom_decode[$2B20+i]:=rom_decode[$8100+i]; rom_decode[$2B30+i]:=rom_decode[$8110+i]; rom_decode[$2BF0+i]:=rom_decode[$81D0+i]; rom_decode[$2CC0+i]:=rom_decode[$80D0+i]; rom_decode[$2CD8+i]:=rom_decode[$80E0+i]; rom_decode[$2CF0+i]:=rom_decode[$81E0+i]; rom_decode[$2D60+i]:=rom_decode[$8160+i]; end; end; function iniciar_pacman:boolean; var colores:tpaleta; f:word; bit0,bit1,bit2:byte; memoria_temp:array[0..$7fff] of byte; rweights,gweights,bweights:array[0..2] of single; const ps_x:array[0..15] of dword=(8*8, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3, 0, 1, 2, 3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8); pc_x:array[0..7] of dword=(8*8+0, 8*8+1, 8*8+2, 8*8+3, 0, 1, 2, 3); resistances:array[0..2] of integer=(1000,470,220); procedure conv_chars; begin init_gfx(0,8,8,256); gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(0,0,@memoria_temp,@pc_x,@ps_y,true,false); end; procedure conv_sprites; begin init_gfx(1,16,16,64); gfx_set_desc_data(2,0,64*8,0,4); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,true,false); end; begin llamadas_maquina.bucle_general:=pacman_principal; llamadas_maquina.reset:=reset_pacman; llamadas_maquina.fps_max:=60.6060606060; llamadas_maquina.save_qsnap:=pacman_qsave; llamadas_maquina.load_qsnap:=pacman_qload; iniciar_pacman:=false; iniciar_audio(false); screen_init(1,224,288); screen_init(2,256,512,false,true); iniciar_video(224,288); //Main CPU z80_0:=cpu_z80.create(3072000,264); z80_0.change_io_calls(nil,pacman_outbyte); z80_0.init_sound(pacman_sound_update); namco_snd_0:=namco_snd_chip.create(3); case main_vars.tipo_maquina of 10:begin //Pacman z80_0.change_ram_calls(pacman_getbyte,pacman_putbyte); //cargar roms if not(roms_load(@memoria,pacman_rom)) then exit; //cargar sonido & iniciar_sonido if not(roms_load(namco_snd_0.get_wave_dir,pacman_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,pacman_char)) then exit; conv_chars; //convertir sprites if not(roms_load(@memoria_temp,pacman_sprites)) then exit; conv_sprites; //poner la paleta if not(roms_load(@memoria_temp,pacman_pal)) then exit; //DIP read_events:=eventos_pacman; marcade.dswa:=$c9; marcade.dswb:=$10; marcade.dswc:=$80; marcade.dswa_val:=@pacman_dip_a; marcade.dswb_val:=@pacman_dip_b; marcade.dswc_val:=@pacman_dip_c; end; 88:begin //MS Pacman z80_0.change_ram_calls(mspacman_getbyte,mspacman_putbyte); //cargar y desencriptar roms if not(roms_load(@memoria,mspacman_rom)) then exit; copymemory(@rom_decode,@memoria,$1000); // pacman.6e copymemory(@rom_decode[$1000],@memoria[$1000],$1000); // pacman.6f copymemory(@rom_decode[$2000],@memoria[$2000],$1000); // pacman.6h for f:=0 to $fff do rom_decode[$3000+f]:=BITSWAP8(memoria[$b000+BITSWAP16(f,15,14,13,12,11,3,7,9,10,8,6,5,4,2,1,0)],0,4,5,7,6,3,2,1); // decrypt u7 */ for f:=0 to $7ff do begin rom_decode[$8000+f]:=BITSWAP8(memoria[$8000+BITSWAP16(f,15,14,13,12,11,8,7,5,9,10,6,3,4,2,1,0)],0,4,5,7,6,3,2,1); // decrypt u5 */ rom_decode[$8800+f]:=BITSWAP8(memoria[$9800+BITSWAP16(f,15,14,13,12,11,3,7,9,10,8,6,5,4,2,1,0)],0,4,5,7,6,3,2,1); // decrypt half of u6 */ rom_decode[$9000+f]:=BITSWAP8(memoria[$9000+BITSWAP16(f,15,14,13,12,11,3,7,9,10,8,6,5,4,2,1,0)],0,4,5,7,6,3,2,1); // decrypt half of u6 */ end; copymemory(@rom_decode[$9800],@memoria[$1800],$800); // mirror of pacman.6f high copymemory(@rom_decode[$a000],@memoria[$2000],$1000); // mirror of pacman.6h copymemory(@rom_decode[$b000],@memoria[$3000],$1000); // mirror of pacman.6j mspacman_install_patches; //cargar sonido & iniciar_sonido if not(roms_load(namco_snd_0.get_wave_dir,pacman_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,mspacman_char)) then exit; conv_chars; //convertir sprites if not(roms_load(@memoria_temp,mspacman_sprites)) then exit; conv_sprites; //poner la paleta if not(roms_load(@memoria_temp,pacman_pal)) then exit; //DIP read_events:=eventos_mspacman; marcade.dswa:=$c9; marcade.dswb:=$10; marcade.dswc:=$80; marcade.dswa_val:=@mspacman_dip; marcade.dswb_val:=@pacman_dip_b; marcade.dswc_val:=@pacman_dip_c; end; 234:begin //Crush Roller z80_0.change_ram_calls(crush_getbyte,crush_putbyte); //cargar roms if not(roms_load(@memoria,crush_rom)) then exit; //cargar sonido & iniciar_sonido if not(roms_load(namco_snd_0.get_wave_dir,pacman_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,crush_char)) then exit; conv_chars; //convertir sprites if not(roms_load(@memoria_temp,crush_sprites)) then exit; conv_sprites; //poner la paleta if not(roms_load(@memoria_temp,crush_pal)) then exit; //DIP read_events:=eventos_mspacman; marcade.dswa:=$31; marcade.dswb:=$0; marcade.dswa_val:=@crush_dip_a; marcade.dswb_val:=@crush_dip_b; end; 305:begin //MS Pacman Twin z80_0.change_ram_calls(mspactwin_getbyte,mspactwin_putbyte); //cargar y desencriptar roms if not(roms_load(@memoria_temp,mspactwin_rom)) then exit; copymemory(@memoria,@memoria_temp,$4000); copymemory(@memoria[$8000],@memoria_temp[$4000],$4000); for f:=0 to $1fff do begin // decode opcode rom_decode[f*2]:=BITSWAP8(memoria[f*2],4,5,6,7,0,1,2,3); rom_decode[(f*2)+1]:=BITSWAP8(memoria[(f*2)+1] xor $9a,6,4,5,7,2,0,3,1); rom_decode[$8000+(f*2)]:=BITSWAP8(memoria[$8000+(f*2)],4,5,6,7,0,1,2,3); rom_decode[$8001+(f*2)]:=BITSWAP8(memoria[$8001+(f*2)] xor $9a,6,4,5,7,2,0,3,1); // decode operand memoria[f*2]:=BITSWAP8(memoria[f*2],0,1,2,3,4,5,6,7); memoria[(f*2)+1]:=BITSWAP8(memoria[(f*2)+1] xor $a3,2,4,6,3,7,0,5,1); memoria[$8000+(f*2)]:=BITSWAP8(memoria[$8000+(f*2)],0,1,2,3,4,5,6,7); memoria[$8001+(f*2)]:=BITSWAP8(memoria[$8001+(f*2)] xor $a3,2,4,6,3,7,0,5,1); end; //cargar sonido & iniciar_sonido if not(roms_load(namco_snd_0.get_wave_dir,pacman_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,mspactwin_char)) then exit; conv_chars; //convertir sprites if not(roms_load(@memoria_temp,mspactwin_sprites)) then exit; conv_sprites; //poner la paleta if not(roms_load(@memoria_temp,mspactwin_pal)) then exit; //DIP read_events:=eventos_mspacman; marcade.dswa:=$c9; marcade.dswa_val:=@mspactwin_dip_a; marcade.dswb:=$10; marcade.dswb_val:=@mspactwin_dip_b; marcade.dswc:=$80; marcade.dswc_val:=@mspactwin_dip_c; end; end; compute_resistor_weights(0, 255, -1.0, 3,@resistances,@rweights,0,0, 3,@resistances,@gweights,0,0, 2,@resistances[1],@bweights,0,0); for f:=0 to $1f do begin // red component bit0:=(memoria_temp[f] shr 0) and $01; bit1:=(memoria_temp[f] shr 1) and $01; bit2:=(memoria_temp[f] shr 2) and $01; colores[f].r:=combine_3_weights(@rweights, bit0, bit1, bit2); // green component bit0:=(memoria_temp[f] shr 3) and $01; bit1:=(memoria_temp[f] shr 4) and $01; bit2:=(memoria_temp[f] shr 5) and $01; colores[f].g:=combine_3_weights(@gweights, bit0, bit1, bit2); // blue component bit0:=(memoria_temp[f] shr 6) and $01; bit1:=(memoria_temp[f] shr 7) and $01; colores[f].b:=combine_2_weights(@bweights, bit0, bit1); end; set_pal(colores,$20); for f:=0 to 255 do begin gfx[0].colores[f]:=memoria_temp[$20+f] and $f; gfx[1].colores[f]:=memoria_temp[$20+f] and $f; end; //final reset_pacman; iniciar_pacman:=true; end; end.
unit DW.VOIP.iOS; {*******************************************************} { } { Kastri } { } { Delphi Worlds Cross-Platform Library } { } { Copyright 2020-2021 Dave Nottage under MIT license } { which is located in the root folder of this library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // macOS Macapi.ObjectiveC, // iOS iOSapi.Foundation, iOSapi.AVFoundation, // DW DW.iOSapi.CallKit, DW.VOIP; type TPlatformVOIP = class; TCXProviderDelegate = class(TOCLocal, CXProviderDelegate) private FVOIP: TPlatformVOIP; public { CXProviderDelegate } [MethodName('provider:didActivateAudioSession:')] procedure providerDidActivateAudioSession(provider: CXProvider; audioSession: AVAudioSession); cdecl; procedure providerDidBegin(provider: CXProvider); cdecl; [MethodName('provider:didDeactivateAudioSession:')] procedure providerDidDeactivateAudioSession(provider: CXProvider; audioSession: AVAudioSession); cdecl; procedure providerDidReset(provider: CXProvider); cdecl; [MethodName('provider:executeTransaction:')] function providerExecuteTransaction(provider: CXProvider; transaction: CXTransaction): Boolean; cdecl; [MethodName('provider:performAnswerCallAction:')] procedure providerPerformAnswerCallAction(provider: CXProvider; action: CXAnswerCallAction); cdecl; [MethodName('provider:performEndCallAction:')] procedure providerPerformEndCallAction(provider: CXProvider; action: CXEndCallAction); cdecl; [MethodName('provider:performPlayDTMFCallAction:')] procedure providerPerformPlayDTMFCallAction(provider: CXProvider; action: CXPlayDTMFCallAction); cdecl; [MethodName('provider:performSetGroupCallAction:')] procedure providerPerformSetGroupCallAction(provider: CXProvider; action: CXSetGroupCallAction); cdecl; [MethodName('provider:performSetHeldCallAction:')] procedure providerPerformSetHeldCallAction(provider: CXProvider; action: CXSetHeldCallAction); cdecl; [MethodName('provider:performSetMutedCallAction:')] procedure providerPerformSetMutedCallAction(provider: CXProvider; action: CXSetMutedCallAction); cdecl; [MethodName('provider:performStartCallAction:')] procedure providerPerformStartCallAction(provider: CXProvider; action: CXStartCallAction); cdecl; [MethodName('provider:timedOutPerformingAction:')] procedure providerTimedOutPerformingAction(provider: CXProvider; action: CXAction); cdecl; public constructor Create(const AVOIP: TPlatformVOIP); end; TPlatformVOIP = class(TCustomPlatformVOIP) private FController: CXCallController; FIncomingUUID: NSUUID; FIsCalling: Boolean; FProvider: CXProvider; FProviderDelegate: TCXProviderDelegate; procedure IncomingCallCompletionHandler(error: NSError); procedure RequestStartCallTransactionCompletionHandler(error: NSError); procedure UpdateProvider; protected procedure IconUpdated; override; procedure PerformAnswerCallAction(const action: CXAnswerCallAction); procedure PerformEndCallAction(const action: CXEndCallAction); procedure ReportIncomingCall(const AIdent, ADisplayName: string); override; procedure ReportOutgoingCall; override; procedure StartCall(const ADisplayName: string); procedure VOIPCallState(const ACallState: TVOIPCallState; const AIdent: string); public constructor Create(const AVOIP: TVOIP); destructor Destroy; override; end; implementation uses DW.OSLog, System.Classes, Macapi.Helpers, iOSapi.UIKit, FMX.Helpers.iOS; { TCXProviderDelegate } constructor TCXProviderDelegate.Create(const AVOIP: TPlatformVOIP); begin inherited Create; FVOIP := AVOIP; end; procedure TCXProviderDelegate.providerDidActivateAudioSession(provider: CXProvider; audioSession: AVAudioSession); begin TOSLog.d('TCXProviderDelegate.providerDidActivateAudioSession'); end; procedure TCXProviderDelegate.providerDidBegin(provider: CXProvider); begin TOSLog.d('TCXProviderDelegate.providerDidBegin'); end; procedure TCXProviderDelegate.providerDidDeactivateAudioSession(provider: CXProvider; audioSession: AVAudioSession); begin TOSLog.d('TCXProviderDelegate.providerDidDeactivateAudioSession'); end; procedure TCXProviderDelegate.providerDidReset(provider: CXProvider); begin TOSLog.d('TCXProviderDelegate.providerDidReset'); end; function TCXProviderDelegate.providerExecuteTransaction(provider: CXProvider; transaction: CXTransaction): Boolean; begin TOSLog.d('TCXProviderDelegate.providerExecuteTransaction'); Result := False; end; procedure TCXProviderDelegate.providerPerformAnswerCallAction(provider: CXProvider; action: CXAnswerCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformAnswerCallAction'); // Called if the call is answered FVOIP.PerformAnswerCallAction(action); end; procedure TCXProviderDelegate.providerPerformEndCallAction(provider: CXProvider; action: CXEndCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformEndCallAction'); // Called if the call is ended or declined FVOIP.PerformEndCallAction(action); end; procedure TCXProviderDelegate.providerPerformPlayDTMFCallAction(provider: CXProvider; action: CXPlayDTMFCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformPlayDTMFCallAction'); end; procedure TCXProviderDelegate.providerPerformSetGroupCallAction(provider: CXProvider; action: CXSetGroupCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformSetGroupCallAction'); end; procedure TCXProviderDelegate.providerPerformSetHeldCallAction(provider: CXProvider; action: CXSetHeldCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformSetHeldCallAction'); end; procedure TCXProviderDelegate.providerPerformSetMutedCallAction(provider: CXProvider; action: CXSetMutedCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformSetMutedCallAction'); end; procedure TCXProviderDelegate.providerPerformStartCallAction(provider: CXProvider; action: CXStartCallAction); begin TOSLog.d('TCXProviderDelegate.providerPerformStartCallAction'); end; procedure TCXProviderDelegate.providerTimedOutPerformingAction(provider: CXProvider; action: CXAction); begin TOSLog.d('TCXProviderDelegate.providerTimedOutPerformingAction'); end; { TPlatformVOIP } constructor TPlatformVOIP.Create(const AVOIP: TVOIP); begin inherited; FProviderDelegate := TCXProviderDelegate.Create(Self); FController := TCXCallController.Create; UpdateProvider; end; destructor TPlatformVOIP.Destroy; begin FProviderDelegate.Free; inherited; end; procedure TPlatformVOIP.UpdateProvider; var LConfiguration: CXProviderConfiguration; LData: NSData; begin LConfiguration := TCXProviderConfiguration.Create; LConfiguration := TCXProviderConfiguration.Wrap(LConfiguration.initWithLocalizedName(StrToNSStr('VOIPDemo'))); // TMacHelperEx.GetBundleValueNS('CFBundleDisplayName') if not Icon.IsEmpty then begin LData := TNSData.Wrap(UIImagePNGRepresentation(NSObjectToID(BitmapToUIImage(Icon)))); LConfiguration.setIconTemplateImageData(LData); // 120 x 120 transparent PNG end; // LConfiguration.setRingtoneSound // LConfiguration.setSupportsVideo(True); // Default False ? // LConfiguration.setIncludeCallsInRecents(False); // Default True ? iOS 11 and above if FProvider = nil then begin FProvider := TCXProvider.Create; FProvider := TCXProvider.Wrap(FProvider.initWithConfiguration(LConfiguration)); FProvider.setDelegate(FProviderDelegate.GetObjectID, 0); end else FProvider.setConfiguration(LConfiguration); end; procedure TPlatformVOIP.IconUpdated; begin UpdateProvider; end; procedure TPlatformVOIP.IncomingCallCompletionHandler(error: NSError); begin TOSLog.d('TPlatformVOIP.IncomingCallCompletionHandler'); if error <> nil then begin TOSLog.d('> error is nil'); if FIncomingUUID <> nil then VOIPCallState(TVOIPCallState.IncomingCall, NSStrToStr(FIncomingUUID.UUIDString)); //!!!!! else something is wrong end else TOSLog.d('> error: %s', [NSStrToStr(error.localizedDescription)]); end; procedure TPlatformVOIP.PerformAnswerCallAction(const action: CXAnswerCallAction); begin FIsCalling := False; action.fulfill; VOIPCallState(TVOIPCallState.CallAnswered, NSStrToStr(action.callUUID.UUIDString)); end; procedure TPlatformVOIP.PerformEndCallAction(const action: CXEndCallAction); var LState: TVOIPCallState; begin action.fulfill; if FIsCalling then LState := TVOIPCallState.CallDeclined else LState := TVOIPCallState.CallDisconnected; VOIPCallState(LState, NSStrToStr(action.callUUID.UUIDString)); end; procedure TPlatformVOIP.ReportIncomingCall(const AIdent, ADisplayName: string); var LUpdate: CXCallUpdate; LHandle: CXHandle; begin TOSLog.d('+TPlatformVOIP.ReportIncomingCall'); if TThread.CurrentThread.ThreadID = MainThreadID then TOSLog.d('> On main thread') else TOSLog.d('> Not on main thread'); FIncomingUUID := nil; FIncomingUUID := TNSUUID.Wrap(TNSUUID.OCClass.UUID); LHandle := TCXHandle.Create; LHandle := TCXHandle.Wrap(LHandle.initWithType(CXHandleTypeEmailAddress, StrToNSStr(AIdent))); LUpdate := TCXCallUpdate.Create; // LUpdate.setHasVideo(True); // for video LUpdate.setRemoteHandle(LHandle); LUpdate.setLocalizedCallerName(StrToNSStr(ADisplayName)); TOSLog.d('> reportNewIncomingCallWithUUID: %s', [NSStrToStr(FIncomingUUID.UUIDString)]); FProvider.reportNewIncomingCallWithUUID(FIncomingUUID, LUpdate, IncomingCallCompletionHandler); TOSLog.d('-TPlatformVOIP.ReportIncomingCall'); end; procedure TPlatformVOIP.RequestStartCallTransactionCompletionHandler(error: NSError); begin FIsCalling := error = nil; end; procedure TPlatformVOIP.StartCall(const ADisplayName: string); var LHandle: CXHandle; LUUID: NSUUID; LTransaction: CXTransaction; LAction: CXStartCallAction; begin LUUID := TNSUUID.Wrap(TNSUUID.OCClass.UUID); LHandle := TCXHandle.Create; LHandle := TCXHandle.Wrap(LHandle.initWithType(CXHandleTypeGeneric, StrToNSStr(ADisplayName))); LAction := TCXStartCallAction.Create; LAction := TCXStartCallAction.Wrap(LAction.initWithCallUUID(LUUID, LHandle)); LTransaction := TCXTransaction.Create; LTransaction := TCXTransaction.Wrap(LTransaction.initWithAction(LAction)); FController.requestTransaction(LTransaction, RequestStartCallTransactionCompletionHandler); end; procedure TPlatformVOIP.VOIPCallState(const ACallState: TVOIPCallState; const AIdent: string); begin DoVOIPCallState(ACallState, AIdent); end; procedure TPlatformVOIP.ReportOutgoingCall; var LUUID: NSUUID; begin // This tells iOS that the call is considered as being connected, and the in-call timer starts LUUID := TCXCall.Wrap(FController.callObserver.calls.objectAtIndex(0)).UUID; FProvider.reportOutgoingCallWithUUIDConnectedAtDate(LUUID, nil); // nil NSDate means now end; end.
unit DictionKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Diction } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Diction\Forms\DictionKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "DictionKeywordsPack" MUID: (4A9CEA5001CF_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , Diction_Form , tfwPropertyLike , vtPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo {$If Defined(Nemesis)} , nscContextFilter {$IfEnd} // Defined(Nemesis) , nscTreeViewWithAdapterDragDrop , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4A9CEA5001CF_Packimpl_uses* //#UC END# *4A9CEA5001CF_Packimpl_uses* ; type TkwEnDictionBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TenDiction.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aenDiction: TenDiction): TvtPanel; {* Реализация слова скрипта .TenDiction.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDictionBackgroundPanel TkwEnDictionContextFilter = {final} class(TtfwPropertyLike) {* Слово скрипта .TenDiction.ContextFilter } private function ContextFilter(const aCtx: TtfwContext; aenDiction: TenDiction): TnscContextFilter; {* Реализация слова скрипта .TenDiction.ContextFilter } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDictionContextFilter TkwEnDictionWordsTree = {final} class(TtfwPropertyLike) {* Слово скрипта .TenDiction.WordsTree } private function WordsTree(const aCtx: TtfwContext; aenDiction: TenDiction): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .TenDiction.WordsTree } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDictionWordsTree Tkw_Form_Diction = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Diction ---- *Пример использования*: [code]форма::Diction TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Diction Tkw_Diction_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Diction_Control_BackgroundPanel Tkw_Diction_Control_BackgroundPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Diction_Control_BackgroundPanel_Push Tkw_Diction_Control_ContextFilter = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ContextFilter ---- *Пример использования*: [code]контрол::ContextFilter TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Diction_Control_ContextFilter Tkw_Diction_Control_ContextFilter_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ContextFilter ---- *Пример использования*: [code]контрол::ContextFilter:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Diction_Control_ContextFilter_Push Tkw_Diction_Control_WordsTree = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола WordsTree ---- *Пример использования*: [code]контрол::WordsTree TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Diction_Control_WordsTree Tkw_Diction_Control_WordsTree_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола WordsTree ---- *Пример использования*: [code]контрол::WordsTree:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Diction_Control_WordsTree_Push function TkwEnDictionBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aenDiction: TenDiction): TvtPanel; {* Реализация слова скрипта .TenDiction.BackgroundPanel } begin Result := aenDiction.BackgroundPanel; end;//TkwEnDictionBackgroundPanel.BackgroundPanel class function TkwEnDictionBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TenDiction.BackgroundPanel'; end;//TkwEnDictionBackgroundPanel.GetWordNameForRegister function TkwEnDictionBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnDictionBackgroundPanel.GetResultTypeInfo function TkwEnDictionBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDictionBackgroundPanel.GetAllParamsCount function TkwEnDictionBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenDiction)]); end;//TkwEnDictionBackgroundPanel.ParamsTypes procedure TkwEnDictionBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEnDictionBackgroundPanel.SetValuePrim procedure TkwEnDictionBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aenDiction: TenDiction; begin try l_aenDiction := TenDiction(aCtx.rEngine.PopObjAs(TenDiction)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenDiction: TenDiction : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aenDiction)); end;//TkwEnDictionBackgroundPanel.DoDoIt function TkwEnDictionContextFilter.ContextFilter(const aCtx: TtfwContext; aenDiction: TenDiction): TnscContextFilter; {* Реализация слова скрипта .TenDiction.ContextFilter } begin Result := aenDiction.ContextFilter; end;//TkwEnDictionContextFilter.ContextFilter class function TkwEnDictionContextFilter.GetWordNameForRegister: AnsiString; begin Result := '.TenDiction.ContextFilter'; end;//TkwEnDictionContextFilter.GetWordNameForRegister function TkwEnDictionContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscContextFilter); end;//TkwEnDictionContextFilter.GetResultTypeInfo function TkwEnDictionContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDictionContextFilter.GetAllParamsCount function TkwEnDictionContextFilter.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenDiction)]); end;//TkwEnDictionContextFilter.ParamsTypes procedure TkwEnDictionContextFilter.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx); end;//TkwEnDictionContextFilter.SetValuePrim procedure TkwEnDictionContextFilter.DoDoIt(const aCtx: TtfwContext); var l_aenDiction: TenDiction; begin try l_aenDiction := TenDiction(aCtx.rEngine.PopObjAs(TenDiction)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenDiction: TenDiction : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aenDiction)); end;//TkwEnDictionContextFilter.DoDoIt function TkwEnDictionWordsTree.WordsTree(const aCtx: TtfwContext; aenDiction: TenDiction): TnscTreeViewWithAdapterDragDrop; {* Реализация слова скрипта .TenDiction.WordsTree } begin Result := aenDiction.WordsTree; end;//TkwEnDictionWordsTree.WordsTree class function TkwEnDictionWordsTree.GetWordNameForRegister: AnsiString; begin Result := '.TenDiction.WordsTree'; end;//TkwEnDictionWordsTree.GetWordNameForRegister function TkwEnDictionWordsTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscTreeViewWithAdapterDragDrop); end;//TkwEnDictionWordsTree.GetResultTypeInfo function TkwEnDictionWordsTree.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDictionWordsTree.GetAllParamsCount function TkwEnDictionWordsTree.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TenDiction)]); end;//TkwEnDictionWordsTree.ParamsTypes procedure TkwEnDictionWordsTree.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству WordsTree', aCtx); end;//TkwEnDictionWordsTree.SetValuePrim procedure TkwEnDictionWordsTree.DoDoIt(const aCtx: TtfwContext); var l_aenDiction: TenDiction; begin try l_aenDiction := TenDiction(aCtx.rEngine.PopObjAs(TenDiction)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aenDiction: TenDiction : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(WordsTree(aCtx, l_aenDiction)); end;//TkwEnDictionWordsTree.DoDoIt function Tkw_Form_Diction.GetString: AnsiString; begin Result := 'enDiction'; end;//Tkw_Form_Diction.GetString class procedure Tkw_Form_Diction.RegisterInEngine; begin inherited; TtfwClassRef.Register(TenDiction); end;//Tkw_Form_Diction.RegisterInEngine class function Tkw_Form_Diction.GetWordNameForRegister: AnsiString; begin Result := 'форма::Diction'; end;//Tkw_Form_Diction.GetWordNameForRegister function Tkw_Diction_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_Diction_Control_BackgroundPanel.GetString class procedure Tkw_Diction_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_Diction_Control_BackgroundPanel.RegisterInEngine class function Tkw_Diction_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_Diction_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_Diction_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_Diction_Control_BackgroundPanel_Push.DoDoIt class function Tkw_Diction_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_Diction_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_Diction_Control_ContextFilter.GetString: AnsiString; begin Result := 'ContextFilter'; end;//Tkw_Diction_Control_ContextFilter.GetString class procedure Tkw_Diction_Control_ContextFilter.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscContextFilter); end;//Tkw_Diction_Control_ContextFilter.RegisterInEngine class function Tkw_Diction_Control_ContextFilter.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter'; end;//Tkw_Diction_Control_ContextFilter.GetWordNameForRegister procedure Tkw_Diction_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ContextFilter'); inherited; end;//Tkw_Diction_Control_ContextFilter_Push.DoDoIt class function Tkw_Diction_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter:push'; end;//Tkw_Diction_Control_ContextFilter_Push.GetWordNameForRegister function Tkw_Diction_Control_WordsTree.GetString: AnsiString; begin Result := 'WordsTree'; end;//Tkw_Diction_Control_WordsTree.GetString class procedure Tkw_Diction_Control_WordsTree.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop); end;//Tkw_Diction_Control_WordsTree.RegisterInEngine class function Tkw_Diction_Control_WordsTree.GetWordNameForRegister: AnsiString; begin Result := 'контрол::WordsTree'; end;//Tkw_Diction_Control_WordsTree.GetWordNameForRegister procedure Tkw_Diction_Control_WordsTree_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('WordsTree'); inherited; end;//Tkw_Diction_Control_WordsTree_Push.DoDoIt class function Tkw_Diction_Control_WordsTree_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::WordsTree:push'; end;//Tkw_Diction_Control_WordsTree_Push.GetWordNameForRegister initialization TkwEnDictionBackgroundPanel.RegisterInEngine; {* Регистрация enDiction_BackgroundPanel } TkwEnDictionContextFilter.RegisterInEngine; {* Регистрация enDiction_ContextFilter } TkwEnDictionWordsTree.RegisterInEngine; {* Регистрация enDiction_WordsTree } Tkw_Form_Diction.RegisterInEngine; {* Регистрация Tkw_Form_Diction } Tkw_Diction_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_Diction_Control_BackgroundPanel } Tkw_Diction_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_Diction_Control_BackgroundPanel_Push } Tkw_Diction_Control_ContextFilter.RegisterInEngine; {* Регистрация Tkw_Diction_Control_ContextFilter } Tkw_Diction_Control_ContextFilter_Push.RegisterInEngine; {* Регистрация Tkw_Diction_Control_ContextFilter_Push } Tkw_Diction_Control_WordsTree.RegisterInEngine; {* Регистрация Tkw_Diction_Control_WordsTree } Tkw_Diction_Control_WordsTree_Push.RegisterInEngine; {* Регистрация Tkw_Diction_Control_WordsTree_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TenDiction)); {* Регистрация типа TenDiction } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter)); {* Регистрация типа TnscContextFilter } {$IfEnd} // Defined(Nemesis) TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop)); {* Регистрация типа TnscTreeViewWithAdapterDragDrop } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit speedrumbler_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,nz80,ym_2203,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,sound_engine; function iniciar_speedr:boolean; implementation const speedr_rom:array[0..7] of tipo_roms=( (n:'rc04.14e';l:$8000;p:$0;crc:$a68ce89c),(n:'rc03.13e';l:$8000;p:$8000;crc:$87bda812), (n:'rc02.12e';l:$8000;p:$10000;crc:$d8609cca),(n:'rc01.11e';l:$8000;p:$18000;crc:$27ec4776), (n:'rc09.14f';l:$8000;p:$20000;crc:$2146101d),(n:'rc08.13f';l:$8000;p:$28000;crc:$838369a6), (n:'rc07.12f';l:$8000;p:$30000;crc:$de785076),(n:'rc06.11f';l:$8000;p:$38000;crc:$a70f4fd4)); speedr_sound:tipo_roms=(n:'rc05.2f';l:$8000;p:0;crc:$0177cebe); speedr_char:tipo_roms=(n:'rc10.6g';l:$4000;p:0;crc:$adabe271); speedr_tiles:array[0..7] of tipo_roms=( (n:'rc11.11a';l:$8000;p:$0;crc:$5fa042ba),(n:'rc12.13a';l:$8000;p:$8000;crc:$a2db64af), (n:'rc13.14a';l:$8000;p:$10000;crc:$f1df5499),(n:'rc14.15a';l:$8000;p:$18000;crc:$b22b31b3), (n:'rc15.11c';l:$8000;p:$20000;crc:$ca3a3af3),(n:'rc16.13c';l:$8000;p:$28000;crc:$c49a4a11), (n:'rc17.14c';l:$8000;p:$30000;crc:$aa80aaab),(n:'rc18.15c';l:$8000;p:$38000;crc:$ce67868e)); speedr_sprites:array[0..7] of tipo_roms=( (n:'rc20.15e';l:$8000;p:$0;crc:$3924c861),(n:'rc19.14e';l:$8000;p:$8000;crc:$ff8f9129), (n:'rc22.15f';l:$8000;p:$10000;crc:$ab64161c),(n:'rc21.14f';l:$8000;p:$18000;crc:$fd64bcd1), (n:'rc24.15h';l:$8000;p:$20000;crc:$c972af3e),(n:'rc23.14h';l:$8000;p:$28000;crc:$8c9abf57), (n:'rc26.15j';l:$8000;p:$30000;crc:$d4f1732f),(n:'rc25.14j';l:$8000;p:$38000;crc:$d2a4ea4f)); speedr_prom:array[0..1] of tipo_roms=( (n:'63s141.12a';l:$100;p:$0;crc:$8421786f),(n:'63s141.13a';l:$100;p:$100;crc:$6048583f)); //Dip speedr_dip_a:array [0..3] of def_dip=( (mask:$7;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$80;name:'Flip Screen';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); speedr_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Bonus Life';number:4;dip:((dip_val:$18;dip_name:'20K 70K+'),(dip_val:$10;dip_name:'30K 80K+'),(dip_val:$8;dip_name:'20K 80K'),(dip_val:$0;dip_name:'30K 80K'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$40;dip_name:'Easy'),(dip_val:$60;dip_name:'Normal'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$80;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var memoria_rom:array[0..$3f,0..$fff] of byte; prom_bank:array[0..$1ff] of byte; memoria_fg:array[0..$fff] of byte; soundlatch:byte; scroll_x,scroll_y:word; procedure update_video_speedr; var x,y,f,color,nchar:word; atrib:byte; begin //background for f:=$0 to $fff do begin atrib:=memoria[$2000+(f*2)]; color:=(atrib and $e0) shr 5; if (gfx[1].buffer[f] or buffer_color[color+$10]) then begin x:=f mod 64; y:=63-(f div 64); nchar:=memoria[$2001+(f*2)]+((atrib and $7) shl 8); put_gfx_flip(x*16,y*16,nchar,(color shl 4)+$80,2,1,(atrib and 8)<>0,false); if (atrib and $10)<>0 then put_gfx_trans_flip(x*16,y*16,nchar,(color shl 4)+$80,3,1,(atrib and 8)<>0,false) else put_gfx_block_trans(x*16,y*16,3,16,16); gfx[1].buffer[f]:=false; end; end; //foreground for f:=$0 to $7ff do begin atrib:=memoria_fg[f*2]; color:=(atrib and $3c) shr 2; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f mod 32; y:=63-(f div 32); nchar:=memoria_fg[$1+(f*2)]+((atrib and $3) shl 8); if (atrib and $40)<>0 then put_gfx(x*8,y*8,nchar,(color shl 2)+$1c0,1,0) else put_gfx_trans(x*8,y*8,nchar,(color shl 2)+$1c0,1,0); gfx[0].buffer[f]:=false; end; end; scroll_x_y(2,4,scroll_x,512-scroll_y); //sprites for f:=$7f downto 0 do begin atrib:=buffer_sprites[(f shl 2)+1]; nchar:=buffer_sprites[f shl 2]+((atrib and $e0) shl 3); color:=((atrib and $1c) shl 2)+$100; x:=buffer_sprites[$2+(f shl 2)]; y:=496-(buffer_sprites[$3+(f shl 2)]+((atrib and $1) shl 8)); put_gfx_sprite(nchar,color,(atrib and 2)<>0,false,2); actualiza_gfx_sprite(x,y,4,2); end; scroll_x_y(3,4,scroll_x,512-scroll_y); actualiza_trozo(0,0,256,512,1,0,0,256,512,4); //Actualiza buffer sprites copymemory(@buffer_sprites,@memoria[$1e00],$200); //chars actualiza_trozo_final(8,80,240,352,4); fillchar(buffer_color,MAX_COLOR_BUFFER,0); end; procedure eventos_speedr; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); //P2 if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); //SYS if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); end; end; procedure speedr_principal; var f:byte; frame_m,frame_s:single; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //Sound CPU z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; case f of 0:m6809_0.change_firq(HOLD_LINE); 248:begin update_video_speedr; m6809_0.change_irq(HOLD_LINE); end; end; end; eventos_speedr; video_sync; end; end; procedure cambiar_color(pos:word); var tmp_color:byte; color:tcolor; begin tmp_color:=buffer_paleta[pos]; color.r:=pal4bit(tmp_color shr 4); color.g:=pal4bit(tmp_color); tmp_color:=buffer_paleta[$1+pos]; color.b:=pal4bit(tmp_color shr 4); pos:=pos shr 1; set_pal_color(color,pos); case pos of $80..$ff:buffer_color[((pos shr 4) and $7)+$10]:=true; $1c0..$1ff:buffer_color[(pos shr 2) and $f]:=true; end; end; procedure cambiar_banco(valor:byte); var f,bank:byte; pos1,pos2:word; begin pos1:=valor and $f0; pos2:=$100+((valor and $f) shl 4); for f:=5 to $f do begin bank:=((prom_bank[f+pos1] and $03) shl 4) or (prom_bank[f+pos2] and $0f); copymemory(@memoria[f*$1000],@memoria_rom[bank,0],$1000); end; end; function speedr_getbyte(direccion:word):byte; begin case direccion of $0..$3fff,$5000..$ffff:speedr_getbyte:=memoria[direccion]; $4008:speedr_getbyte:=marcade.in0; $4009:speedr_getbyte:=marcade.in1; $400a:speedr_getbyte:=marcade.in2; $400b:speedr_getbyte:=marcade.dswa; $400c:speedr_getbyte:=marcade.dswb; end; end; procedure speedr_putbyte(direccion:word;valor:byte); begin case direccion of 0..$1fff:memoria[direccion]:=valor; $2000..$3fff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[1].buffer[(direccion and $1fff) shr 1]:=true; end; $4009:main_screen.flip_main_screen:=(valor and 1)<>0; $4008:cambiar_banco(valor); $400a:scroll_y:=(scroll_y and $300) or valor; $400b:scroll_y:=(scroll_y and $ff) or ((valor and 3) shl 8); $400c:scroll_x:=(scroll_x and $300) or valor; $400d:scroll_x:=(scroll_x and $ff) or ((valor and 3) shl 8); $400e:soundlatch:=valor; $5000..$5fff:if memoria_fg[direccion and $fff]<>valor then begin gfx[0].buffer[(direccion and $fff) shr 1]:=true; memoria_fg[direccion and $fff]:=valor; end; $7000..$73ff:if buffer_paleta[direccion and $3ff]<>valor then begin buffer_paleta[direccion and $3ff]:=valor; cambiar_color(direccion and $3fe); end; $6000..$6fff,$7400..$ffff:; //ROM end; end; function sound_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$c000..$c7ff:sound_getbyte:=mem_snd[direccion]; $e000:sound_getbyte:=soundlatch; end; end; procedure sound_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; //ROM $c000..$c7ff:mem_snd[direccion]:=valor; $8000:ym2203_0.Control(valor); $8001:ym2203_0.Write(valor); $a000:ym2203_1.Control(valor); $a001:ym2203_1.Write(valor); end; end; procedure speedr_sound_update; begin ym2203_0.update; ym2203_1.update; end; procedure snd_irq(irqstate:byte); begin z80_0.change_irq(irqstate); end; //Main procedure reset_speedr; begin //Poner el banco antes que el reset!!! cambiar_banco(0); m6809_0.reset; z80_0.reset; ym2203_0.reset; ym2203_1.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; soundlatch:=0; scroll_x:=0; scroll_y:=0; end; function iniciar_speedr:boolean; var f:byte; memoria_temp:array[0..$3ffff] of byte; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 2*64+0, 2*64+1, 2*64+2, 2*64+3, 2*64+4, 2*64+5, 2*64+6, 2*64+7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); pt_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 32*8+0, 32*8+1, 32*8+2, 32*8+3, 33*8+0, 33*8+1, 33*8+2, 33*8+3); pt_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); begin llamadas_maquina.bucle_general:=speedr_principal; llamadas_maquina.reset:=reset_speedr; iniciar_speedr:=false; iniciar_audio(false); //Background screen_init(1,256,512,true); //Foreground screen_init(2,1024,1024); screen_mod_scroll(2,1024,256,1023,1024,512,1023); screen_init(3,1024,1024,true); screen_mod_scroll(3,1024,256,1023,1024,512,1023); screen_init(4,256,512,false,true); //Final iniciar_video(240,352); //Main CPU m6809_0:=cpu_m6809.Create(8000000,256,TCPU_MC6809); m6809_0.change_ram_calls(speedr_getbyte,speedr_putbyte); //Sound CPU z80_0:=cpu_z80.create(4000000,256); z80_0.change_ram_calls(sound_getbyte,sound_putbyte); z80_0.init_sound(speedr_sound_update); //Sound Chip ym2203_0:=ym2203_chip.create(4000000); ym2203_0.change_irq_calls(snd_irq); ym2203_1:=ym2203_chip.create(4000000); //cargar roms if not(roms_load(@memoria_temp,speedr_rom)) then exit; if not(roms_load(@prom_bank,speedr_prom)) then exit; //Pongo las ROMs en su banco for f:=0 to $3f do copymemory(@memoria_rom[f,0],@memoria_temp[(f*$1000)],$1000); //Cargar Sound if not(roms_load(@mem_snd,speedr_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,speedr_char)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[3]:=true; gfx_set_desc_data(2,0,16*8,4,0); convert_gfx(0,0,@memoria_temp,@pt_x,@pt_y,false,true); //tiles if not(roms_load(@memoria_temp,speedr_tiles)) then exit; init_gfx(1,16,16,$800); for f:=0 to 10 do gfx[1].trans[f]:=true; gfx_set_desc_data(4,0,64*8,$800*64*8+4,$800*64*8+0,4,0); convert_gfx(1,0,@memoria_temp,@pt_x,@pt_y,false,true); //sprites if not(roms_load(@memoria_temp,speedr_sprites)) then exit; init_gfx(2,16,16,$800); gfx[2].trans[15]:=true; gfx_set_desc_data(4,0,32*8,$1800*32*8,$1000*32*8,$800*32*8,$0*32*8); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,true); //Dip marcade.dswa:=$ff; marcade.dswb:=$73; marcade.dswa_val:=@speedr_dip_a; marcade.dswb_val:=@speedr_dip_b; //final reset_speedr; iniciar_speedr:=true; end; end.
unit uImageDownloadThread; interface uses Classes, SysUtils, TypInfo, Variants, XMLDoc, DB, nxdb, ShoppingServiceXMLClasses, EbayConnect, uTypes, Forms, IdThread, IdSync, uThreadSync, IdComponent; type TDownloadImagesThread = class(TidThread) private // Private declarations FForm : TForm; FOperationResult : AckCodeType; FErrorRecord : eBayAPIError; FEItemId : string; RecAdded : Integer; FSyncObj : TFTSync; FRxDelta : Integer; FTxDelta : Integer; FItemsToGet : TStringList; FEbayShoppingConnect : TEbayShoppingConnect; FGetMultipleItems : TGetMultipleItems; FQuery : TnxQuery; FQueryItems : TnxQuery; FAppID : string; FSiteID : SiteCodeType; FGlobalID : Global_ID; FUpdateRec : TDownloadImageThreadStatus; FCounter : Integer; FCounterAll : Integer; FBasePath : string; FImageFolder : string; FMultiThread : Boolean; FFirsImage : string; FFirstURL : string; protected // Protected declarations procedure GetMultipleItemsAPIError(Sender: TObject; ErrorRecord: eBayAPIError); procedure GetMultipleItemsEndRequest(Sender: TObject); procedure GetMultipleItemsStartRequest(Sender: TObject); procedure WriteEbayApiExceptionLog(E : Exception); procedure WriteExceptionLog(E: Exception); procedure SetItemsToGet(Value : TStringList); procedure DecTCounter; procedure SetGlobalID(Value : Global_ID); procedure EbayShoppingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); public // Public declarations TID : Integer; // Objects visible outside threads property SiteID : SiteCodeType read FSiteID; property AppID : string read FAppID write FAppID; property GlobalID : Global_ID read FGlobalID write SetGlobalID; property ItemsToGet : TStringList read FItemsToGet write SetItemsToGet; property MultiThread : Boolean read FMultiThread write FMultiThread; property FirstImageID : string read FFirsImage write FFirsImage; property FirstImageUrl : string read FFirstURL write FFirstURL; // methods constructor Create; destructor Destroy; override; procedure Run; override; procedure WriteToDB; end; implementation uses functions, ActiveX, IdHTTP, uMain, uHttpDownload; { TCompleteCheckThread } constructor TDownloadImagesThread.Create; begin inherited Create; FEbayShoppingConnect := TEbayShoppingConnect.Create(nil); FEbayShoppingConnect.OnWork := EbayShoppingConnectWork; FEbayShoppingConnect.AppID := FAppID; FGlobalID := EBAY_US; FSiteID := GlobalID2SiteCode(FGlobalID); FEbayShoppingConnect.SiteID := FSiteID; FQueryItems := TnxQuery.Create(nil); FQueryItems.Database := fmMain.nxdtbs1; FQueryItems.SQL.Add('SELECT TOP 19 Items.ItemID'); FQueryItems.SQL.Add('FROM Items'); FQueryItems.SQL.Add('WHERE Items.PictureURL Is Null'); FItemsToGet := TStringList.Create; FSyncObj := TFTSync.Create(Self); FBasePath := fmMain.BasePath; FImageFolder := 'Photos'; DecTCounter; FreeOnTerminate := True; FMultiThread := True; FFirsImage := ''; end; destructor TDownloadImagesThread.Destroy; begin FreeAndNil(FEbayShoppingConnect); FreeAndNil(FItemsToGet); FreeAndNil(FSyncObj); FreeAndNil(FQueryItems); inherited; end; procedure TDownloadImagesThread.DecTCounter; begin FSyncObj.Operation := OpDecCounter; FSyncObj.Synchronize; end; procedure TDownloadImagesThread.EbayShoppingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin case AWorkMode of wmRead : begin FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FRxDelta); FRxDelta := AWorkCount; end; wmWrite : begin FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FTxDelta); FTxDelta := AWorkCount; end; end; end; procedure TDownloadImagesThread.GetMultipleItemsAPIError(Sender: TObject; ErrorRecord: eBayAPIError); var i : Integer; begin with ErrorRecord , FSyncObj do begin WriteAdvLog(Format('%s: ThreadID %d - ApiCall: GetMultipleItems. API Error',[DateTimeToStr(now),Self.ThreadID])); WriteAdvLog(Format('ShortMessage %s , LongMessage %s ',[ShortMessage, LongMessage])); WriteAdvLog(Format('ErrorCode %s , SeverityCode %s ,ErrorClassification, %s, index %d',[ErrorCode,SeverityCode,ErrorClassification,index])); end; FSyncObj.WriteAdvLog('Request XML'); for i := 0 to FEbayShoppingConnect.RequestXMLText.Count -1 do FSyncObj.WriteAdvLog(FEbayShoppingConnect.RequestXMLText.Strings[i]); FSyncObj.WriteAdvLog('Response XML'); for i := 0 to FEbayShoppingConnect.ResponseXMLText.Count -1 do FSyncObj.WriteAdvLog(FEbayShoppingConnect.ResponseXMLText.Strings[i]); FSyncObj.SaveAdvLog; end; procedure TDownloadImagesThread.GetMultipleItemsEndRequest(Sender: TObject); begin FSyncObj.WriteLog(Format('%s: ThreadID %d - ApiCall: GetMultipleItems. Result %s',[DateTimeToStr(now),Self.ThreadID,GetEnumName(TypeInfo(AckCodeType),ord(FGetMultipleItems.Ack))])); FGetMultipleItems.ResponseXMLDoc.SaveToFile('GetMultipleItemsResponse.xml'); FSyncObj.IncApiUsage; end; procedure TDownloadImagesThread.GetMultipleItemsStartRequest( Sender: TObject); begin FSyncObj.WriteLog(Format('%s: ThreadID %d - ApiCall: GetMultipleItems. Starting',[DateTimeToStr(now),Self.ThreadID])); FGetMultipleItems.RequestXMLDoc.SaveToFile('GetMultipleItemsRequest.xml'); end; procedure TDownloadImagesThread.Run; var i : Integer; hr: HRESULT; begin inherited; try hr := CoInitializeEx(nil, COINIT_APARTMENTTHREADED); FGetMultipleItems := TGetMultipleItems.Create(nil); FGetMultipleItems.OnAPIError := GetMultipleItemsAPIError; FGetMultipleItems.OnStartRequest := GetMultipleItemsStartRequest; FGetMultipleItems.OnEndRequest := GetMultipleItemsEndRequest; FGetMultipleItems.Connector := FEbayShoppingConnect; FGetMultipleItems.IncludeSelector := [Details,ItemSpecifics,Description]; if hr <> S_OK then Exception.Create('Error occurs: ' + IntToHex(hr, 2)); try FItemsToGet.Clear; FItemsToGet.Add(FFirsImage); FQueryItems.Open; if FQueryItems.RecordCount >0 then begin while not FQueryItems.Eof do begin FItemsToGet.Add(FQueryItems.FieldValues['ItemID']); FQueryItems.Next; end; FEbayShoppingConnect.AppID := FAppID; FEbayShoppingConnect.SiteID := FSiteID; FGetMultipleItems.ItemID.Clear; for i := 0 to FItemsToGet.Count-1 do FGetMultipleItems.ItemID.Add(FItemsToGet.Strings[i]); try FRxDelta := 0; FTxDelta := 0; FOperationResult := FGetMultipleItems.DoRequestEx; if (FOperationResult in [Failure, PartialFailure]) then begin Exception.Create('Request Failure'); end; if Terminated then Exit; if FOperationResult in [Success, Warning, PartialFailure] then begin FCounterAll := 0; FCounter := 0; WriteToDB; FUpdateRec.TotalItems := FCounterAll; FUpdateRec.SavedPhotos := FCounter; FSyncObj.UpdDThreadStatus(FUpdateRec); end; if (FOperationResult in [Failure, Warning, PartialFailure]) then with FSyncObj do begin WriteLog(Format('%s: ThreadID %d Request failure',[DateTimeToStr(now),Self.ThreadID])); WriteAdvLog('Request XML'); for i := 0 to FEbayShoppingConnect.RequestXMLText.Count -1 do WriteAdvLog(FEbayShoppingConnect.RequestXMLText.Strings[i]); WriteAdvLog('Response XML'); for i := 0 to FEbayShoppingConnect.ResponseXMLText.Count -1 do WriteAdvLog(FEbayShoppingConnect.ResponseXMLText.Strings[i]); SaveAdvLog; end; except on E : Exception do WriteEbayApiExceptionLog(E); end; if Terminated then Stop; end else Stop; finally FQueryItems.Close; end; finally CoUninitialize; FreeAndNil(FGetMultipleItems); end; Stop; end; procedure TDownloadImagesThread.WriteEbayApiExceptionLog(E: Exception); var i : Integer; begin with FSyncObj do begin WriteLog(Format('%s: ThreadID %d Exception',[DateTimeToStr(now),Self.ThreadID])); WriteLog(Format('Exception class name: %s',[E.ClassName])); WriteLog(Format('Exception message: %s',[E.Message])); WriteAdvLog('Request XML'); for i := 0 to FEbayShoppingConnect.RequestXMLText.Count -1 do WriteAdvLog(FEbayShoppingConnect.RequestXMLText.Strings[i]); WriteAdvLog('Response XML'); for i := 0 to FEbayShoppingConnect.ResponseXMLText.Count -1 do WriteAdvLog(FEbayShoppingConnect.ResponseXMLText.Strings[i]); SaveAdvLog; end; end; procedure TDownloadImagesThread.WriteExceptionLog(E: Exception); begin with FSyncObj do begin WriteLog(Format('%s: ThreadID %d Exception',[DateTimeToStr(now),Self.ThreadID])); WriteLog(Format('Exception class name: %s',[E.ClassName])); WriteLog(Format('Exception message: %s',[E.Message])); SaveAdvLog; end; end; procedure TDownloadImagesThread.WriteToDB; var i, j: Integer; MemStream: TMemoryStream; ImgHttp : TidHttp; ContentType : string; ItemDetails : TItemDetails; begin try for i:=0 to FGetMultipleItems.Items.Count-1 do with FGetMultipleItems.Items.Items[i] do begin inc(FCounterAll); ItemDetails.PictureURL := No_Photo; ItemDetails.ItemID := ItemID; ItemDetails.Description := Description; if ChildNodes.FindNode('PictureURL') <> nil then begin //if PictureURL <> nil then begin try ItemDetails.PictureURL := PictureURL[0]; except ItemDetails.PictureURL := No_Photo; end; end; // try save photo url if FFirsImage = ItemID then FFirstURL := ItemDetails.PictureURL; FSyncObj.SavePictureDetails(ItemDetails); inc(FCounter); //************** // end try download photos end; except on E : Exception do begin WriteExceptionLog(E); FSyncObj.WriteLog(Format('Exception ItemID: %s',[ItemDetails.ItemID])); end; end; end; procedure TDownloadImagesThread.SetItemsToGet(Value : TStringList); begin if Value <> nil then FItemsToGet.Assign(Value); end; procedure TDownloadImagesThread.SetGlobalID(Value : Global_ID); begin FGlobalID := Value; FSiteID := GlobalID2SiteCode(FGlobalID); FEbayShoppingConnect.SiteID := FSiteID; end; initialization Randomize; end.
unit MdiChilds.DocToProjectFormat; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.Reg, MdiChilds.ProgressForm, MdiChilds.DocList, MDIChilds.CustomDialog, Vcl.StdCtrls, Vcl.ExtCtrls, GlobalData, GsDocument; type TFmDocToProjectFormat = class(TFmProcess) btnDocLoad: TButton; Label1: TLabel; lblDocCount: TLabel; Timer: TTimer; procedure btnDocLoadClick(Sender: TObject); procedure TimerTimer(Sender: TObject); private { Private declarations } protected procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure AfterExecute; override; public procedure AfterConstruction; override; procedure ExecuteDocument(D: TGsDocument); end; var FmDocToProjectFormat: TFmDocToProjectFormat; implementation {$R *.dfm} procedure TFmDocToProjectFormat.AfterConstruction; begin inherited; lblDocCount.Caption := IntToStr(Documents.Count); end; procedure TFmDocToProjectFormat.AfterExecute; var I: Integer; begin for I := 0 to Documents.Count - 1 do Documents[I].Save; end; procedure TFmDocToProjectFormat.btnDocLoadClick(Sender: TObject); begin TFmDocList.CreateForm(True).Show; end; procedure TFmDocToProjectFormat.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; D: TGsDocument; begin ShowMessage := True; ProgressForm.InitPB(Documents.Count); ProgressForm.Show; for I := 0 to Documents.Count - 1 do begin if not ProgressForm.InProcess then Break; D := Documents[I]; ProgressForm.StepIt(ExtractFileName(D.FileName)); ExecuteDocument(D); end; end; procedure TFmDocToProjectFormat.ExecuteDocument(D: TGsDocument); var L: Tlist; I: Integer; Row: TGsRow; Cost: TGsCost; J: Integer; Factor: TGsFactor; TypeName: string; RowA: TGsRow; RowB: TGsRow; begin RowA := nil; TypeName := D.TypeName; D.BaseDataType := bdtProject; D.TypeName := TypeName; L := TList.Create; try D.Chapters.EnumItems(L, TGsRow, True); for I := 0 to L.Count - 1 do begin Row := TGsRow(L[I]); if Row.Code.EndsText('А', Row.Code) then RowA := Row; if Row.Code.EndsText('Б', Row.Code) then begin RowB := Row; RowA.Code := StringReplace(RowA.Code, '-А', '', []); RowB.Code := StringReplace(RowA.Code, '-Б', '', []); RowA.Code := StringReplace(RowA.Code, 'А', '', []); RowB.Code := StringReplace(RowA.Code, 'Б', '', []); if AnsiSameText(RowA.Caption, RowB.Caption) then begin Cost := RowB.GetCost(cstPZ); if Cost <> nil then Cost.Kind := cstPriceB; RowA.AssignCost(cstPriceB, RowB); RowA.Measure := RowB.Measure; Cost := RowA.GetCost(cstPZ); if Cost <> nil then Cost.Kind := cstPriceA; RowB.Enabled := False; //пометка на удаление end; end; Cost := Row.GetCost(cstPZ); if Cost <> nil then Cost.Kind := cstPriceA; for J := 0 to Row.FactorList.Count - 1 do begin Factor := TGsFactor(Row.FactorList.Items[J]); if Factor.Attributes[Ord(GsDocument.dtaPZ)] <> Unassigned then begin Factor.Attributes[Ord(GsDocument.dtaProjectDocK)] := Factor.Attributes[Ord(GsDocument.dtaPZ)]; Factor.Attributes[Ord(GsDocument.dtaPZ)] := Unassigned; end; end; end; finally L.Free; end; end; procedure TFmDocToProjectFormat.TimerTimer(Sender: TObject); begin lblDocCount.Caption := IntToStr(Documents.Count); end; begin FormsRegistrator.RegisterForm(TFmDocToProjectFormat, 'Перевод сборников в новый формат "проектные работы"', 'Утилиты', false, dpkCustom, '/FORMATPROJECT'); end.
unit AddressBookContactUnit; interface uses REST.Json.Types, System.Generics.Collections, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit, JSONDictionaryIntermediateObjectUnit; type /// <summary> /// Address Book Contact /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Addressbook_v4.dtd /// </remarks> TAddressBookContact = class(TGenericParameters) private [JSONName('address_id')] [Nullable] FId: NullableInteger; [JSONName('address_group')] [Nullable] FAddressGroup: NullableString; [JSONName('address_alias')] [Nullable] FAlias: NullableString; [JSONName('address_1')] FAddress: String; [JSONName('address_2')] [Nullable] FAddress2: NullableString; [JSONName('first_name')] [Nullable] FFirstName: NullableString; [JSONName('last_name')] [Nullable] FLastName: NullableString; [JSONName('address_email')] [Nullable] FEmail: NullableString; [JSONName('address_phone_number')] [Nullable] FPhoneNumber: NullableString; [JSONName('address_city')] [Nullable] FCity: NullableString; [JSONName('address_state_id')] [Nullable] FStateId: NullableString; [JSONName('address_country_id')] [Nullable] FCountryId: NullableString; [JSONName('address_zip')] [Nullable] FZip: NullableString; [JSONName('cached_lat')] FLatitude: Double; [JSONName('cached_lng')] FLongitude: Double; [JSONName('curbside_lat')] [Nullable] FCurbsideLatitude: NullableDouble; [JSONName('curbside_lng')] [Nullable] FCurbsideLongitude: NullableDouble; [JSONName('color')] [Nullable] FColor: NullableString; [JSONName('address_icon')] [Nullable] FAddressIcon: NullableString; [JSONName('address_custom_data')] [NullableObject(TDictionaryStringIntermediateObject)] FCustomData: NullableObject; function GetCustomData: TDictionaryStringIntermediateObject; public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; overload; override; constructor Create(Address: String; Latitude, Longitude: Double); reintroduce; overload; destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Address unique ID /// </summary> property Id: NullableInteger read FId write FId; /// <summary> /// Address group /// </summary> property AddressGroup: NullableString read FAddressGroup write FAddressGroup; /// <summary> /// Address alias /// </summary> property Alias: NullableString read FAlias write FAlias; /// <summary> /// The route Address Line 1 /// </summary> property Address: String read FAddress write FAddress; /// <summary> /// The route Address Line 2 which is not used for geocoding /// </summary> property Address2: NullableString read FAddress2 write FAddress2; /// <summary> /// The first name of the receiving address /// </summary> property FirstName: NullableString read FFirstName write FFirstName; /// <summary> /// The last name of the receiving party /// </summary> property LastName: NullableString read FLastName write FLastName; /// <summary> /// Address email /// </summary> property Email: NullableString read FEmail write FEmail; /// <summary> /// The phone number for the address /// </summary> property PhoneNumber: NullableString read FPhoneNumber write FPhoneNumber; /// <summary> /// The city the address is located in /// </summary> property City: NullableString read FCity write FCity; /// <summary> /// The state the address is located in /// </summary> property StateId: NullableString read FStateId write FStateId; /// <summary> /// The country the address is located in /// </summary> property CountryId: NullableString read FCountryId write FCountryId; /// <summary> /// The zip code the address is located in /// </summary> property Zip: NullableString read FZip write FZip; /// <summary> /// Cached latitude /// </summary> property Latitude: Double read FLatitude write FLatitude; /// <summary> /// Cached longitude /// </summary> property Longitude: Double read FLongitude write FLongitude; /// <summary> /// Curbside latitude /// </summary> property CurbsideLatitude: NullableDouble read FCurbsideLatitude write FCurbsideLatitude; /// <summary> /// Curbside longitude /// </summary> property CurbsideLongitude: NullableDouble read FCurbsideLongitude write FCurbsideLongitude; /// <summary> /// Color of an address /// </summary> property Color: NullableString read FColor write FColor; /// <summary> /// URL to an address icon file /// </summary> property AddressIcon: NullableString read FAddressIcon write FAddressIcon; /// <summary> /// Address custom data /// </summary> property CustomData: TDictionaryStringIntermediateObject read GetCustomData; procedure AddCustomData(Key: String; Value: String); end; TAddressBookContactArray = TArray<TAddressBookContact>; TAddressBookContactList = TObjectList<TAddressBookContact>; implementation { TAddressBookContact } constructor TAddressBookContact.Create; begin Inherited Create; FId := NullableInteger.Null; FAddressGroup := NullableString.Null; FAlias := NullableString.Null; FAddress2 := NullableString.Null; FFirstName := NullableString.Null; FLastName := NullableString.Null; FEmail := NullableString.Null; FPhoneNumber := NullableString.Null; FCity := NullableString.Null; FStateId := NullableString.Null; FCountryId := NullableString.Null; FZip := NullableString.Null; FColor := NullableString.Null; FAddressIcon := NullableString.Null; FCustomData := NullableObject.Null; FCurbsideLatitude := NullableDouble.Null; FCurbsideLongitude := NullableDouble.Null; end; { TAddressBookContact } procedure TAddressBookContact.AddCustomData(Key, Value: String); var Dic: TDictionaryStringIntermediateObject; begin if (FCustomData.IsNull) then FCustomData := TDictionaryStringIntermediateObject.Create(); Dic := FCustomData.Value as TDictionaryStringIntermediateObject; Dic.Add(Key, Value); end; constructor TAddressBookContact.Create(Address: String; Latitude, Longitude: Double); begin Create; FAddress := Address; FLatitude := Latitude; FLongitude := Longitude; end; destructor TAddressBookContact.Destroy; begin if FCustomData.IsNotNull then FCustomData.Free; inherited; end; function TAddressBookContact.Equals(Obj: TObject): Boolean; var Other: TAddressBookContact; begin Result := False; if not (Obj is TAddressBookContact) then Exit; Other := TAddressBookContact(Obj); Result := (FId = Other.FId) and (FAddressGroup = Other.FAddressGroup) and (FAlias = Other.FAlias) and (FAddress = Other.FAddress) and (FAddress2 = Other.FAddress2) and (FFirstName = Other.FFirstName) and (FLastName = Other.FLastName) and (FEmail = Other.FEmail) and (FPhoneNumber = Other.FPhoneNumber) and (FCity = Other.FCity) and (FStateId = Other.FStateId) and (FCountryId = Other.FCountryId) and (FZip = Other.FZip) and (FLatitude = Other.FLatitude) and (FLongitude = Other.FLongitude) and (FCurbsideLatitude = Other.FCurbsideLatitude) and (FCurbsideLongitude = Other.FCurbsideLongitude) and (FColor = Other.FColor) and (FAddressIcon = Other.FAddressIcon) and (FCustomData = Other.FCustomData); end; function TAddressBookContact.GetCustomData: TDictionaryStringIntermediateObject; begin if (FCustomData.IsNull) then Result := nil else Result := FCustomData.Value as TDictionaryStringIntermediateObject; 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.6 7/23/04 6:40:08 PM RLebeau Added extra exception handling to Connect() Rev 1.5 2004.05.20 11:39:10 AM czhower IdStreamVCL Rev 1.4 2004.02.03 4:17:18 PM czhower For unit name changes. Rev 1.3 10/19/2003 11:38:26 AM DSiders Added localization comments. Rev 1.2 2003.10.18 1:56:46 PM czhower Now uses ASCII instead of binary format. Rev 1.1 2003.10.17 6:16:20 PM czhower Functional complete. } unit IdInterceptSimLog; { This file uses string outputs instead of binary so that the results can be viewed and modified with notepad if necessary. Most times a Send/Receive includes a writeln, but may not always. We write out an additional EOL to guarantee separation in notepad. It also auto detects when an EOL can be used instead. TODO: Can also change it to detect several EOLs and non binary and use :Lines:x } interface {$i IdCompilerDefines.inc} uses Classes, IdGlobal, IdIntercept, IdBaseComponent; type TIdInterceptSimLog = class(TIdConnectionIntercept) private protected FFilename: string; FStream: TStream; // procedure SetFilename(const AValue: string); procedure WriteRecord(const ATag: string; const ABuffer: TIdBytes); public procedure Connect(AConnection: TComponent); override; procedure Disconnect; override; procedure Receive(var ABuffer: TIdBytes); override; procedure Send(var ABuffer: TIdBytes); override; published property Filename: string read FFilename write SetFilename; end; implementation uses {$IFDEF DOTNET} IdStreamNET, {$ELSE} IdStreamVCL, {$ENDIF} IdException, IdResourceStringsCore, SysUtils; { TIdInterceptSimLog } procedure TIdInterceptSimLog.Connect(AConnection: TComponent); begin inherited Connect(AConnection); // Warning! This will overwrite any existing file. It makes no sense // to concatenate sim logs. FStream := TIdFileCreateStream.Create(Filename); end; procedure TIdInterceptSimLog.Disconnect; begin FreeAndNil(FStream); inherited Disconnect; end; procedure TIdInterceptSimLog.Receive(var ABuffer: TIdBytes); begin // let the next Intercept in the chain decode its data first inherited Receive(ABuffer); WriteRecord('Recv', ABuffer); {do not localize} end; procedure TIdInterceptSimLog.Send(var ABuffer: TIdBytes); begin WriteRecord('Send', ABuffer); {do not localize} // let the next Intercept in the chain encode its data next inherited Send(ABuffer); end; procedure TIdInterceptSimLog.SetFilename(const AValue: string); begin if Assigned(FStream) then begin EIdException.Toss(RSLogFileAlreadyOpen); end; FFilename := AValue; end; procedure TIdInterceptSimLog.WriteRecord(const ATag: string; const ABuffer: TIdBytes); var i: Integer; LUseEOL: Boolean; LSize: Integer; begin LUseEOL := False; LSize := Length(ABuffer); if LSize > 1 then begin if (ABuffer[LSize - 2] = 13) and (ABuffer[LSize - 1] = 10) then begin LUseEOL := True; for i := 0 to LSize - 3 do begin // If any binary, CR or LF if (ABuffer[i] < 32) or (ABuffer[i] > 127) then begin LUseEOL := False; Break; end; end; end; end; with FStream do begin if LUseEOL then begin WriteLn(ATag + ':EOL'); {do not localize} end else begin WriteLn(ATag + ':Bytes:' + IntToStr(LSize)); {do not localize} end; WriteStringToStream(FStream, ''); WriteTIdBytesToStream(FStream, ABuffer, LSize); WriteStringToStream(FStream, EOL); end; end; end.
unit UnrarDll; interface function UnrarAll(const fn, dir: string): boolean; function UnrarSingle(const fn, dir, fn1: string): boolean; implementation uses Windows, SysUtils, RAR, Classes; function UnrarAll(const fn, dir: string): boolean; var r: TRAR; begin r := TRAR.Create(nil); try Result := r.OpenFile(fn); if Result then Result := r.Extract(dir, True, nil); finally FreeAndNil(r); end; end; function UnrarSingle(const fn, dir, fn1: string): boolean; var r: TRAR; List: TStringList; begin r := TRAR.Create(nil); List := TStringList.Create; List.Add(fn1); try Result := r.OpenFile(fn); if Result then Result := r.Extract(dir, False, List); finally FreeAndNil(r); FreeAndNil(List); end; end; end.
program ReverseArray(input, output); const MAX_SIZE = 30; var size, i, number : integer; list : array[0..MAX_SIZE] of integer; begin write('Enter the numbers, input 1 to indicate termination: '); size := 0; number := 1; while number <> 0 do begin read(number); list[size] := number; size := size + 1; end; size := size - 2; for i := size downto 0 do write(list[i], ' '); writeln(); end.
{***********************************************************************} { TPlanner component } { for Delphi & C++Builder } { } { written by TMS Software } { copyright © 1999-2012 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } {***********************************************************************} unit planreg; {$I TMSDEFS.INC} interface uses Classes, Planner, PlanCheck , PlanItemEdit, PlanSimpleEdit, PlanPeriodEdit, PlannerWaitList, PlannerActions, ActnList , PlanRecurrEdit , PlanDraw {$IFDEF DELPHIXE3_LVL} , System.Actions {$ENDIF} ; procedure Register; implementation procedure Register; begin RegisterComponents('TMS Planner', [TPlanner]); RegisterComponents('TMS Planner', [TCapitalPlannerCheck]); RegisterComponents('TMS Planner', [TAlarmMessage]); RegisterComponents('TMS Planner', [TSimpleItemEditor]); RegisterComponents('TMS Planner', [TDefaultItemEditor]); RegisterComponents('TMS Planner', [TPeriodItemEditor]); RegisterComponents('TMS Planner', [TPlannerRecurrencyEditor]); RegisterComponents('TMS Planner', [TShapeDrawTool]); RegisterComponents('TMS Planner', [TPlannerWaitList]); RegisterActions('Planner', [TPlannerCut, TPlannerCopy, TPlannerPaste, TPlannerDelete, TPlannerInsert, TPlannerEdit], nil); end; end.
unit UCodes; interface var DosOrigLevelCodes: array[0..3, 0..29] of string = ( ( 'AAWFHRIEJL', 'CMBVBHXJUI', 'SVSHEIMGVH', 'MDWHUZMXVA', 'DDNAPAUQUS', 'OFRPYQZGRH', 'CUMWNOYRIA', 'SZUTFDXUPW', 'RHCQHWEHOY', 'EEGEOMHEPT', 'TCBBCUUJPL', 'TMIVVDCBBF', 'RFOGJVIIRR', 'XIMHTTOSKO', 'PWRCMKCBOR', 'CXVRYHSTMR', 'EFYJDZHBCW', 'OSCRAIXNIL', 'XJJMBWTEXM', 'DXKFUPCQYO', 'ILFERZQROC', 'TDGWSLZEBE', 'AJKJCLNLRV', 'OGJPWPGSOW', 'JJQULFSVTX', 'EUGHSLZEAF', 'XIWTZHKVAG', 'BNKADSIKOG', 'DHBSIUROXA', 'GXRAEEKKDA' ), ( 'NTOGWBMBJR', 'FUNKBZEBBC', 'UYCFTZMAPU', 'XNRZTSXZTU', 'AJIBUGWXBX', 'YMRJKTSIQN', 'ZCZAQJNQVQ', 'YMMZGFLRTA', 'PUMEQBZUWL', 'AFPWBMYWWS', 'ZFERVEAVOM', 'LDUWCPUFMK', 'NSUIAPHBMF', 'CRWIHMXSKC', 'VGAJXWLGKJ', 'QLQTVLNQIG', 'KSREYAIXMN', 'WRKPDZMDIP', 'VMDMDIRVWE', 'ETHIGBXRCR', 'AQPUEXVQMU', 'TEJXNWSHPC', 'IJKOXRTZJC', 'KHXGKCNNNF', 'FKZNPJJUXR', 'ONYFAZMZFV', 'CLBZJSWVKR', 'HWEJKCZAEC', 'BQHUDSKMNC', 'YIYHUWKNHS' ), ( 'ILLZJPSMEI', 'KMJMBEZOLX', 'VPKHVPHQWG', 'QBMVWFZRSG', 'XGMJVPAKFM', 'NGOPIOTSEY', 'LSOONTXOPV', 'LAYATXGQYU', 'BCJWFYPZUK', 'AAPUMNTYHE', 'DZDIEKMCJH', 'HBHVGJPBGK', 'BTKASNLSAC', 'GNUQGVMLBR', 'RLGPJCWPVA', 'RRWJVUXCGN', 'TULKEXMDYQ', 'PCLASDFCJQ', 'LOHSKCSZFU', 'LSZLATCPPX', 'PUIQWHGBJA', 'IXEBWJEGMX', 'KDDQHKOWVE', 'TTREJHYKFG', 'AWVAENHQOO', 'MUESGEWXCG', 'XRDKLLUXKX', 'OAWPKYXPQK', 'DCZNZHKRMB', 'CTDWFOEPQY' ), ( 'ZGAGFZYVDN', 'HPNIIUCRXB', 'KXMKUCRWHD', 'XVCGYKWUYC', 'AHSGKCRARZ', 'SSOIROJIKC', 'HUNOARNIHO', 'FNXLQHOSFM', 'RIPNLDNUSF', 'LZTVKAYOMM', 'OVCBQEASXV', 'BDWAYACZHY', 'ABBGHUKVTZ', 'JUFYJYHJYO', 'GKHSWNWBFM', 'TETTURRRHI', 'GGKSLFGRGN', 'TVTZXTELEE', 'YBDXVXGCRW', 'VSATNHATKA', 'ISZOJHYNZM', 'KIDCASIQJG', 'DDSXOBIYHQ', 'ZBPTKWIPHB', 'LNTACWPPVW', 'EYCQQNBVDS', 'EUPCKBXTXM', 'VELOFGWLKR', 'BBBCMYEBRY', 'ACCCGRORQJ' ) ); // the following codes are randomly generated by me DosOhNoLevelCodes: array[0..4, 0..19] of string = ( ( 'STSNZYUSZH', 'KVFLBJEMSC', 'NUMGUBQDDU', 'HCWYUNZZBW', 'UYGVNJFOYQ', 'GJIKJVJHRM', 'OAKYVCKECN', 'QLCWMYNAJH', 'UOWHABSVFF', 'KOCMUSTJKV', 'UEEELFTUHV', 'TCYHLRQARI', 'SMJIADXCQC', 'EICHWBTVZA', 'WRODQXQWSM', 'VTTNGRSGCJ', 'GSZYPHFKEB', 'DGMUYNUTSS', 'IJHRKIYNSO', 'UUIXSQMKHR' ), ( 'IBOFJVXZGF', 'ROHSNBDNPU', 'LDFFGIZRMS', 'OTZOROVWOC', 'RXEIVGMCSJ', 'MLQMSJJYAA', 'XFZQLVDAHG', 'VDMLRKUTPF', 'HWELYLLRVS', 'XCRWYREYWI', 'GVSHYTHRQU', 'TCHNITDGPJ', 'OVITHLGMAN', 'WEHVBHHVUQ', 'LWGULPXJBP', 'HKJQRLUQGX', 'EVLJAUUVJS', 'RDSIWNXXBI', 'RMPOVNCEVZ', 'RBDUCQETPG' ), ( 'ZUFSSMUTAY', 'BRZJOIKCKJ', 'QZTJUZMUOB', 'ISTJIIELUH', 'QWLJBCDZKC', 'DBZZCLGONQ', 'BNRDDAPLKI', 'XETKAOCVHP', 'WKLRGGVGBL', 'GYPFGEJMJC', 'JAUSUAQGIE', 'WZUZIGKWMY', 'ZCZPGTRHNO', 'RUNJLMNSNP', 'CESRWBKJYY', 'EAEPFKCBPR', 'OEGOXDJIAG', 'YQTDRARVAA', 'AIGEESQGJL', 'LJENOAFXOI' ), ( 'PWNOVXLFRV', 'ETHVSKSXEA', 'HRSAAVRERD', 'IWBQYLVQTA', 'COPSAFYYZE', 'YPFUVELLMP', 'BIOOKDFMLV', 'FCZTUMCASI', 'KFEXPJFCRY', 'MMURPIAPMU', 'JMMXFGWDWT', 'IIUJLWXFEV', 'UAZIUJDJQY', 'CQKXCOOCSH', 'JTOZHPLJTR', 'YERLYJPNLA', 'FSQDJWOAOJ', 'VCFINQHMCL', 'UKVSAEYEJB', 'EBFCWNHLIZ' ), ( 'PJMGMOXVOH', 'NASMATLIKZ', 'UVLLGWSBDD', 'VYWNQXZPVL', 'GYBDKJQKFD', 'JKCPUJJNKZ', 'AXLBKJZSZH', 'TPUXESTVTO', 'QZPRDYGIXE', 'IOEZNKCQWX', 'JMUQXLRWRF', 'MVRJNMKLID', 'ONAAUBHSPC', 'JEQWHFSGKN', 'GBTOEZKCVM', 'XTHZHSGFZM', 'LVFUVDFFQW', 'PVPKPZWPAF', 'BILMLOCYZX', 'VBAWXNNSYW' ) ); implementation end.
unit UniversalMapHandler; interface uses VoyagerInterfaces, Classes, Controls, MPlayer, UniversalMapViewer, VoyagerServerInterfaces, VCLUtils; type TUniversalMapHandler = class( TInterfacedObject, IMetaURLHandler, IURLHandler ) public constructor Create; destructor Destroy; override; private fControl : TUniversalMapView; // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( const URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; fClientView : IClientView; end; const tidMetaHandler_UniversalMapHandler = 'UniversalMapHandler'; const htmlAction_SetUserInfo = 'SETUSERINFO'; // htmlParmName_Username = 'Username'; // htmlParmName_Password = 'Password'; htmlParmName_Logon = 'Logon'; implementation uses URLParser, SysUtils, Events, ServerCnxEvents, Forms, URLUtils, ChangeLog, ClientMLS, Config, ServerCnxHandler; // TUniversalMapHandler constructor TUniversalMapHandler.Create; begin inherited Create; fControl := TUniversalMapView.Create( nil ); end; destructor TUniversalMapHandler.Destroy; begin RemoveComponentFreeAndNil(fControl); //.rag .Free; inherited; end; function TUniversalMapHandler.getName : string; begin result := tidMetaHandler_UniversalMapHandler; end; function TUniversalMapHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TUniversalMapHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TUniversalMapHandler.Instantiate : IURLHandler; begin result := self; end; function TUniversalMapHandler.HandleURL( URL : TURL ) : TURLHandlingResult; var AnchorData : TAnchorData; begin AnchorData := GetAnchorData( URL ); fControl.Logon := URLParser.StrToBoolean(URLParser.GetParmValue( URL, htmlParmName_Logon )); if AnchorData.Action = htmlAction_SetUserInfo then begin //if (fClientView = nil) // then begin fControl.Username := GetParmValue( URL, htmlParmName_Username ); fControl.MasterUser := GetParmValue( URL, htmlParmName_MasterUserName ); // end // else // begin // fControl.Username := fClientView.getUserName; // fControl.MasterUser := fClientView.getUserMasterName; end; fControl.Password := GetParmValue( URL, htmlParmName_Password ); fControl.Start; end; result := urlHandled; end; function TUniversalMapHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; { var cachepath : string; fConfigHolder : IConfigHolder;} begin result := evnHandled; case EventId of evnHandlerExposed : begin fMasterURLHandler.HandleEvent( evnAnswerClientView, fClientView ); if fClientView <> nil then begin fControl.Username := fClientView.getUserName; fControl.Password := fClientView.getUserPassword; fControl.Start; end; { fMasterURLHandler.HandleEvent( evnAnswerPrivateCache, cachepath ); fMasterURLHandler.HandleEvent( evnAnswerConfigHolder, fConfigHolder ); ChangeLogView.LogPath := cachepath + 'news\news' + ActiveLanguage + '.rtf'; if not FileExists( ChangeLogView.LogPath ) then ChangeLogView.LogPath := cachepath + 'news\news0.rtf'; ChangeLogView.LastEntry := fConfigHolder.ReadInteger( false, fClientView.getUserMasterName, 'LastNewsEntry', 0 ); ChangeLogView.RenderNews; if ChangeLogView.NewEntries and (ChangeLogView.ShowModal = mrOk) then fConfigHolder.WriteInteger( false, fClientView.getUserMasterName, 'LastNewsEntry', ChangeLogView.LastEntry ); } end; evnHandlerUnexposed: fControl.RemoveWeb; evnLogonCompleted : begin fControl.Jump.Enabled := true; fControl.EnableDblClick := true; end; evnShutDown : //.rag begin fMasterURLHandler := nil; fClientView := nil; RemoveComponentFreeAndNil(fControl); //.rag .Free; end; end; end; function TUniversalMapHandler.getControl : TControl; begin result := fControl; end; procedure TUniversalMapHandler.setMasterURLHandler( const URLHandler : IMasterURLHandler ); var cache : string; begin fMasterURLHandler := URLHandler; fControl.MasterURLHandler := URLHandler; URLHandler.HandleEvent( evnAnswerPrivateCache, cache ); fControl.Cache := cache; end; end.
program const_circle (input,output); const PI = 3.141592654; var r, d, c : real; {variable declaration: radius, dia, circumference} begin d := 2 * r; c := PI * d; end.
unit Billing; interface uses JunoApi4Delphi.Interfaces; type TBilling<T : IInterface> = class(TInterfacedObject, iBilling<T>) private [weak] FParent : T; FEmail : String; FName : String; FDocument : String; FStreet : String; FNumber : String; FComplement : String; FNeighborhood : String; FCity : String; FState : String; FPostCode : String; public constructor Create(Parent : T); destructor Destroy; override; class function New(Parent : T) : iBilling<T>; function Email(Value : String) : iBilling<T>; overload; function Email : String; overload; function Name(Value : String) : iBilling<T>; overload; function Name : String; overload; function Document(Value : String) : iBilling<T>; overload; function Document : String; overload; function Street(Value : String) : iBilling<T>; overload; function Street : String; overload; function Number(Value : String) : iBilling<T>; overload; function Number : String; overload; function Complement(Value : String) : iBilling<T>; overload; function Complement : String; overload; function Neighborhood(Value : String) : iBilling<T>; overload; function Neighborhood : String; overload; function City(Value : String) : iBilling<T>; overload; function City : String; overload; function State(Value : String) : iBilling<T>; overload; function State : String; overload; function PostCode(Value : String) : iBilling<T>; overload; function PostCode : String; overload; function &End : T; end; implementation { TBilling<T> } function TBilling<T>.City: String; begin Result := FCity; end; function TBilling<T>.City(Value: String): iBilling<T>; begin Result := Self; FCity := Value; end; function TBilling<T>.Complement: String; begin Result := FComplement; end; function TBilling<T>.Complement(Value: String): iBilling<T>; begin Result := Self; FComplement := Value; end; constructor TBilling<T>.Create(Parent: T); begin FParent := Parent; end; destructor TBilling<T>.Destroy; begin inherited; end; function TBilling<T>.Document(Value: String): iBilling<T>; begin Result := Self; FDocument := Value; end; function TBilling<T>.Document: String; begin Result := FDocument; end; function TBilling<T>.Email: String; begin Result := FEmail; end; function TBilling<T>.Email(Value: String): iBilling<T>; begin Result := Self; FEmail := Value; end; function TBilling<T>.&End: T; begin Result := FParent; end; function TBilling<T>.Neighborhood(Value: String): iBilling<T>; begin Result := Self; FNeighborhood := Value; end; function TBilling<T>.Name(Value: String): iBilling<T>; begin Result := Self; FName := Value; end; function TBilling<T>.Name: String; begin Result := FName; end; function TBilling<T>.Neighborhood: String; begin Result := FNeighborhood; end; class function TBilling<T>.New(Parent: T): iBilling<T>; begin Result := Self.Create(Parent); end; function TBilling<T>.Number: String; begin Result := FNumber; end; function TBilling<T>.Number(Value: String): iBilling<T>; begin Result := Self; FNumber := Value; end; function TBilling<T>.PostCode(Value: String): iBilling<T>; begin Result := Self; FPostCode := Value; end; function TBilling<T>.PostCode: String; begin Result := FPostCode; end; function TBilling<T>.State(Value: String): iBilling<T>; begin Result := Self; FState := Value; end; function TBilling<T>.State: String; begin Result := FState; end; function TBilling<T>.Street(Value: String): iBilling<T>; begin Result := Self; FStreet := Value; end; function TBilling<T>.Street: String; begin Result := FStreet; end; end.
unit PlansService; interface uses JunoApi4Delphi.Interfaces, Data.DB, System.JSON, REST.Response.Adapter; type TPlansService = class(TInterfacedObject, iPlans) private FParent : iJunoApi4DelphiConig; FAuth : iAuthorizationService; FJSON : TJSONObject; public constructor Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService); destructor Destroy; override; class function New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iPlans; function CratePlan : iPlans; function Name(Value : String) : iPlans; function Amount(Value : Double) : iPlans; function EndCreatePlan(Value : TDataSet) : iPlans; overload; function EndCreatePlan : String; overload; function GetPlans(Value : TDataSet) : iPlans; overload; function GetPlans : String; overload; function GetPlan(Value : String; dtValue : TDataSet): iPlans; overload; function GetPlan(Value : String) : String; overload; function DeactivePlan(Value : String; dtValue : TDataSet) : iPlans; overload; function DeactivePlan(Value : String) : String; overload; function ActivePlan(Value : String; dtValue : TDataSet) : iPlans; overload; function ActivePlan(Value : String) : String; overload; end; implementation uses RESTRequest4D, REST.Types, System.SysUtils; CONST PLAN_ENDPOINT = '/plans'; { TPlansService } function TPlansService.ActivePlan(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT +'/'+ Value +'/activation') .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; end; function TPlansService.ActivePlan(Value: String; dtValue: TDataSet): iPlans; var lJSONObj : TJSONObject; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT +'/'+ Value +'/activation') .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := dtValue; lConv.UpdateDataSet(lJSONObj); finally lConv.Free; end; end; function TPlansService.Amount(Value: Double): iPlans; begin Result := Self; FJSON.AddPair('amount', TJSONNumber.Create(Value)); end; function TPlansService.DeactivePlan(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT +'/'+ Value +'/deactivation') .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; end; function TPlansService.DeactivePlan(Value: String; dtValue: TDataSet): iPlans; var lJSONObj : TJSONObject; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT +'/'+ Value +'/deactivation') .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := dtValue; lConv.UpdateDataSet(lJSONObj); finally lConv.Free; end; end; function TPlansService.CratePlan: iPlans; begin Result := Self; end; constructor TPlansService.Create(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService); begin FParent := Parent; FAuth := AuthService; FJSON := TJSONObject.Create; end; destructor TPlansService.Destroy; begin inherited; end; function TPlansService.EndCreatePlan(Value: TDataSet): iPlans; var lJSONObj : TJSONObject; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT) .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := Value; lConv.UpdateDataSet(lJSONObj); finally lConv.Free; end; end; function TPlansService.EndCreatePlan: String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT) .Accept('application/json') .Token(FAuth.Token) .AddBody('application/json',ctAPPLICATION_JSON) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .AddParam('body', FJSON.ToString, pkREQUESTBODY) .Post.Content end; function TPlansService.GetPlan(Value: String): String; begin Result := TRequest.New .BaseURL(FParent.AuthorizationEndpoint + PLAN_ENDPOINT + '/'+Value) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; end; function TPlansService.GetPlan(Value: String; dtValue: TDataSet): iPlans; var lJSONObj : TJSONObject; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.AuthorizationEndpoint + PLAN_ENDPOINT + '/'+Value) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := dtValue; lConv.UpdateDataSet(lJSONObj); finally lConv.Free; end; end; function TPlansService.GetPlans: String; begin Result := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; end; function TPlansService.GetPlans(Value: TDataSet): iPlans; var lJSONObj : TJSONObject; lJSONArray : TJSONArray; jv : TJSONValue; lConv : TCustomJSONDataSetAdapter; lJSON : String; begin Result := Self; lJSON := TRequest.New .BaseURL(FParent.ResourceEndpoint + PLAN_ENDPOINT) .Token(FAuth.Token) .AddParam('X-Api-Version','2',pkHTTPHEADER) .AddParam('X-Resource-Token', FParent.ResourceToken, pkHTTPHEADER) .Get.Content; lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject; jv := lJSONObj.Get('_embedded').JsonValue; lJSONObj := jv as TJSONObject; lJSONArray := lJSONObj.Get('plans').JsonValue as TJSONArray; lConv := TCustomJSONDataSetAdapter.Create(nil); try lConv.DataSet := Value; lConv.UpdateDataSet(lJSONArray); finally lConv.Free; end; end; function TPlansService.Name(Value: String): iPlans; begin Result := Self; FJson.AddPair('name', Value); end; class function TPlansService.New(Parent : iJunoApi4DelphiConig; AuthService : iAuthorizationService) : iPlans; begin Result := Self.Create(Parent, AuthService); end; end.
unit Main; interface uses Thermostat.Classes, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls; type TFormMain = class(TForm) TrackBarSampleTemp: TTrackBar; Label1: TLabel; Label2: TLabel; TrackBarTargetTemp: TTrackBar; LabelHeater: TLabel; ButtonStartStop: TButton; RadioGroupWaterLevel: TRadioGroup; Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure TrackBarTempChange(Sender: TObject); procedure RadioGroupWaterLevelClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure ButtonStartStopClick(Sender: TObject); private FThermostat: TThermostat; procedure UpdateSampleTemperature; procedure EnableControls; procedure TrackBarFromTemp(TrackBar: TTrackBar; Temp: Integer); function TempFromTrackBar(TrackBar: TTrackBar): Integer; //procedure SetControlWaterLevel(Value: TWaterLevel); function GetControlWaterLevel: TWaterLevel; procedure SetCaptionButtonStartStop; procedure SetLabelHeater; public property Thermostat: TThermostat read FThermostat; end; var FormMain: TFormMain; implementation {$R *.dfm} { TFormMain } procedure TFormMain.ButtonStartStopClick(Sender: TObject); begin Thermostat.Active := not Thermostat.Active; end; procedure TFormMain.EnableControls; begin ButtonStartStop.Enabled := (Thermostat.WaterLevel = waterlevelOk); end; procedure TFormMain.FormCreate(Sender: TObject); begin FThermostat := TThermostat.Create; Thermostat.TargetTemperature := 40 + Random(40); Thermostat.SampleTemperature := Random(100); TrackBarFromTemp(TrackBarSampleTemp, Thermostat.SampleTemperature); TrackBarFromTemp(TrackBarTargetTemp, Thermostat.TargetTemperature); EnableControls; end; function TFormMain.GetControlWaterLevel: TWaterLevel; begin Result := TWaterLevel(RadioGroupWaterLevel.ItemIndex); end; procedure TFormMain.RadioGroupWaterLevelClick(Sender: TObject); begin Thermostat.WaterLevel := GetControlWaterLevel; end; procedure TFormMain.SetCaptionButtonStartStop; begin if Thermostat.Active then ButtonStartStop.Caption := 'Stop' else ButtonStartStop.Caption := 'Start'; end; //procedure TFormMain.SetControlWaterLevel(Value: TWaterLevel); //begin // RadioGroupWaterLevel.ItemIndex := Ord(Value); //end; procedure TFormMain.SetLabelHeater; begin if Thermostat.Heater then begin LabelHeater.Caption := 'Heater: ON'; LabelHeater.Font.Color := clGreen; end else begin LabelHeater.Caption := 'Heater: OFF'; LabelHeater.Font.Color := clWindowText; end; end; function TFormMain.TempFromTrackBar(TrackBar: TTrackBar): Integer; begin Result := TrackBar.Max - TrackBar.Position; end; procedure TFormMain.Timer1Timer(Sender: TObject); begin UpdateSampleTemperature; Thermostat.Run; EnableControls; SetCaptionButtonStartStop; SetLabelHeater; end; procedure TFormMain.TrackBarFromTemp(TrackBar: TTrackBar; Temp: Integer); begin TrackBar.Position := TrackBar.Max - Temp; end; procedure TFormMain.TrackBarTempChange(Sender: TObject); begin if Sender = TrackBarSampleTemp then Thermostat.SampleTemperature := TempFromTrackBar(TTrackBar(Sender)) else if Sender = TrackBarTargetTemp then Thermostat.TargetTemperature := TempFromTrackBar(TTrackBar(Sender)); end; procedure TFormMain.UpdateSampleTemperature; begin if Thermostat.Heater then Thermostat.SampleTemperature := Thermostat.SampleTemperature + 1 else Thermostat.SampleTemperature := Thermostat.SampleTemperature - 1; TrackBarFromTemp(TrackBarSampleTemp, Thermostat.SampleTemperature); end; end.
unit ExtAILog; interface uses Windows, Messages, SysUtils, Variants, Classes; type TLogEvent = procedure (const aText: string) of object; TLogIDEvent = procedure (const aText: string; const aID: Byte) of object; // Global logger TExtAILog = class private fSynchronize: Boolean; fID: Byte; fOnLog: TLogEvent; fOnIDLog: TLogIDEvent; public constructor Create(aOnLog: TLogEvent; aSynchronize: Boolean = True); overload; constructor Create(aOnLogID: TLogIDEvent; aID: Byte; aSynchronize: Boolean = True); overload; destructor Destroy(); override; procedure Log(const aText: string); overload; procedure Log(const aText: string; const aArgs: array of const); overload; end; var gLog: TExtAILog; implementation { TLog } constructor TExtAILog.Create(aOnLog: TLogEvent; aSynchronize: Boolean = True); begin Inherited Create; fSynchronize := aSynchronize; fID := 0; fOnLog := aOnLog; fOnIDLog := nil; Log('TExtAILog-Create'); end; constructor TExtAILog.Create(aOnLogID: TLogIDEvent; aID: Byte; aSynchronize: Boolean = True); begin Inherited Create; fSynchronize := aSynchronize; fID := aID; fOnLog := nil; fOnIDLog := aOnLogID; Log('TExtAILog-Create'); end; destructor TExtAILog.Destroy(); begin Log('TExtAILog-Destroy'); Inherited; end; procedure TExtAILog.Log(const aText: string); begin if (Self = nil) then Exit; if Assigned(fOnLog) then begin // Logs in DLLs do not need to synchronize because they are stored to buffer if not fSynchronize then fOnLog(aText) else // Logs in threads need to synchronize because they are stored to GUI in a different thread TThread.Synchronize(nil, procedure begin fOnLog(aText); end ) end else if Assigned(fOnIDLog) then begin if not fSynchronize then fOnIDLog(aText, fID) else TThread.Synchronize(nil, procedure begin fOnIDLog(aText, fID); end ); end; end; procedure TExtAILog.Log(const aText: string; const aArgs: array of const); begin if (Self = nil) then Exit; Log(Format(aText, aArgs)); end; end.
unit CameraConfigurationUtils; interface uses System.Classes, System.SysUtils, Fmx.Forms, Fmx.Dialogs, Androidapi.JNI.Hardware, Androidapi.JNI.JavaTypes, Androidapi.Helpers; type TCameraConfigurationUtils = class sealed private class function findSettableValue(name: string; const supportedValues: JList; desiredValues: TArray<JString>): JString; public class procedure setVideoStabilization(parameters: JCamera_Parameters); static; class procedure setBarcodeSceneMode(parameters: JCamera_Parameters); static; end; implementation { TCameraConfigurationUtils } class function TCameraConfigurationUtils.findSettableValue(name: string; const supportedValues: JList; desiredValues: TArray<JString>): JString; var desiredValue: JString; s: string; I: Integer; begin if supportedValues <> nil then begin for desiredValue in desiredValues do begin if supportedValues.contains( desiredValue) then Exit(desiredValue); end; end; Result := nil; end; class procedure TCameraConfigurationUtils.setBarcodeSceneMode(parameters: JCamera_Parameters ) ; var sceneMode: JString; begin if SameText(JStringToString(parameters.getSceneMode), JStringToString(TJCamera_Parameters.JavaClass.SCENE_MODE_BARCODE)) then begin // Log.i(TAG, "Barcode scene mode already set"); Exit; end; sceneMode := findSettableValue('scene mode', parameters.getSupportedSceneModes(), [TJCamera_Parameters.JavaClass.SCENE_MODE_BARCODE]); if (sceneMode <> nil) then parameters.setSceneMode(sceneMode); end; class procedure TCameraConfigurationUtils.setVideoStabilization(parameters: JCamera_Parameters); begin if (parameters.isVideoStabilizationSupported()) then begin if (parameters.getVideoStabilization()) then begin // Log.i(TAG, "Video stabilization already enabled"); end else begin // Log.i(TAG, "Enabling video stabilization..."); parameters.setVideoStabilization(true); end; end else begin // Log.i(TAG, "This device does not support video stabilization"); end; end; end.
{ lzRichEdit Copyright (C) 2010 Elson Junio elsonjunio@yahoo.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Gtk2RTFTool; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, LCLType, LCLProc, IntfGraphics, GraphType, gtk2, glib2, gdk2, pango, Gtk2Proc, Gtk2Def, gdk2pixbuf, Gtk2Globals, {Gtk2WSControls,} RTFPars_lzRichEdit, FastImage; const UnicodeBulletCode = $2022; //************Nome de Fontes ******* type TFNameC=record CharPos:Int64; FontName:Integer; end; { TFontNameC } TFontNameC= class(TObject) private FFNameC: array of TFNameC; public function Count:Cardinal; procedure Add(FName:Integer; chPos:Int64); function Get(Index: Integer): TFNameC; constructor Create; destructor Destroy; override; end; //********************************************* //************Tamanho de Fontes ******* type TFSizeC=record CharPos:Int64; FontSize:Integer; end; { TFontSizeC } TFontSizeC= class(TObject) private FFSizeC: array of TFSizeC; public function Count:Cardinal; procedure Add(FSize:Integer; chPos:Int64); function Get(Index: Integer): TFSizeC; constructor Create; destructor Destroy; override; end; //********************************************* //************Cor de Fontes ******* type TFColorC=record CharPos:Int64; FontColor:TColor; end; { TFontColorC } TFontColorC= class(TObject) private FFColorC: array of TFColorC; public function Count:Cardinal; procedure Add(FColor:TColor; chPos:Int64); function Get(Index: Integer): TFColorC; constructor Create; destructor Destroy; override; end; //********************************************* //************Estilo de Fontes ******* type TFStylesC=record CharPos:Int64; FontSTyles:TFontStyles; end; { TFontStylesC } TFontStylesC= class(TObject) private FFStylesC: array of TFStylesC; public function Count:Cardinal; procedure Add(FStyle:TFontStyles; chPos:Int64); function Get(Index: Integer): TFStylesC; constructor Create; destructor Destroy; override; end; //********************************************* //************Alinhamento de Parágrafos ******* type TAlignC=record CharPos:Int64; Alignment:TAlignment; end; { TParAlignmentC } TParAlignmentC= class(TObject) private FAlignC: array of TAlignC; public function Count:Cardinal; procedure Add(Al:TAlignment; chPos:Int64); function Get(Index: Integer): TAlignC; constructor Create; destructor Destroy; override; end; //********************************************* //************Recuos de Parágrafos ******* type TIndentC=record CharPos:Int64; LeftIndent:Integer; RightIndent: Integer; FirstIndent:Integer; end; { TParIndentC } TParIndentC= class(TObject) private FIndentC: array of TIndentC; public function Count:Cardinal; function Add(chPos:Int64):Integer; procedure AddLeftIdent(LeftIndent:Integer; chPos:Int64); procedure AddRightIndent(RightIndent:Integer; chPos:Int64); procedure AddFirstIndent(FirstIndent:Integer; chPos:Int64); function Get(Index: Integer): TIndentC; constructor Create; destructor Destroy; override; end; //********************************************* type TRTFPict = record PictType, W, H, WG, HG: integer; HEX: string; end; TRSFontAttributes = record Charset: TFontCharset; Color: TColor; Name: TFontName; Pitch: TFontPitch; fProtected: boolean; Size: integer; Style: TFontStyles; end; TRSParaAttributes = record Alignment: TAlignment; FirstIndent: integer; LeftIndent: integer; RightIndent: integer; Tab: integer; TabCount: integer; end; { TRTFSave } TRTFSave = class(TObject) protected FTextView: TWinControl; FRTFout: TStringList; Ffonttbl: TStringList; Fcolortbl: TStringList; FFontAttributes: TRSFontAttributes; private function AddFont(FontName: string): integer; function AddColor(Color: TColor): integer; function GetGTKTextBuffer(var TextBuffer: PGtkTextBuffer): boolean; function GetText(var S: string): boolean; function GetFontAttributes(const Position: integer; var FontAttributes: TRSFontAttributes): boolean; function GetParaAttributes(const Position: integer; var ParaAttributes: TRSParaAttributes): boolean; function Start: boolean; function GetImage(Picture: TPicture; Position: integer): boolean; public procedure SaveToStream(Stream: TStream); constructor Create(TextView: TWinControl); destructor Destroy; override; end; { TRTFRead } TRTFRead = class private FRTFParser: TRTFParser; FTextView: TWinControl; RTFPict: TRTFPict; FIsPict: boolean; FGroups: integer; FSkipGroup: integer; //-- FGFontAttributes: array of TRSFontAttributes; //-- {FGUl:Integer; FGcf:Integer; FGB:Integer; FGI:Integer;} //-- FParAlignmentC: TParAlignmentC; FParIndentC: TParIndentC; FFontNameC: TFontNameC; FFontSizeC: TFontSizeC; FFontColorC: TFontColorC; FFontStylesC: TFontStylesC; //-- FFontStyles:TFontStyles; //-- Buffer: PGtkTextBuffer; //-- private function GetGTKTextBuffer(var TextBuffer: PGtkTextBuffer): boolean; function GetText(var S: string): boolean; function GetLenText: integer; procedure InsertPosLastChar(C: TUTF8Char); function GetRealTextBuf: string; procedure SetFormat(const iSelStart, iSelEnd: integer; TextBuffer: PGtkTextBuffer; Tag: Pointer); //-- procedure SetFirstIndent(CharStart: integer; Value: Integer; CharEnd: integer); procedure SetLeftIndent(CharStart: integer; Value: Integer; CharEnd: integer); procedure SetRightIndent(CharStart: integer; Value: Integer; CharEnd: integer); procedure SetAlignment(CharStart: integer; Value: TAlignment; CharEnd: integer); procedure SetFontName(CharStart: integer; Value: TFontName; CharEnd: integer); procedure SetFontSize(CharStart: integer; Value: Integer; CharEnd: integer); procedure SetFontStyles(CharStart: integer; Value: TFontStyles; CharEnd: integer); procedure SetFontColor(CharStart: integer; Value: TColor; CharEnd: integer); //-- procedure SetTextAttributes(Pos: integer; Value: TRSFontAttributes; LPos: integer = 1); procedure InsertImage(Image: TPicture); private procedure DoGroup; procedure DoWrite; procedure DoCtrl; //-- procedure DoSpecialChar; procedure DoParAttr; procedure DoCharAttr; procedure DoPictAttr; procedure DoBeginPict; procedure DoEndPict; private procedure SetAlignmentC; procedure SetIndentC; procedure SetFontNameC; procedure SetFontSizeC; procedure SetStylesC; procedure SetColorC; public procedure LoadFromStream(Stream: TStream); constructor Create(TextView: TWinControl); destructor Destroy; override; end; function PNGToRTF(PNG: TPortableNetworkGraphic): string; function RTFToBMP(const S: string; DataType: integer; var Picture: TPicture; Width: integer = 0; Height: integer = 0): boolean; implementation function PNGToRTF(PNG: TPortableNetworkGraphic): string; var MemoryStream: TMemoryStream; I:Int64=0; Len: integer=0; Buf: byte = $0; begin Result := '{\pict\pngblip\picw' + IntToStr(PNG.Width * 15) + '\pich' + IntToStr(PNG.Height * 15) + '\picwgoal' + IntToStr(PNG.Width * 15) + '\pichgoal' + IntToStr(PNG.Height * 15) + UnicodeToUTF8($A); //-- MemoryStream := TMemoryStream.Create; PNG.SaveToStream(MemoryStream); MemoryStream.Seek(0, soBeginning); Len := 0; //-- { for I := 0 to MemoryStream.Size do begin if Len = 39 then begin Result := Result + UnicodeToUTF8($A); Len := 0; end; MemoryStream.Read(Buf, 1); Result := Result + LowerCase(IntToHex(Buf, 2)); Len := Len + 1; end;} //-- while I <= MemoryStream.Size do begin if Len = 39 then begin Result := Result + UnicodeToUTF8($A); Len := 0; end; MemoryStream.Read(Buf, 1); Result := Result + LowerCase(IntToHex(Buf, 2)); Len := Len + 1; Inc(I); end; //-- MemoryStream.Free; Result := Result + '}'; end; function RTFToBMP(const S: string; DataType: integer; var Picture: TPicture; Width: integer; Height: integer): boolean; var MStream: TMemoryStream; Pict: TPicture; I: integer = 1; B: byte = 0; L: integer; S2: string; begin Result := False; MStream := TMemoryStream.Create; MStream.Seek(0, soBeginning); L := UTF8Length(S); while True do begin S2 := S[I] + S[I + 1]; if (S2 <> '') then B := StrToInt('$' + trim(S2)) else B := $0; MStream.Write(B, 1); I := I + 2; if (I > L) then Break; end; if DataType = 18 then begin MStream.Seek(0, soBeginning); if (Width = 0) and (Height = 0) then Picture.PNG.LoadFromStream(MStream) else begin Pict := TPicture.Create; Pict.PNG.LoadFromStream(MStream); //-- Picture.PNG.Width := Width div 15; Picture.PNG.Height := Height div 15; Picture.PNG.Clear; Picture.PNG.Clear; //-- Picture.PNG.Canvas.CopyRect(Rect(0, 0, Width div 15, Height div 15), Pict.PNG.Canvas, Rect(0, 0, Pict.PNG.Width, Pict.PNG.Height)); Pict.Free; end; Result := True; end; MStream.Free; end; { TFontColorC } function TFontColorC.Count: Cardinal; begin Result:= Length(FFColorC); end; procedure TFontColorC.Add(FColor: TColor; chPos: Int64); var I:Integer=0; begin {for I:= 0 to Count -1 do begin if FFColorC[I].CharPos = chPos then begin FFColorC[I].FontColor:= FColor; Exit; end; end;} while I < Count do begin if FFColorC[I].CharPos = chPos then begin FFColorC[I].FontColor:= FColor; Exit; end; Inc(I); end; SetLength(FFColorC, Count + 1); FFColorC[Count -1].FontColor:= FColor; FFColorC[Count -1].CharPos:= chPos; end; function TFontColorC.Get(Index: Integer): TFColorC; begin Result.CharPos:= FFColorC[Index].CharPos; Result.FontColor:= FFColorC[Index].FontColor; end; constructor TFontColorC.Create; begin SetLength(FFColorC, 0); end; destructor TFontColorC.Destroy; begin SetLength(FFColorC, 0); inherited Destroy; end; { TFontStylesC } function TFontStylesC.Count: Cardinal; begin Result:=Length(FFStylesC); end; procedure TFontStylesC.Add(FStyle: TFontStyles; chPos: Int64); var I:Integer=0; begin {for I:= 0 to Count -1 do begin if FFStylesC[I].CharPos = chPos then begin FFStylesC[I].FontSTyles:= FStyle; Exit; end; end;} while I < Count do begin if FFStylesC[I].CharPos = chPos then begin FFStylesC[I].FontSTyles:= FStyle; Exit; end; Inc(I); end; SetLength(FFStylesC, Count + 1); FFStylesC[Count -1].FontSTyles:= FStyle; FFStylesC[Count -1].CharPos:= chPos; end; function TFontStylesC.Get(Index: Integer): TFStylesC; begin Result.CharPos:= FFStylesC[Index].CharPos; Result.FontSTyles:= FFStylesC[Index].FontSTyles; end; constructor TFontStylesC.Create; begin SetLength(FFStylesC, 0); end; destructor TFontStylesC.Destroy; begin SetLength(FFStylesC, 0); inherited Destroy; end; { TFontSizeC } function TFontSizeC.Count: Cardinal; begin Result:=Length(FFSizeC); end; procedure TFontSizeC.Add(FSize: Integer; chPos: Int64); var I:Integer=0; begin {for I:= 0 to Count -1 do begin if FFSizeC[I].CharPos = chPos then begin FFSizeC[I].FontSize:= FSize; Exit; end; end;} while I < Count do begin if FFSizeC[I].CharPos = chPos then begin FFSizeC[I].FontSize:= FSize; Exit; end; Inc(I); end; SetLength(FFSizeC, Count + 1); FFSizeC[Count -1].FontSize:= FSize; FFSizeC[Count -1].CharPos:= chPos; end; function TFontSizeC.Get(Index: Integer): TFSizeC; begin Result.CharPos:= FFSizeC[Index].CharPos; Result.FontSize:= FFSizeC[Index].FontSize; end; constructor TFontSizeC.Create; begin SetLength(FFSizeC, 0); end; destructor TFontSizeC.Destroy; begin SetLength(FFSizeC, 0); inherited Destroy; end; { TFontNameC } function TFontNameC.Count: Cardinal; begin Result:= Length(FFNameC); end; procedure TFontNameC.Add(FName: Integer; chPos: Int64); var I:Integer=0; begin {for I:= 0 to Count -1 do begin if FFNameC[I].CharPos = chPos then begin FFNameC[I].FontName:= FName; Exit; end; end;} while I < Count do begin if FFNameC[I].CharPos = chPos then begin FFNameC[I].FontName:= FName; Exit; end; Inc(I); end; SetLength(FFNameC, Count + 1); FFNameC[Count -1].FontName:= FName; FFNameC[Count -1].CharPos:= chPos; end; function TFontNameC.Get(Index: Integer): TFNameC; begin Result.CharPos:= FFNameC[Index].CharPos; Result.FontName:= FFNameC[Index].FontName; end; constructor TFontNameC.Create; begin SetLength(FFNameC, 0); end; destructor TFontNameC.Destroy; begin SetLength(FFNameC, 0); inherited Destroy; end; { TParIndentC } function TParIndentC.Count: Cardinal; begin Result:= Length(FIndentC); end; function TParIndentC.Add(chPos: Int64): Integer; var I:Integer=0; begin {for I:= 0 to Count -1 do if FIndentC[I].CharPos = chPos then begin Result:= I; Exit; end;} //-- while I < Count do begin if FIndentC[I].CharPos = chPos then begin Result:= I; Exit; end; Inc(I); end; SetLength(FIndentC, Count + 1); FIndentC[Count -1].CharPos:= chPos; Result:= Count -1; end; procedure TParIndentC.AddLeftIdent(LeftIndent: Integer; chPos: Int64); var Index: Integer; begin Index:= Add(chPos); FIndentC[Index].LeftIndent:= LeftIndent; end; procedure TParIndentC.AddRightIndent(RightIndent: Integer; chPos: Int64); var Index: Integer; begin Index:= Add(chPos); FIndentC[Index].RightIndent:= RightIndent; end; procedure TParIndentC.AddFirstIndent(FirstIndent: Integer; chPos: Int64); var Index: Integer; begin Index:= Add(chPos); FIndentC[Index].FirstIndent:= FirstIndent; end; function TParIndentC.Get(Index: Integer): TIndentC; begin Result.CharPos:= FIndentC[Index].CharPos; Result.LeftIndent:= FIndentC[Index].LeftIndent; Result.RightIndent:= FIndentC[Index].RightIndent; Result.FirstIndent:= FIndentC[Index].FirstIndent; end; constructor TParIndentC.Create; begin SetLength(FIndentC, 0); end; destructor TParIndentC.Destroy; begin SetLength(FIndentC, 0); inherited Destroy; end; { TParAlignmentC } function TParAlignmentC.Count: Cardinal; begin Result:= Length(FAlignC); end; procedure TParAlignmentC.Add(Al: TAlignment; chPos: Int64); begin SetLength(FAlignC, Count + 1); FAlignC[Count - 1].Alignment:= Al; FAlignC[Count - 1].CharPos:= chPos; end; function TParAlignmentC.Get(Index: Integer): TAlignC; begin Result.CharPos:= FAlignC[Index].CharPos; Result.Alignment:= FAlignC[Index].Alignment; end; constructor TParAlignmentC.Create; begin SetLength(FAlignC, 0); end; destructor TParAlignmentC.Destroy; begin SetLength(FAlignC, 0); inherited Destroy; end; { TRTFRead } function TRTFRead.GetGTKTextBuffer(var TextBuffer: PGtkTextBuffer): boolean; var AWidget: PGtkWidget; begin Result := False; //-- AWidget := PGtkWidget(FTextView.Handle); AWidget := GetWidgetInfo(AWidget, False)^.CoreWidget; if not (Assigned(AWidget)) then Exit; //-- TextBuffer := gtk_text_view_get_buffer(PGtkTextView(AWidget)); if not (Assigned(TextBuffer)) then Exit; //-- Result := True; end; function TRTFRead.GetText(var S: string): boolean; var iterStart, iterEnd: TGtkTextIter; begin Result := False; gtk_text_buffer_get_start_iter(Buffer, @iterStart); gtk_text_buffer_get_end_iter(Buffer, @iterEnd); S := gtk_text_buffer_get_slice(Buffer, @iterStart, @iterEnd, gboolean(False)); Result := True; end; function TRTFRead.GetLenText: integer; begin Result := gtk_text_buffer_get_char_count(Buffer); end; procedure TRTFRead.InsertPosLastChar(C: TUTF8Char); var iterStart: TGtkTextIter; Ch: TUTF8Char; begin Ch := C; gtk_text_buffer_get_end_iter(Buffer, @iterStart); gtk_text_buffer_insert(Buffer, @iterStart, @Ch[1], Length(Ch)); end; function TRTFRead.GetRealTextBuf: string; begin Result := ''; GetText(Result); end; procedure TRTFRead.SetFormat(const iSelStart, iSelEnd: integer; TextBuffer: PGtkTextBuffer; Tag: Pointer); var iterStart, iterEnd: TGtkTextIter; begin gtk_text_buffer_get_iter_at_offset(TextBuffer, @iterStart, iSelStart); gtk_text_buffer_get_iter_at_offset(TextBuffer, @iterEnd, iSelEnd); gtk_text_buffer_apply_tag(TextBuffer, tag, @iterStart, @iterEnd); end; procedure TRTFRead.SetFirstIndent(CharStart: integer; Value: Integer; CharEnd: integer); var Tag: Pointer = nil; begin //-- Tag := gtk_text_buffer_create_tag(buffer, nil, 'indent', [Value, 'indent-set', gboolean(gTRUE), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetLeftIndent(CharStart: integer; Value: Integer; CharEnd: integer); var Tag: Pointer = nil; begin Tag := gtk_text_buffer_create_tag(buffer, nil, 'left_margin', [Value, 'left_margin-set', gboolean(gTRUE), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetRightIndent(CharStart: integer; Value: Integer; CharEnd: integer); var Tag: Pointer = nil; begin Tag := gtk_text_buffer_create_tag(buffer, nil, 'right_margin', [Value, 'right_margin-set', gboolean(gTRUE), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetAlignment(CharStart: integer; Value: TAlignment; CharEnd: integer); const GTKJustification: array [TAlignment] of integer = (GTK_JUSTIFY_LEFT, GTK_JUSTIFY_RIGHT, GTK_JUSTIFY_CENTER); var Tag: Pointer = nil; begin Tag := gtk_text_buffer_create_tag(buffer, nil, 'justification', [GTKJustification[Value], 'justification-set', gboolean(gTRUE), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetFontName(CharStart: integer; Value: TFontName; CharEnd: integer); var Tag: Pointer = nil; begin Tag := gtk_text_buffer_create_tag(buffer, nil, 'family', [@Value[1], 'family-set', gTRUE, nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetFontSize(CharStart: integer; Value: Integer; CharEnd: integer); var Tag: Pointer = nil; begin Tag := gtk_text_buffer_create_tag(buffer, nil, 'size-points', [double(Value), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetFontStyles(CharStart: integer; Value: TFontStyles; CharEnd: integer); var Tag: Pointer = nil; const PangoUnderline: array [boolean] of integer = (PANGO_UNDERLINE_NONE, PANGO_UNDERLINE_SINGLE); PangoBold: array [boolean] of integer = (PANGO_WEIGHT_NORMAL, PANGO_WEIGHT_BOLD); PangoItalic: array [boolean] of integer = (PANGO_STYLE_NORMAL, PANGO_STYLE_ITALIC); begin //-- Tag := gtk_text_buffer_create_tag(buffer, nil, 'underline', [PangoUnderline[fsUnderline in Value], 'underline-set', gboolean(gTRUE), 'weight', PangoBold[fsBold in Value], 'weight-set', gboolean(gTRUE), 'style', PangoItalic[fsItalic in Value], 'style-set', gboolean(gTRUE), 'strikethrough', gboolean(fsStrikeOut in Value), 'strikethrough-set', gboolean(gTRUE), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetFontColor(CharStart: integer; Value: TColor; CharEnd: integer); var FontColor: TGDKColor; Tag: Pointer = nil; begin FontColor := TColortoTGDKColor(Value); Tag := gtk_text_buffer_create_tag(buffer, nil, 'foreground-gdk', [@FontColor, 'foreground-set', gboolean(gTRUE), nil]); SetFormat(CharStart, CharEnd, Buffer, Tag); end; procedure TRTFRead.SetTextAttributes(Pos: integer; Value: TRSFontAttributes; LPos: integer = 1); var FontFamily: string; FontColor: TGDKColor; Tag: Pointer = nil; const PangoUnderline: array [boolean] of integer = (PANGO_UNDERLINE_NONE, PANGO_UNDERLINE_SINGLE); PangoBold: array [boolean] of integer = (PANGO_WEIGHT_NORMAL, PANGO_WEIGHT_BOLD); PangoItalic: array [boolean] of integer = (PANGO_STYLE_NORMAL, PANGO_STYLE_ITALIC); begin FontColor := TColortoTGDKColor(Value.Color); //-- FontFamily := Value.Name; if (FontFamily = '') then FontFamily := #0; //-- Tag := gtk_text_buffer_create_tag(buffer, nil, 'family', [@FontFamily[1], 'family-set', gTRUE, 'size-points', double(Value.Size), 'foreground-gdk', @FontColor, 'foreground-set', gboolean(gTRUE), 'underline', PangoUnderline[fsUnderline in Value.Style], 'underline-set', gboolean(gTRUE), 'weight', PangoBold[fsBold in Value.Style], 'weight-set', gboolean(gTRUE), 'style', PangoItalic[fsItalic in Value.Style], 'style-set', gboolean(gTRUE), 'strikethrough', gboolean(fsStrikeOut in Value.Style), 'strikethrough-set', gboolean(gTRUE), nil]); SetFormat(Pos, LPos, Buffer, Tag); end; procedure TRTFRead.InsertImage(Image: TPicture); var iPosition: TGtkTextIter; GDIObj: PGDIObject = nil; pixbuf: PGDKPixBuf = nil; pixmap: PGdkDrawable = nil; bitmap: PGdkBitmap = nil; iWidth, iHeight: integer; begin //-- gtk_text_buffer_get_end_iter(buffer, @iPosition); //-- GDIObj := PGDIObject(Image.Bitmap.Handle); //-- case GDIObj^.GDIBitmapType of gbBitmap: begin bitmap := GDIObj^.GDIBitmapObject; gdk_drawable_get_size(bitmap, @iWidth, @iHeight); pixbuf := CreatePixbufFromDrawable(bitmap, nil, False, 0, 0, 0, 0, iWidth, iHeight); end; gbPixmap: begin pixmap := GDIObj^.GDIPixmapObject.Image; if pixmap <> nil then begin gdk_drawable_get_size(pixmap, @iWidth, @iHeight); bitmap := CreateGdkMaskBitmap(Image.Bitmap.Handle, 0); pixbuf := CreatePixbufFromImageAndMask(pixmap, 0, 0, iWidth, iHeight, nil, Bitmap); end; end; gbPixbuf: begin pixbuf := gdk_pixbuf_copy(GDIObj^.GDIPixbufObject); end; end; if (pixbuf <> nil) then gtk_text_buffer_insert_pixbuf(buffer, @iPosition, pixbuf); end; procedure TRTFRead.DoGroup; begin if (FRTFParser.RTFMajor = rtfBeginGroup) then begin FGroups := FGroups + 1; SetLength(FGFontAttributes, FGroups); if (FGroups > 1) then begin FGFontAttributes[FGroups -1].Name := FGFontAttributes[FGroups -2].Name; FGFontAttributes[FGroups -1].Color := FGFontAttributes[FGroups -2].Color; FGFontAttributes[FGroups -1].Size := FGFontAttributes[FGroups -2].Size; FGFontAttributes[FGroups -1].Style := []; //-- FFontStyles:= []; end; {FFontStylesC.Add(FGFontAttributes[FGroups -1].Style, GetLenText); FFontNameC.Add(StrToInt(FGFontAttributes[FGroups -1].Name), GetLenText); FFontSizeC.Add(FGFontAttributes[FGroups -1].Size, GetLenText); FFontColorC.Add(FGFontAttributes[FGroups -1].Color, GetLenText);} end else if (FRTFParser.RTFMajor = rtfEndGroup) then begin FGroups := FGroups - 1; SetLength(FGFontAttributes, FGroups); if (FGroups > 0) then begin FFontStylesC.Add(FGFontAttributes[FGroups -1].Style, GetLenText); FFontNameC.Add(StrToInt(FGFontAttributes[FGroups -1].Name), GetLenText); FFontSizeC.Add(FGFontAttributes[FGroups -1].Size, GetLenText); FFontColorC.Add(FGFontAttributes[FGroups -1].Color, GetLenText); end; end; if (FGroups < FSkipGroup) then FSkipGroup := -1;end; procedure TRTFRead.DoWrite; var C: TUTF8char; begin C := UnicodeToUTF8(FRTFParser.RTFMajor); if FIsPict then RTFPict.HEX := RTFPict.HEX + C else begin if (FSkipGroup = -1) and (FRTFParser.RTFMajor = 183) then begin InsertPosLastChar(UnicodeToUTF8(UnicodeBulletCode)); C := chr($0); end; if (FSkipGroup = -1) and (C <> chr($0)) then begin if C = #194 + #149 then C:= UnicodeToUTF8(UnicodeBulletCode); InsertPosLastChar(C); end; end; end; procedure TRTFRead.DoCtrl; begin case FRTFParser.RTFMajor of rtfSpecialChar: DoSpecialChar; rtfParAttr: DoParAttr; rtfCharAttr: DoCharAttr; rtfPictAttr: DoPictAttr; end; end; procedure TRTFRead.DoSpecialChar; begin case FRTFParser.rtfMinor of rtfPar: begin if (FSkipGroup = -1) then InsertPosLastChar(#10); end; rtfTab: begin if (FSkipGroup = -1) then begin InsertPosLastChar(#9); end; end; rtfOptDest: begin if (FSkipGroup = -1) then FSkipGroup := FGroups; end; end; end; procedure TRTFRead.DoParAttr; begin //-- case FRTFParser.rtfMinor of rtfParDef:begin FParIndentC.AddFirstIndent(0, GetLenText); FParIndentC.AddLeftIdent(0, GetLenText); FParIndentC.AddRightIndent(0, GetLenText); if (FGroups <= 1) then begin FParAlignmentC.Add(taLeftJustify, GetLenText); FFontColorC.Add(clWindowText, GetLenText); end; end; rtfQuadLeft: FParAlignmentC.Add(taLeftJustify, GetLenText); rtfQuadRight:FParAlignmentC.Add(taRightJustify, GetLenText); rtfQuadJust:FParAlignmentC.Add(taLeftJustify, GetLenText); rtfQuadCenter:FParAlignmentC.Add(taCenter, GetLenText); rtfFirstIndent:FParIndentC.AddFirstIndent(FRTFParser.rtfParam div 568 * 37, GetLenText); rtfLeftIndent:FParIndentC.AddLeftIdent(FRTFParser.rtfParam div 568 * 37, GetLenText); rtfRightIndent:FParIndentC.AddRightIndent(FRTFParser.rtfParam div 568 * 37, GetLenText); end; end; procedure TRTFRead.DoCharAttr; begin case FRTFParser.rtfMinor of rtfBold: begin if (FRTFParser.rtfParam <> rtfNoParam) then begin if (fsBold in FFontStyles) then FFontStyles := FFontStyles - [fsBold]; //FGB:= -1; end else begin if not(fsBold in FFontStyles) then FFontStyles := FFontStyles + [fsBold]; //FGB:= FGroups; end; FFontStylesC.Add(FFontStyles, GetLenText); FGFontAttributes[FGroups -1].Style:= FFontStyles; end; rtfItalic: begin if (FRTFParser.rtfParam <> rtfNoParam) then begin if (fsItalic in FFontStyles) then FFontStyles := FFontStyles - [fsItalic]; //FGI:= -1; end else begin if not(fsItalic in FFontStyles) then FFontStyles := FFontStyles + [fsItalic]; //FGI:= FGroups; end; FFontStylesC.Add(FFontStyles, GetLenText); FGFontAttributes[FGroups -1].Style:= FFontStyles; end; rtfStrikeThru: begin if (FRTFParser.rtfParam <> rtfNoParam) then begin if (fsStrikeOut in FFontStyles) then FFontStyles := FFontStyles - [fsStrikeOut]; end else begin if not(fsStrikeOut in FFontStyles) then FFontStyles := FFontStyles + [fsStrikeOut]; end; FFontStylesC.Add(FFontStyles, GetLenText); FGFontAttributes[FGroups -1].Style:= FFontStyles; end; rtfFontNum: begin FFontNameC.Add(FRTFParser.rtfParam, GetLenText); FGFontAttributes[FGroups -1].Name:= IntToStr(FRTFParser.rtfParam); end; rtfFontSize: begin FFontSizeC.Add(FRTFParser.rtfParam div 2, GetLenText); FGFontAttributes[FGroups -1].Size:= FRTFParser.rtfParam div 2; end; rtfUnderline: begin if not(fsUnderline in FFontStyles) then begin FFontStyles := FFontStyles + [fsUnderline]; //FGUl:= FGroups; end; FFontStylesC.Add(FFontStyles, GetLenText); FGFontAttributes[FGroups -1].Style:= FFontStyles; end; rtfNoUnderline: begin if (fsUnderline in FFontStyles) then begin FFontStyles := FFontStyles - [fsUnderline]; //FGUl:= -1; end; FFontStylesC.Add(FFontStyles, GetLenText); FGFontAttributes[FGroups -1].Style:= FFontStyles; end; rtfForeColor: begin //FGcf:= FGroups; if (FRTFParser.Colors[FRTFParser.rtfParam] = nil) or (FRTFParser.rtfParam = 0) then FFontColorC.Add(clWindowText, GetLenText) else FFontColorC.Add(RGBToColor(FRTFParser.Colors[FRTFParser.rtfParam]^.rtfCRed, FRTFParser.Colors[FRTFParser.rtfParam]^.rtfCGreen, FRTFParser.Colors[FRTFParser.rtfParam]^.rtfCBlue), GetLenText); FGFontAttributes[FGroups -1].Color:= FFontColorC.Get(FFontColorC.Count -1).FontColor; end; end; end; procedure TRTFRead.DoPictAttr; begin if (FRTFParser.rtfMajor = rtfPictAttr) and (FRTFParser.rtfMinor in [rtfMacQD .. rtfpngblip]) then case FRTFParser.rtfMinor of rtfPicWid: RTFPict.W := FRTFParser.rtfParam; rtfPicHt: RTFPict.H := FRTFParser.rtfParam; rtfPicGoalWid: RTFPict.WG := FRTFParser.rtfParam; rtfPicGoalHt: RTFPict.HG := FRTFParser.rtfParam; rtfpngblip: RTFPict.PictType := rtfpngblip; end; end; procedure TRTFRead.DoBeginPict; begin RTFPict.HEX := ''; RTFPict.H := 0; RTFPict.HG := 0; RTFPict.W := 0; RTFPict.WG := 0; RTFPict.PictType := -1; FIsPict := True; end; procedure TRTFRead.DoEndPict; var Picture: TPicture; R: boolean = False; begin FIsPict := False; Picture := TPicture.Create; if (RTFPict.WG = 0) and (RTFPict.HG = 0) or (RTFPict.WG = RTFPict.W) and (RTFPict.HG = RTFPict.H) then R := RTFToBMP(RTFPict.HEX, RTFPict.PictType, Picture) else R := RTFToBMP(RTFPict.HEX, RTFPict.PictType, Picture, RTFPict.WG, RTFPict.HG); if R then InsertImage(Picture); Picture.Free; end; procedure TRTFRead.SetAlignmentC; var I:Integer=0; ChStart:Integer = 0; ChEnd:Integer = 0; begin {for I:=0 to FParAlignmentC.Count -1 do begin ChStart:= FParAlignmentC.Get(I).CharPos; if ((I + 1) < (FParAlignmentC.Count -1)) then ChEnd:= FParAlignmentC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetAlignment(ChStart, FParAlignmentC.Get(I).Alignment, ChEnd); end;} while I < FParAlignmentC.Count do begin ChStart:= FParAlignmentC.Get(I).CharPos; if ((I + 1) < (FParAlignmentC.Count -1)) then ChEnd:= FParAlignmentC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetAlignment(ChStart, FParAlignmentC.Get(I).Alignment, ChEnd); Inc(I) end; end; procedure TRTFRead.SetIndentC; var I:Integer=0; ChStart:Integer = 0; ChEnd:Integer = 0; begin {for I:=0 to FParIndentC.Count -1 do begin ChStart:= FParIndentC.Get(I).CharPos; if ((I + 1) < (FParIndentC.Count -1)) then ChEnd:= FParIndentC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFirstIndent(ChStart, FParIndentC.Get(I).FirstIndent, ChEnd); SetLeftIndent(ChStart, FParIndentC.Get(I).LeftIndent, ChEnd); SetRightIndent(ChStart, FParIndentC.Get(I).RightIndent, ChEnd); end;} while I < FParIndentC.Count do begin ChStart:= FParIndentC.Get(I).CharPos; if ((I + 1) < (FParIndentC.Count -1)) then ChEnd:= FParIndentC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFirstIndent(ChStart, FParIndentC.Get(I).FirstIndent, ChEnd); SetLeftIndent(ChStart, FParIndentC.Get(I).LeftIndent, ChEnd); SetRightIndent(ChStart, FParIndentC.Get(I).RightIndent, ChEnd); Inc(I) end; end; procedure TRTFRead.SetFontNameC; var I:Integer=0; ChStart:Integer = 0; ChEnd:Integer = 0; begin {for I:=0 to FFontNameC.Count -1 do begin ChStart:= FFontNameC.Get(I).CharPos; if ((I + 1) < (FFontNameC.Count -1)) then ChEnd:= FFontNameC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontName(ChStart, FRTFParser.Fonts[FFontNameC.Get(I).FontName]^.rtfFName, ChEnd); end;} while I < FFontNameC.Count do begin ChStart:= FFontNameC.Get(I).CharPos; if ((I + 1) < (FFontNameC.Count -1)) then ChEnd:= FFontNameC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontName(ChStart, FRTFParser.Fonts[FFontNameC.Get(I).FontName]^.rtfFName, ChEnd); Inc(I) end; end; procedure TRTFRead.SetFontSizeC; var I:Integer=0; ChStart:Integer = 0; ChEnd:Integer = 0; begin {for I:=0 to FFontSizeC.Count -1 do begin ChStart:= FFontSizeC.Get(I).CharPos; if ((I + 1) < (FFontSizeC.Count -1)) then ChEnd:= FFontSizeC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontSize(ChStart,FFontSizeC.Get(I).FontSize , ChEnd); end;} while I < FFontSizeC.Count do begin ChStart:= FFontSizeC.Get(I).CharPos; if ((I + 1) < (FFontSizeC.Count -1)) then ChEnd:= FFontSizeC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontSize(ChStart,FFontSizeC.Get(I).FontSize , ChEnd); Inc(I) end; end; procedure TRTFRead.SetStylesC; var I:Integer=0; ChStart:Integer = 0; ChEnd:Integer = 0; begin {for I:=0 to FFontStylesC.Count -1 do begin ChStart:= FFontStylesC.Get(I).CharPos; if ((I + 1) < (FFontStylesC.Count -1)) then ChEnd:= FFontStylesC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontStyles(ChStart,FFontStylesC.Get(I).FontSTyles , ChEnd); end;} while I < FFontStylesC.Count do begin ChStart:= FFontStylesC.Get(I).CharPos; if ((I + 1) < (FFontStylesC.Count -1)) then ChEnd:= FFontStylesC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontStyles(ChStart,FFontStylesC.Get(I).FontSTyles , ChEnd); Inc(I) end; end; procedure TRTFRead.SetColorC; var I:Integer=0; ChStart:Integer = 0; ChEnd:Integer = 0; begin {for I:=0 to FFontColorC.Count -1 do begin ChStart:= FFontColorC.Get(I).CharPos; if ((I + 1) < (FFontColorC.Count -1)) then ChEnd:= FFontColorC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontColor(ChStart, FFontColorC.Get(I).FontColor , ChEnd); end;} while I < FFontColorC.Count do begin ChStart:= FFontColorC.Get(I).CharPos; if ((I + 1) < (FFontColorC.Count -1)) then ChEnd:= FFontColorC.Get(I + 1).CharPos else ChEnd:= GetLenText; //-- SetFontColor(ChStart, FFontColorC.Get(I).FontColor , ChEnd); Inc(I) end; end; procedure TRTFRead.LoadFromStream(Stream: TStream); begin //-- FGroups := 0; FSkipGroup := -1; FFontStyles:= []; //-- SetLength(FGFontAttributes, 1); FGFontAttributes[0].Color:= clWindowText; FGFontAttributes[0].Size:= 10; FGFontAttributes[0].Name:='0'; FGFontAttributes[0].Style:=[]; //-- //-- FParAlignmentC:= TParAlignmentC.Create; FParIndentC:= TParIndentC.Create; FFontNameC:= TFontNameC.Create; FFontSizeC:= TFontSizeC.Create; FFontStylesC:= TFontStylesC.Create; FFontColorC:= TFontColorC.Create; //-- FRTFParser := TRTFParser.Create(Stream); FRTFParser.classcallbacks[rtfText] := @DoWrite; FRTFParser.classcallbacks[rtfcontrol] := @DoCtrl; FRTFParser.classcallbacks[rtfGroup] := @DoGroup; FRTFParser.OnRTFBeginPict := @DoBeginPict; FRTFParser.OnRTFEndPict := @DoEndPict; FRTFParser.StartReading; //-- SetAlignmentC; SetIndentC; SetFontNameC; SetFontSizeC; SetStylesC; SetColorC; //-- FParAlignmentC.Free; FParIndentC.Free; FFontNameC.Free; FFontSizeC.Free; FFontStylesC.Free; FFontColorC.Free; //-- FRTFParser.Free; SetLength(FGFontAttributes, 0); end; constructor TRTFRead.Create(TextView: TWinControl); begin inherited Create; FTextView := TextView; FIsPict := False; GetGTKTextBuffer(Buffer); end; destructor TRTFRead.Destroy; begin inherited Destroy; end; { TRTFSave } function TRTFSave.AddFont(FontName: string): integer; var I:Integer=0; begin //if Ffonttbl.Find(FontName, Result) then // Exit; While I < Ffonttbl.Count do begin if (UTF8LowerCase(Ffonttbl[I]) = UTF8LowerCase(FontName)) then begin Result:= I; Exit; end; Inc(I); end; Result := Ffonttbl.Add(FontName); end; function TRTFSave.AddColor(Color: TColor): integer; var R, G, B: byte; Par: string; I: Integer=0; begin R := Red(Color); G := Green(Color); B := Blue(Color); Par := '\red' + IntToStr(R) + '\green' + IntToStr(G) + '\blue' + IntToStr(B); While I < FColortbl.Count do begin if (UTF8LowerCase(FColortbl[I]) = UTF8LowerCase(Par)) then begin Result:= I; Exit; end; Inc(I); end; Result := FColortbl.Add(Par); end; function TRTFSave.GetGTKTextBuffer(var TextBuffer: PGtkTextBuffer): boolean; var AWidget: PGtkWidget; begin Result := False; //-- AWidget := PGtkWidget(FTextView.Handle); AWidget := GetWidgetInfo(AWidget, False)^.CoreWidget; if not (Assigned(AWidget)) then Exit; //-- TextBuffer := gtk_text_view_get_buffer(PGtkTextView(AWidget)); if not (Assigned(TextBuffer)) then Exit; //-- Result := True; end; function TRTFSave.GetText(var S: string): boolean; var iterStart, iterEnd: TGtkTextIter; Buffer: PGtkTextBuffer = nil; begin Result := False; if not (GetGTKTextBuffer(Buffer)) then Exit; gtk_text_buffer_get_start_iter(Buffer, @iterStart); gtk_text_buffer_get_end_iter(Buffer, @iterEnd); S := gtk_text_buffer_get_slice(Buffer, @iterStart, @iterEnd, gboolean(False)); Result := True; end; function TRTFSave.GetFontAttributes(const Position: integer; var FontAttributes: TRSFontAttributes): boolean; var Buffer: PGtkTextBuffer = nil; Attributes: PGtkTextAttributes; iPosition: TGtkTextIter; begin Result := False; //-- if not (GetGTKTextBuffer(Buffer)) then Exit; //-- Attributes := gtk_text_attributes_new; if not Assigned(Attributes) then Exit; //-- gtk_text_buffer_get_iter_at_offset(buffer, @iPosition, Position); //-- if (gtk_text_iter_get_attributes(@iPosition, Attributes)) then begin FontAttributes.Name := pango_font_description_get_family(Attributes^.font); FontAttributes.Size := pango_font_description_get_size(Attributes^.font); if not (pango_font_description_get_size_is_absolute(Attributes^.font)) then FontAttributes.Size := Round(FontAttributes.Size / PANGO_SCALE); FontAttributes.Color := TGDKColorToTColor(Attributes^.appearance.fg_color); //-- FontAttributes.Style := []; //-- if (Strikethrough(Attributes^.appearance) > 0) then Include(FontAttributes.Style, fsStrikeOut); if (underline(Attributes^.appearance) > 0) then Include(FontAttributes.Style, fsUnderline); //-- if (pango_font_description_get_weight(Attributes^.font) = PANGO_WEIGHT_BOLD) then Include(FontAttributes.Style, fsBold); if (pango_font_description_get_style(Attributes^.font) = PANGO_STYLE_ITALIC) then Include(FontAttributes.Style, fsItalic); //-- Result := True; end; gtk_text_attributes_unref(Attributes); end; function TRTFSave.GetParaAttributes(const Position: integer; var ParaAttributes: TRSParaAttributes): boolean; var Buffer: PGtkTextBuffer = nil; Attributes: PGtkTextAttributes; iPosition: TGtkTextIter; begin Result := False; //-- if not (GetGTKTextBuffer(Buffer)) then Exit; //-- Attributes := gtk_text_attributes_new; if not Assigned(Attributes) then Exit; //-- gtk_text_buffer_get_iter_at_offset(buffer, @iPosition, Position); //-- if (gtk_text_iter_get_attributes(@iPosition, Attributes)) then begin case Attributes^.justification of GTK_JUSTIFY_LEFT: ParaAttributes.Alignment := taLeftJustify; GTK_JUSTIFY_RIGHT: ParaAttributes.Alignment := taRightJustify; GTK_JUSTIFY_CENTER: ParaAttributes.Alignment := taCenter; end; //-- ParaAttributes.LeftIndent := Attributes^.left_margin div 37; ParaAttributes.RightIndent := Attributes^.right_margin div 37; ParaAttributes.FirstIndent := Attributes^.indent div 37; //-- Result := True; end; gtk_text_attributes_unref(Attributes); end; function TRTFSave.Start: boolean; var S: String=''; TextLen, I: Integer; IChar: Integer=1; CharLen: Integer; UChar: TUTF8Char; Line: String; LineCount: Integer=0; CodChar: Cardinal; TmpCodChar: Cardinal; TmpChar: TUTF8Char; NPara:Boolean=True; ParaAttributes: TRSParaAttributes; FontAttributes: TRSFontAttributes; Space: Boolean=False; Picture: TPicture; begin Result:= False; //--Pega o texto no controle if not(GetText(S)) then Exit; //-- FRTFout.Clear; Picture:= TPicture.Create; //-- TextLen:= UTF8Length(S); //-- FRTFout.Text:= '\pard'; //-- // for IChar:=1 to TextLen do while IChar <= TextLen do begin UChar:= UTF8Copy(S, IChar, 1); CodChar:= UTF8CharacterToUnicode(@UChar[1], CharLen); if CodChar = $0 then begin UChar:= ''; end; //-- //Novo Parágrafo if (CodChar=$A) then begin //-- if (fsBold in FFontAttributes.Style) then FRTFout[FRTFout.Count -1]:= FRTFout[FRTFout.Count -1] + '\b0'; if (fsItalic in FFontAttributes.Style) then FRTFout[FRTFout.Count -1]:= FRTFout[FRTFout.Count -1] + '\i0'; if (fsUnderline in FFontAttributes.Style) then FRTFout[FRTFout.Count -1]:= FRTFout[FRTFout.Count -1] + '\ulnone'; //-- FFontAttributes.Style:= []; //-- FRTFout[FRTFout.Count -1]:= FRTFout[FRTFout.Count -1] + '\par'; FRTFout.Add('\pard'); //-- LineCount:= FRTFout.Count -1; //-- NPara:= True; end; //--- if (NPara) then begin //Resolve todas as questões do parágrafo // //-- Inicializa atributos de parágrafo ParaAttributes.LeftIndent:= 0; ParaAttributes.RightIndent:= 0; ParaAttributes.FirstIndent:= 0; ParaAttributes.Alignment:= taLeftJustify; //Pega as propriedades do parágrafo if (IChar > 1) then GetParaAttributes(IChar + 1, ParaAttributes) else GetParaAttributes(1, ParaAttributes); //Coloca o alinhamento case ParaAttributes.Alignment of taRightJustify: FRTFout[LineCount]:= FRTFout[LineCount] + '\qr'; taCenter: FRTFout[LineCount]:= FRTFout[LineCount] + '\qc'; end; //Verifica se é um marcador if (TextLen > IChar) and (UTF8Copy(S, IChar + 1, 1) = UnicodeToUTF8(UnicodeBulletCode)) or (IChar=1) and (UTF8Copy(S, 1, 1) = UnicodeToUTF8(UnicodeBulletCode)) then begin //Insere o código para marcador em RTF //FRTFout[LineCount]:= FRTFout[LineCount] + '{\pntext\f' + IntToStr(AddFont('Symbol')) + '\''B7\tab}{\*\pn\pnlvlblt\pnf' + IntToStr(AddFont('Symbol')) + '\pnindent0{\pntxtb\''B7}}'; {if ParaAttributes.LeftIndent >0 then ParaAttributes.LeftIndent:= ParaAttributes.LeftIndent -1;} if (TextLen > IChar + 2) and (UTF8Copy(S, IChar + 2, 1) = UnicodeToUTF8($9))then begin UTF8Delete(S, IChar + 2, 1); UTF8Insert(UnicodeToUTF8($0), S, IChar + 2); end; end; //Parâmetros de identação if (ParaAttributes.LeftIndent > 0) then FRTFout[LineCount]:= FRTFout[LineCount] + '\li' + IntToStr(ParaAttributes.LeftIndent * 568); if (ParaAttributes.RightIndent > 0) then FRTFout[LineCount]:= FRTFout[LineCount] + '\ri' + IntToStr(ParaAttributes.RightIndent * 568); if (ParaAttributes.FirstIndent > 0) then FRTFout[LineCount]:= FRTFout[LineCount] + '\fi' + IntToStr(ParaAttributes.FirstIndent * 568); //Verifica se é um marcador if (TextLen > IChar) and (UTF8Copy(S, IChar + 1, 1) = UnicodeToUTF8(UnicodeBulletCode)) or (IChar=1) and (UTF8Copy(S, 1, 1) = UnicodeToUTF8(UnicodeBulletCode)) then begin //Insere o código para marcador em RTF FRTFout[LineCount]:= FRTFout[LineCount] + '{\pntext\f' + IntToStr(AddFont('Symbol')) + '\''B7\tab}{\*\pn\pnlvlblt\pnf' + IntToStr(AddFont('Symbol')) + '\pnindent0{\pntxtb\''B7}}'; end; //-- //NPara:= False; end; //-- //Propriedades do Texto //-- FontAttributes.Name:='Sans'; FontAttributes.Size:=10; FontAttributes.Style:=[]; FontAttributes.Color:=clWindowText; //-- GetFontAttributes(IChar -1, FontAttributes); //-- if (FontAttributes.Name <> FFontAttributes.Name) or (NPara) then begin FRTFout[LineCount]:= FRTFout[LineCount] + '\f' + IntToStr(AddFont(FontAttributes.Name)); FFontAttributes.Name := FontAttributes.Name; Space := True; end; if (FontAttributes.Size <> FFontAttributes.Size) or (NPara) then begin FRTFout[LineCount]:= FRTFout[LineCount] + '\fs' + IntToStr(FontAttributes.Size * 2); FFontAttributes.Size := FontAttributes.Size; Space := True; end; if (FontAttributes.Color <> FFontAttributes.Color) or (NPara) then begin FRTFout[LineCount]:= FRTFout[LineCount] + '\cf' + IntToStr(AddColor(FontAttributes.Color)); FFontAttributes.Color := FontAttributes.Color; Space := True; end; //------ if (fsBold in FontAttributes.Style) and not(fsBold in FFontAttributes.Style) then FRTFout[LineCount]:= FRTFout[LineCount] + '\b' else if (fsBold in FFontAttributes.Style) and not(fsBold in FontAttributes.Style) then FRTFout[LineCount]:= FRTFout[LineCount] + '\b0'; //-- if (fsItalic in FontAttributes.Style) and not(fsItalic in FFontAttributes.Style) then FRTFout[LineCount]:= FRTFout[LineCount] + '\i' else if (fsItalic in FFontAttributes.Style) and not(fsItalic in FontAttributes.Style) then FRTFout[LineCount]:= FRTFout[LineCount] + '\i0'; //-- if (fsUnderline in FontAttributes.Style) and not(fsUnderline in FFontAttributes.Style) then FRTFout[LineCount]:= FRTFout[LineCount] + '\ul' else if (fsUnderline in FFontAttributes.Style) and not(fsUnderline in FontAttributes.Style) then FRTFout[LineCount]:= FRTFout[LineCount] + '\ulnone'; //-- if FFontAttributes.Style <> FontAttributes.Style then Space:= true; FFontAttributes.Style := FontAttributes.Style; //------- if (CodChar= UnicodeBulletCode) or (CodChar= $A) then begin UChar:=''; CodChar:=$0; end; //--- //Imagens if CodChar = $FFFC then begin Picture.Clear; GetImage(Picture, IChar -1); FRTFout[LineCount]:= FRTFout[LineCount] + PNGToRTF(Picture.PNG); UChar:= ''; CodChar:=$0; end; //-- //Tratamento de caracteres //TAB if CodChar = $9 then begin FRTFout[LineCount]:= FRTFout[LineCount] + '\tab'; UChar:= ''; CodChar:=$0; Space := True; end; //-- //--Caracteres com código maior que 160 if (CodChar > $A0) then begin FRTFout[LineCount]:= FRTFout[LineCount] + '\''' + UTF8LowerCase(IntToHex(CodChar, 2)); UChar:= ''; CodChar:=$0; end; //Simbolos especiais if (UChar = '\') or (UChar = '{') or (UChar = '}') then FRTFout[LineCount]:= FRTFout[LineCount] + '\'; //-- if Space then begin Space:= False; FRTFout[LineCount]:= FRTFout[LineCount] + ' '; end; //-- FRTFout[LineCount]:= FRTFout[LineCount] + UChar; NPara:= False; Inc(IChar); end; //Finaliza paragrafo FRTFout[LineCount]:= FRTFout[LineCount] + '\par'; //------- //Finaliza a montágem do arquivo Line := '{\rtf1\ansi\deff0\adeflang1025{\fonttbl '; {for I := 0 to (Ffonttbl.Count - 1) do begin Line := Line + '{\f' + IntToStr(I) + '\fswiss ' + Ffonttbl[I] + ';}'; end;} I:=0; While I < Ffonttbl.Count do begin Line := Line + '{\f' + IntToStr(I) + '\fswiss ' + Ffonttbl[I] + ';}'; Inc(I); end; Line := Line + '}'; Line := Line + UnicodeToUTF8($A); if (Fcolortbl.Count > 1) then begin Line := Line + '{\colortbl '; {for I := 1 to (Fcolortbl.Count - 1) do begin Line := Line + ';' + Fcolortbl[I]; end;} I:=1; While I < Fcolortbl.Count do begin Line := Line + ';' + Fcolortbl[I]; Inc(I); end; Line := Line + ';}' + UnicodeToUTF8($A); end; Line := Line + '{\*\generator RTFTool 1.0;}\viewkind4'; //-- FRTFout.Insert(0, Line); FRTFout.Add('}'); Picture.Free; Result:= True; end; function TRTFSave.GetImage(Picture: TPicture; Position: integer): boolean; var Buffer: PGtkTextBuffer = nil; iPosition: TGtkTextIter; pixbuf: PGDKPixBuf = nil; Width, Height, rowstride, n_channels, i, j: integer; //Alpha:Boolean = false; pixels: Pguchar = nil; p: Pguchar = nil; FastImage: TFastImage; begin //-- Result := False; //-- if not (GetGTKTextBuffer(Buffer)) then Exit; //-- gtk_text_buffer_get_iter_at_offset(buffer, @iPosition, Position); //-- pixbuf := gtk_text_iter_get_pixbuf(@iPosition); //-- if (pixbuf = nil) then Exit; n_channels := gdk_pixbuf_get_n_channels(pixbuf); Width := gdk_pixbuf_get_width(pixbuf); Height := gdk_pixbuf_get_height(pixbuf); rowstride := gdk_pixbuf_get_rowstride(pixbuf); pixels := gdk_pixbuf_get_pixels(pixbuf); //Alpha := gdk_pixbuf_get_has_alpha(pixbuf); //-- try FastImage := TFastImage.Create; FastImage.SetSize(Width, Height); {for i := 0 to Width - 1 do for J := 0 to Height - 1 do begin p := pixels + j * rowstride + i * n_channels; if n_channels = 4 then //FastImage.Color[i + 1, j + 1]:= RGBAToFastPixel(Ord((p + 2)^), Ord((p + 1)^), Ord((p + 0)^), Ord((P + 3)^)) FastImage.Color[i + 1, j + 1] := RGBAToFastPixel(Ord((p + 0)^), Ord((p + 1)^), Ord((p + 2)^), Ord((P + 3)^)) else //FastImage.Color[i + 1, j + 1] := RGBAToFastPixel(Ord((p + 2)^), Ord((p + 1)^), Ord((p + 0)^), $FF); FastImage.Color[i + 1, j + 1] := RGBAToFastPixel(Ord((p + 0)^), Ord((p + 1)^), Ord((p + 2)^), $FF); end;} I:=0; J:=0; While I < Width do begin While J < Height do //for J := 0 to Height - 1 do begin p := pixels + j * rowstride + i * n_channels; if n_channels = 4 then //FastImage.Color[i + 1, j + 1]:= RGBAToFastPixel(Ord((p + 2)^), Ord((p + 1)^), Ord((p + 0)^), Ord((P + 3)^)) FastImage.Color[i + 1, j + 1] := RGBAToFastPixel(Ord((p + 0)^), Ord((p + 1)^), Ord((p + 2)^), Ord((P + 3)^)) else //FastImage.Color[i + 1, j + 1] := RGBAToFastPixel(Ord((p + 2)^), Ord((p + 1)^), Ord((p + 0)^), $FF); FastImage.Color[i + 1, j + 1] := RGBAToFastPixel(Ord((p + 0)^), Ord((p + 1)^), Ord((p + 2)^), $FF); Inc(J); end; J:=0; Inc(I); end; FastImage.FastImageToPicture(Picture); finally FastImage.Free; end; Result := True; end; procedure TRTFSave.SaveToStream(Stream: TStream); begin Start; FRTFout.SaveToStream(Stream); end; constructor TRTFSave.Create(TextView: TWinControl); begin inherited Create; Ffonttbl := TStringList.Create; Fcolortbl := TStringList.Create; FRTFout := TStringList.Create; FTextView := TextView; end; destructor TRTFSave.Destroy; begin FRTFout.Free; Ffonttbl.Free; Fcolortbl.Free; inherited Destroy; end; end.
unit GMChatHandler; interface uses Classes, VoyagerInterfaces, VoyagerServerInterfaces, Controls, GMChatViewer, Protocol, GMKernel; type TMetaGMChatHandler = class( TInterfacedObject, IMetaURLHandler ) // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; TGMChatHandler = class( TInterfacedObject, IURLHandler ) private constructor Create; destructor Destroy; override; private fControl : TGMChatView; fClientView : IClientView; fMasterURLHandler : IMasterURLHandler; fGMId : TGameMasterId; fGMName : string; private procedure OnMessageComposed( Msg : string ); procedure OnCallGM; procedure OnDisconnectGM; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); private procedure threadedConnectToGM( const parms : array of const ); procedure syncConnectToGM( const parms : array of const ); procedure threadedSendMsg( const parms : array of const ); procedure syncSendMsg( const parms : array of const ); procedure threadedDisconnectFromGM( const parms : array of const ); private function ReadStrListInteger( Prop : TStringList; Value : string; default : integer ) : integer; function ReadStrListString( Prop : TStringList; Value : string; default : string ) : string; end; const tidHandlerName_GMChat = 'GMChatHandler'; implementation uses Threads, ServerCnxHandler, VoyagerUIEvents, Events, ServerCnxEvents, Forms, Windows, Graphics, SysUtils , Literals; // TMetaGMChatHandler function TMetaGMChatHandler.getName : string; begin result := tidHandlerName_GMChat; end; function TMetaGMChatHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable, hopEnabledWhenCached]; end; function TMetaGMChatHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaGMChatHandler.Instantiate : IURLHandler; begin result := TGMChatHandler.Create; end; // TGMChatHandler constructor TGMChatHandler.Create; begin inherited Create; fControl := TGMChatView.Create( nil ); fControl.OnMessageComposed := OnMessageComposed; fControl.OnCallGM := OnCallGM; fControl.OnDisconnectGM := OnDisconnectGM; end; destructor TGMChatHandler.Destroy; begin fControl.Free; inherited; end; procedure TGMChatHandler.OnMessageComposed( Msg : string ); begin Fork( threadedSendMsg, priNormal, [Msg] ); end; procedure TGMChatHandler.OnCallGM; begin if fGMId = 0 then begin fControl.btnConnect.Enabled := false; fControl.AddChatString( GetLiteral('Literal367'), GetLiteral('Literal368'), clLime ); Fork( threadedConnectToGM, priNormal, [fControl.GetGMOptionString] ); end else begin OnDisconnectGM; end; end; procedure TGMChatHandler.OnDisconnectGM; begin if fGMId <> 0 then begin fControl.AddChatString( GetLiteral('Literal369'), GetFormattedLiteral('Literal370', [fGMName]), clLime ); Fork( threadedDisconnectFromGM, priNormal, [fGMId] ); fControl.lbGMName.Caption := GetLiteral('Literal371'); fGMId := 0; fControl.ChatLine.Visible := false; fControl.btnConnect.Text := GetLiteral('Literal372'); end; end; function TGMChatHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlNotHandled; end; function TGMChatHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var ChannelListChangeInfo : TChannelListChangeInfo absolute info; ChannelName : string absolute info; GMMsgInfo : TGMMsgInfo absolute info; ScrollInfo : TEvnScrollInfo absolute info; GMEventInfo : TGMEvent absolute info; begin result := evnNotHandled; case EventId of evnGMMsg : fControl.AddChatString( fGMName, GMMsgInfo.Msg, clYellow ); evnGMEvent : case GMEventInfo.notID of GM_NOTIFY_USERONLINE : begin fControl.ChatLine.Visible := true; fControl.AddChatString( GetLiteral('Literal373'), GetFormattedLiteral('Literal374', [fGMName]), clLime ); fControl.AddGMToOptions( fGMName ); end; end; evnHandlerExposed :; { begin fControl.Text.SetFocus; fControl.TextInput.Text := 'Enter GMChat text here...'; fControl.TextInput.SelectAll; Fork( threadedUpdateChannelList, priNormal, [self] ); end; } evnHandlerUnexposed : OnDisconnectGM; else exit; end; result := evnHandled; end; function TGMChatHandler.getControl : TControl; begin result := fControl; end; procedure TGMChatHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin URLHandler.HandleEvent( evnAnswerClientView, fClientView ); fMasterURLHandler := URLHandler; fControl.ClientView := fClientView; fControl.MasterURLHandler := fMasterURLHandler; end; procedure TGMChatHandler.threadedConnectToGM( const parms : array of const ); var Options : string absolute parms[0].vPchar; GMName : string; PendingRequest : integer; GMId : TGameMasterId; ErrorCode : integer; Properties : TStringList; res : string; resProperties : TStringList; begin PendingRequest := 1; GMId := INVALID_GAMEMASTER; try Properties := TStringList.Create; try Properties.Values['Money'] := '$' + FormatCurr('#,###,###,###', fClientView.getMoney); Properties.Values['Level'] := 'Unknown'; Properties.Values['CompanyName'] := fClientView.getCompanyName; Properties.Values['World'] := fClientView.getWorldName; Properties.Values['DAAddr'] := fClientView.getDAAddr; Properties.Values['DAPort'] := IntToStr(fClientView.getDAPort); Properties.Values['ISAddr'] := fClientView.getISAddr; res := fClientView.ConnectToGameMaster( fClientView.getUserName, Properties.Text, Options ); resProperties := TStringList.Create; try resProperties.Text := res; finally ErrorCode := ReadStrListInteger( resProperties, 'Error', GM_ERR_UNEXPECTED ); GMName := ReadStrListString( resProperties, 'GameMasterName', '' ); PendingRequest := ReadStrListInteger( resProperties, 'PendingRequest', 1 ); GMId := ReadStrListInteger( resProperties, 'GameMaster', INVALID_GAMEMASTER ); resProperties.Free; end; finally Properties.Free; end; except ErrorCode := GM_ERR_UNEXPECTED; end; try Join( syncConnectToGM, [string(GMName), integer(PendingRequest), integer(GMId), ErrorCode] ); except end; end; procedure TGMChatHandler.syncConnectToGM( const parms : array of const ); var PendingRequest : integer; ErrorCode : integer; begin try fGMName := parms[0].vPchar; PendingRequest := parms[1].vInteger; fGMId := parms[2].vInteger; ErrorCode := parms[3].vInteger; fControl.btnConnect.Enabled := true; case ErrorCode of GM_ERR_NOERROR : begin fControl.AddChatString( GetLiteral('Literal375'), GetFormattedLiteral('Literal376', [fGMName, PendingRequest]), clLime ); fControl.btnConnect.Text := GetLiteral('Literal379'); fControl.lbGMName.Caption := fGMName; end; GM_ERR_NOGMAVAILABLE : fControl.AddChatString( GetLiteral('Literal380'), GetLiteral('Literal381'), clRed ); else fControl.AddChatString( GetLiteral('Literal382'), GetLiteral('Literal383'), clRed ); end; except end; end; procedure TGMChatHandler.threadedSendMsg( const parms : array of const ); var Msg : string absolute parms[0].vPchar; ErrorCode : integer; begin try ErrorCode := fClientView.SendGMMessage( fClientView.getUserName, fGMId, Msg ); except ErrorCode := GM_ERR_UNEXPECTED; end; try Join( syncSendMsg, [Msg, ErrorCode] ); except end; end; procedure TGMChatHandler.syncSendMsg( const parms : array of const ); var Msg : string absolute parms[0].vPchar; ErrorCode : integer; begin try ErrorCode := parms[1].vInteger; case ErrorCode of GM_ERR_NOERROR : fControl.AddChatString( fClientView.getUserName, Msg, $0084935E ); else fControl.AddChatString( GetLiteral('Literal384'), GetLiteral('Literal385'), clRed ); end; except end; end; procedure TGMChatHandler.threadedDisconnectFromGM( const parms : array of const ); var GMId : integer absolute parms[0].vInteger; begin try fClientView.DisconnectUser( fClientView.getUserName, GMId ); except end; end; function TGMChatHandler.ReadStrListInteger( Prop : TStringList; Value : string; default : integer ) : integer; var aux : string; begin aux := Prop.Values[Value]; if aux <> '' then try result := StrToInt(aux); except result := default; end else result := default; end; function TGMChatHandler.ReadStrListString( Prop : TStringList; Value : string; default : string ) : string; var aux : string; begin aux := Prop.Values[Value]; if aux <> '' then result := aux else result := default; end; end.
// *************************************************************************** // // FMXComponents: Firemonkey Opensource Components Set from China // // A simple Firemonkey Circle Score Indicator component // // Copyright 2017 谢顿 (zhaoyipeng@hotmail.com) // // https://github.com/zhaoyipeng/FMXComponents // // *************************************************************************** // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // *************************************************************************** } // version history // 2017-01-20, v0.1.0.0 : first release unit FMX.CircleScoreIndicator; interface uses System.Classes, System.Types, System.Math.Vectors, System.UITypes, System.Generics.Collections, FMX.Controls, FMX.Graphics, FMX.Objects, FMX.ComponentsCommon; type [ComponentPlatformsAttribute(TFMXPlatforms)] TFMXCircleScoreIndicator = class(TShape) private { Private declarations } FMax: Single; FMin: Single; FStartAngle: Single; FThickness: Single; FBackStroke: TStrokeBrush; FHeadBrush: TStrokeBrush; FTailBrush: TStrokeBrush; FScoreBrush: TBrush; FValue: Single; FIsHealthy: Boolean; procedure SetMax(const Value: Single); procedure SetMin(const Value: Single); procedure SetStartAngle(const Value: Single); procedure SetThickness(const Value: Single); procedure SetBackStroke(const Value: TStrokeBrush); procedure SetScoreBrush(const Value: TBrush); procedure SetValue(const Value: Single); function CreateMatrix(Angle: Single; cp2: TPointF): TMatrix; procedure RotateBrush(aBrush: TBrush; Angle: Single); procedure SetIsHealthy(const Value: Boolean); protected procedure Paint; override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetHealthyTheme; procedure SetUnhealthyTheme; published property Align; property Anchors; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Locked default False; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property Stroke; property Visible default True; property Width; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; property Max: Single read FMax write SetMax; property Min: Single read FMin write SetMin; property Value: Single read FValue write SetValue; property StartAngle: Single read FStartAngle write SetStartAngle; property Thickness: Single read FThickness write SetThickness; property BackStroke: TStrokeBrush read FBackStroke write SetBackStroke; property ScoreBrush: TBrush read FScoreBrush write SetScoreBrush; property IsHealthy: Boolean read FIsHealthy write SetIsHealthy; end; implementation uses System.Math; { TFMXCircleScore } constructor TFMXCircleScoreIndicator.Create(AOwner: TComponent); var g: TGradientPoint; begin inherited; FBackStroke := TStrokeBrush.Create(TBrushKind.Solid, $FFF5E0E2); FBackStroke.Thickness := 11; FBackStroke.OnChanged := FillChanged; FScoreBrush := TBrush.Create(TBrushKind.Gradient, $FFF14D4D); FScoreBrush.Gradient.Points.Clear; FScoreBrush.Gradient.Points.Add; FScoreBrush.Gradient.Points.Add; FScoreBrush.Gradient.Points.Add; g := FScoreBrush.Gradient.Points[0]; g.Offset := 0; g.Color := $FFF14D4D; g := FScoreBrush.Gradient.Points[1]; g.Offset := 0.5; g.Color := $FFE46161; g := FScoreBrush.Gradient.Points[2]; g.Offset := 1.0; g.Color := $FFEB8F73; FScoreBrush.OnChanged := FillChanged; FMin := 0; FMax := 100; FValue := 45; FThickness := 11; FHeadBrush := TStrokeBrush.Create(TBrushKind.Solid, $FFF14D4D); FTailBrush := TStrokeBrush.Create(TBrushKind.Solid, $FFEB8F73); end; destructor TFMXCircleScoreIndicator.Destroy; begin FTailBrush.Free; FHeadBrush.Free; FBackStroke.Free; inherited; end; function TFMXCircleScoreIndicator.CreateMatrix(Angle: Single; cp2: TPointF): TMatrix; var ScaleMatrix: TMatrix; M1: TMatrix; M2: TMatrix; RotMatrix: TMatrix; begin ScaleMatrix := TMatrix.Identity; ScaleMatrix.m11 := Scale.X; ScaleMatrix.m22 := Scale.Y; Result := ScaleMatrix; // rotation if Angle <> 0 then begin M1 := TMatrix.Identity; M1.m31 := -cp2.X * Scale.X; M1.m32 := -cp2.Y * Scale.Y; M2 := TMatrix.Identity; M2.m31 := cp2.X * Scale.X; M2.m32 := cp2.Y * Scale.Y; RotMatrix := M1 * (TMatrix.CreateRotation(DegToRad(Angle)) * M2); Result := Result * RotMatrix; end; end; procedure TFMXCircleScoreIndicator.Paint; var r, r1, r2: Single; cr: TRectF; path: TPathData; Angle, delta, stAngle, enAngle: Single; Count: Integer; I: Integer; cp, cp1, cp2, p1, p2, p3, p4: TPointF; s, s2: TStrokeBrush; v1, v2: Single; oldMatrix, M: TMatrix; begin inherited; r := (System.Math.Min(Width, Height) - Thickness) * 0.5; r1 := r - Thickness * 0.5; r2 := r + Thickness * 0.5; cr := TRectF.Create(0, 0, 1, 1).FitInto(LocalRect); cp := cr.CenterPoint; cr.Inflate(-Thickness * 0.5, -Thickness * 0.5); Canvas.DrawEllipse(cr, AbsoluteOpacity, FBackStroke); Angle := 360 * (FValue - FMin) / FMax; if SameValue(Angle, 0.0, 1E-4) then Exit; Count := Ceil(Angle / 5.0); if Odd(Count) then Count := Count + 1; delta := Angle / Count; path := TPathData.Create; s := TStrokeBrush.Create(TBrushKind.Gradient, TAlphaColors.Black); s2 := TStrokeBrush.Create(TBrushKind.Solid, TAlphaColors.Black); try s.Gradient.Points.Clear; s.Gradient.Points.Add; s.Gradient.Points.Add; cp1 := PointF(cp.X, cp.Y - r); Canvas.FillArc(cp1, PointF(Thickness * 0.5, Thickness * 0.5), -90, -180, AbsoluteOpacity, FHeadBrush); Canvas.DrawArc(cp1, PointF(Thickness * 0.5, Thickness * 0.5), -90, -180, AbsoluteOpacity, FHeadBrush); for I := 0 to Count - 1 do begin v1 := I / Count; v2 := (I + 1) / Count; stAngle := -90 + I * delta; enAngle := -90 + (I + 1) * delta; s.Gradient.Points[0].Color := FScoreBrush.Gradient.InterpolateColor(v1); s.Gradient.Points[1].Color := FScoreBrush.Gradient.InterpolateColor(v2); RotateBrush(s, stAngle + delta * 0.5); p1 := PointF(cp.X + r1 * Sin(stAngle), cp.Y + r1 * Cos(stAngle)); p2 := PointF(cp.X + r1 * Sin(enAngle), cp.Y + r1 * Cos(enAngle)); p3 := PointF(cp.X + r2 * Sin(enAngle), cp.Y + r2 * Cos(enAngle)); p4 := PointF(cp.X + r2 * Sin(stAngle), cp.Y + r2 * Cos(stAngle)); path.AddArc(cp, PointF(r1, r1), stAngle, delta); path.AddArc(cp, PointF(r2, r2), enAngle, -delta); path.ClosePath; Canvas.FillPath(path, AbsoluteOpacity, s); {$IFDEF MSWINDOWS} Canvas.DrawArc(cp, PointF(r1, r1), stAngle, delta, AbsoluteOpacity, s); Canvas.DrawArc(cp, PointF(r2, r2), stAngle, delta, AbsoluteOpacity, s); s2.Color := FScoreBrush.Gradient.InterpolateColor(v1); Canvas.DrawLine(path.Points[0].Point, path.Points[7].Point, AbsoluteOpacity, s2); {$ENDIF} path.Clear; end; cp2 := PointF(cp.X + r * Cos(DegToRad(Angle - 90)), cp.Y + r * Sin(DegToRad(Angle - 90))); M := CreateMatrix(Angle, cp2); oldMatrix := Canvas.Matrix; Canvas.MultiplyMatrix(M); Canvas.FillArc(cp2, PointF(Thickness * 0.5, Thickness * 0.5), -90, 180, AbsoluteOpacity, FTailBrush); Canvas.DrawArc(cp2, PointF(Thickness * 0.5, Thickness * 0.5), -90, 180, AbsoluteOpacity, FTailBrush); Canvas.SetMatrix(oldMatrix); finally path.Free; s.Free; s2.Free; end; end; procedure TFMXCircleScoreIndicator.RotateBrush(aBrush: TBrush; Angle: Single); var M1, M2, RotMatrix: TMatrix; p1, p2: TPointF; begin M1 := TMatrix.Identity; M1.m31 := -0.5; M1.m32 := -0.5; M2 := TMatrix.Identity; M2.m31 := 0.5; M2.m32 := 0.5; RotMatrix := M1 * (TMatrix.CreateRotation(DegToRad(Angle)) * M2); p1 := PointF(0, 0.5); p2 := PointF(1, 0.5); p1 := p1 * RotMatrix; p2 := p2 * RotMatrix; aBrush.Gradient.StartPosition.Point := p1; aBrush.Gradient.StopPosition.Point := p2; end; procedure TFMXCircleScoreIndicator.SetBackStroke(const Value: TStrokeBrush); begin FBackStroke := Value; end; procedure TFMXCircleScoreIndicator.SetHealthyTheme; var g: TGradientPoint; begin BeginUpdate; FBackStroke.Color := $FFe0f5ef; FScoreBrush.Gradient.Points.Clear; FScoreBrush.Gradient.Points.Add; FScoreBrush.Gradient.Points.Add; FScoreBrush.Gradient.Points.Add; g := FScoreBrush.Gradient.Points[0]; g.Offset := 0; g.Color := $FF14b98c; g := FScoreBrush.Gradient.Points[1]; g.Offset := 0.5; g.Color := $FF0cd49e; g := FScoreBrush.Gradient.Points[2]; g.Offset := 1.0; g.Color := $FF73eba0; FHeadBrush := TStrokeBrush.Create(TBrushKind.Solid, FScoreBrush.Gradient.Points[0].Color); FTailBrush := TStrokeBrush.Create(TBrushKind.Solid, FScoreBrush.Gradient.Points[2].Color); EndUpdate; end; procedure TFMXCircleScoreIndicator.SetIsHealthy(const Value: Boolean); begin if FIsHealthy <> Value then begin FIsHealthy := Value; if FIsHealthy then SetHealthyTheme else SetUnhealthyTheme; end; end; procedure TFMXCircleScoreIndicator.SetMax(const Value: Single); begin if FMax <> Value then begin FMax := Value; Repaint; end; end; procedure TFMXCircleScoreIndicator.SetMin(const Value: Single); begin if FMin <> Value then begin FMin := Value; Repaint; end; end; procedure TFMXCircleScoreIndicator.SetScoreBrush(const Value: TBrush); begin FScoreBrush := Value; end; procedure TFMXCircleScoreIndicator.SetStartAngle(const Value: Single); begin if FStartAngle <> Value then begin FStartAngle := Value; Repaint; end; end; procedure TFMXCircleScoreIndicator.SetThickness(const Value: Single); begin if FThickness <> Value then begin FThickness := Value; FBackStroke.Thickness := Value; Repaint; end; end; procedure TFMXCircleScoreIndicator.SetUnhealthyTheme; var g: TGradientPoint; begin BeginUpdate; FBackStroke.Color := $FFF5E0E2; FScoreBrush.Gradient.Points.Clear; FScoreBrush.Gradient.Points.Add; FScoreBrush.Gradient.Points.Add; FScoreBrush.Gradient.Points.Add; g := FScoreBrush.Gradient.Points[0]; g.Offset := 0; g.Color := $FFF14D4D; g := FScoreBrush.Gradient.Points[1]; g.Offset := 0.5; g.Color := $FFE46161; g := FScoreBrush.Gradient.Points[2]; g.Offset := 1.0; g.Color := $FFEB8F73; FHeadBrush := TStrokeBrush.Create(TBrushKind.Solid, FScoreBrush.Gradient.Points[0].Color); FTailBrush := TStrokeBrush.Create(TBrushKind.Solid, FScoreBrush.Gradient.Points[2].Color); EndUpdate; end; procedure TFMXCircleScoreIndicator.SetValue(const Value: Single); begin if FValue <> Value then begin FValue := Value; Repaint; end; end; end.
unit Timer.Main; interface Uses System.Classes, System.SysUtils, FireDAC.Comp.Client, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Base.Struct, Form.Modulo, DB.Conect, _Function.Base, Timer.DB; Type TTimerMain = Class Private { Class Private } class procedure StartTimers(Sender: TObject); Public { Class Public } constructor create; class procedure StartMainTimer(Sender: TObject); destructor destroy; override; End; implementation Var TimerMain: TTimer; TimerDB: TTimerDB; constructor TTimerMain.create; begin TimerMain := TTimer.create(Nil); TimerDB := TTimerDB.create; end; class procedure TTimerMain.StartTimers(Sender: TObject); Var Started: Boolean; begin if Not Started then begin Started := True; try TimerDB.StartDBTimer(Sender); TimerMain.Enabled := False; Except TimerMain.Enabled := True; end; Started := False; end; end; class procedure TTimerMain.StartMainTimer(Sender: TObject); begin TimerMain.Enabled := True; TimerMain.Interval := Fivesec; TimerMain.OnTimer := StartTimers; end; destructor TTimerMain.destroy; begin TimerMain.Free; TimerDB.Free; inherited; end; end.
unit NewProp; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, EditableObjects, ComCtrls, NativeEdObjects, Collection; const MAX_EDITPROP = 2; type TPropsInfo = array[0..MAX_EDITPROP-1] of record NameLabel : TLabel; EditorParent : TPanel; end; TNewPropForm = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; Label4: TLabel; Label5: TLabel; lbTemplate: TLabel; Label7: TLabel; edPropName: TEdit; cbPropClass: TComboBox; cbTemplates: TComboBox; cbValue: TComboBox; TabSheet2: TTabSheet; pnContainer: TPanel; Panel1: TPanel; Panel2: TPanel; Label1: TLabel; cbPropTemplates: TComboBox; Panel3: TPanel; Button2: TButton; Button1: TButton; procedure cbPropClassChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure cbTemplatesChange(Sender: TObject); procedure cbPropTemplatesChange(Sender: TObject); procedure FormDestroy(Sender: TObject); public NewProperty : TCollection; CreateMetaClass : boolean; EdParent : TEditableObject; private fTemplate : TNativeMetaEditableObject; fEditor : TObject; end; var NewPropForm: TNewPropForm; implementation uses Notifications, EditorEvents; {$R *.DFM} procedure TNewPropForm.cbPropClassChange(Sender: TObject); begin if CompareText( cbPropClass.Text, 'ComboBox' ) = 0 then begin lbTemplate.Visible := true; cbTemplates.Visible := true; end else begin lbTemplate.Visible := false; cbTemplates.Visible := false; end; end; procedure TNewPropForm.FormCreate(Sender: TObject); var MetaClass : TMetaEditableObject; Data : TGetTemplateData; i : integer; begin NewProperty := TCollection.Create( 5, rkUse ); Data.Name := 'Templates'; Data.Template := cbTemplates.Items; DispatchEvent( evGetTemplates, Data ); MetaClass := TheMetaObjectPool.get( 'MetaProperty' ); if MetaClass <> nil then for i := 0 to pred(MetaClass.Children.Count) do cbPropClass.Items.Add( TEditableObject(MetaClass.Children[i]).Name ); MetaClass := TheMetaObjectPool.get( 'PropertyTemplates' ); if MetaClass <> nil then for i := 0 to pred(MetaClass.Children.Count) do cbPropTemplates.Items.Add( TEditableObject(MetaClass.Children[i]).Name ); end; procedure TNewPropForm.Button2Click(Sender: TObject); var MetaClass : TMetaEditableObject; temp : TEditableObject; useless : integer; _NewProperty : TEditableObject; i : integer; begin if PageControl1.ActivePageIndex = 0 then begin if (edPropName.Text <> '') and (cbPropClass.Text <> '') then begin MetaClass := TheMetaObjectPool.get( 'MetaProperty.' + cbPropClass.Text ); if MetaClass <> nil then begin if not CreateMetaClass then begin _NewProperty := MetaClass.Instantiate( edPropName.Text, cbValue.Text, useless ); _NewProperty.MetaClass := MetaClass; if cbTemplates.Visible then begin temp := TEditableObject.Create; temp.MetaClass := TheMetaObjectPool.get( 'MetaProperty.PlainText' ); temp.Name := 'comboTemplate'; temp.Value := cbTemplates.Text; _NewProperty.Properties.Insert( temp ); end; end else begin _NewProperty := TNativeMetaEditableObject.Create; MetaClass.Clone( TNativeMetaEditableObject(_NewProperty) ); _NewProperty.MetaClass := MetaClass; _NewProperty.Name := edPropName.Text; _NewProperty.Value := cbValue.Text; if cbTemplates.Visible then begin temp := TNativeMetaEditableObject.Create; temp.Name := 'comboTemplate'; temp.Value := cbTemplates.Text; _NewProperty.Properties.Insert( temp ); end; end; NewProperty.Insert( _NewProperty ); ModalResult := mrOk; end; end; end else begin if (cbPropTemplates.Text <> '') and (fTemplate <> nil) then begin fTemplate.ObjectEditor.UpdateObject( fEditor, fTemplate ); for i := 0 to pred(fTemplate.Properties.Count) do NewProperty.Insert( fTemplate.Properties[i] ); fTemplate.Properties.ExtractAll; fTemplate.Free; ModalResult := mrOk; end; end; end; procedure TNewPropForm.Button1Click(Sender: TObject); begin fTemplate.Free; NewProperty.DeleteAll; ModalResult := mrCancel; end; procedure TNewPropForm.cbTemplatesChange(Sender: TObject); var Data : TGetTemplateData; begin cbValue.Items.Clear; Data.Name := cbTemplates.Text; Data.Template := cbValue.Items; DispatchEvent( evGetTemplates, Data ); cbValue.Text := cbValue.Items[0]; end; procedure TNewPropForm.cbPropTemplatesChange(Sender: TObject); function getNextNumber( PropName : string ) : integer; var i : integer; begin i := 1; while EdParent.getProperty( PropName + IntToStr(i) ) <> nil do inc( i ); result := i; end; var OldTemplate : TNativeMetaEditableObject; MetaClass : TMetaEditableObject; i : integer; begin OldTemplate := fTemplate; MetaClass := TheMetaObjectPool.get( 'PropertyTemplates.' + cbPropTemplates.Text ); if (MetaClass <> nil) and CreateMetaClass then begin fTemplate := TNativeMetaEditableObject.Create; MetaClass.Clone( fTemplate ); if (MetaClass.Options and OPT_NUMERABLE) <> 0 then begin for i := 0 to pred(fTemplate.Properties.Count) do TEditableObject(fTemplate.Properties[i]).Name := TEditableObject(fTemplate.Properties[i]).Name + IntToStr(getNextNumber(TEditableObject(fTemplate.Properties[i]).Name)); end; fTemplate.ObjectEditor := TheMetaObjectPool.getEditor( 'Step' ); fEditor := fTemplate.Edit( VOP_DONOTSHOWEVENTS, pnContainer ); if OldTemplate <> nil then OldTemplate.Free; end; end; procedure TNewPropForm.FormDestroy(Sender: TObject); begin NewProperty.Free; end; end.
unit vcmFormSetRefreshParams; {* Параметры обновления представления сборки. } // Библиотека : "vcm" // Автор : Морозов. М.А. // Модуль : vcmInterfaces - // Начат : 21.06.2007 // Версия : $Id: vcmFormSetRefreshParams.pas,v 1.2 2008/11/28 19:38:40 lulin Exp $ } {------------------------------------------------------------------------------- $Log: vcmFormSetRefreshParams.pas,v $ Revision 1.2 2008/11/28 19:38:40 lulin - избавляемся от "прокидывания данных". Revision 1.1 2007/06/22 08:56:23 mmorozov - new: параметры обновления представления сборки оформлены интерфейсом; -------------------------------------------------------------------------------} interface uses vcmInterfaces ; function vcmMakeDataRefreshParams(const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil): IvcmFormSetRefreshDataParams; {-} function vcmMakeRefreshParams(const aParams : IvcmFormSetRefreshDataParams; const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet): IvcmFormSetRefreshParams; {-} implementation uses SysUtils, vcmBase ; type TvcmFormSetRefreshParams = class(TvcmBase, IvcmFormSetRefreshParams) {* Элемент стека обновления. } private // internal methods f_DataSource : IvcmFormSetDataSource; f_FormSet : IvcmFormSet; f_SaveToHistory : TvcmSaveFormSetToHistory; f_DataForHistory : IvcmData; private // IvcmFormSetRefreshParams function pm_GetDataForHistory: IvcmData; {-} function pm_GetDataSource: IvcmFormSetDataSource; procedure pm_SetDataSource(const aValue: IvcmFormSetDataSource); {-} function pm_GetFormSet: IvcmFormSet; procedure pm_SetFormSet(const aValue: IvcmFormSet); {-} function pm_GetSaveToHistory: TvcmSaveFormSetToHistory; {-} protected // protected methods procedure Cleanup; override; {-} public // public methods constructor Create(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory; const aDataForHistory : IvcmData); reintroduce; {-} class function Make(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil): IvcmFormSetRefreshParams; {-} public // public properties property DataSource: IvcmFormSetDataSource read pm_GetDataSource; {-} property FormSet: IvcmFormSet read pm_GetFormSet; {-} property SaveToHistory: TvcmSaveFormSetToHistory read pm_GetSaveToHistory; {-} property DataForHistory: IvcmData read pm_GetDataForHistory; {-} end;//TvcmFormSetRefreshParams function vcmMakeRefreshParams(const aParams : IvcmFormSetRefreshDataParams; const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet): IvcmFormSetRefreshParams; {-} begin if Supports(aParams, IvcmFormSetRefreshParams, Result) then with Result do begin DataSource := aDataSource; FormSet := aFormSet end//with Result do else if aParams <> nil then Result := TvcmFormSetRefreshParams.Make(aDataSource, aFormSet, aParams.SaveToHistory, aParams.DataForHistory) else Result := TvcmFormSetRefreshParams.Make(aDataSource, aFormSet); end; function vcmMakeDataRefreshParams(const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil): IvcmFormSetRefreshDataParams; {-} begin Result := TvcmFormSetRefreshParams.Make(nil, nil, aSaveToHistory, aDataForHistory); end; { TvcmFormSetRefreshParams } procedure TvcmFormSetRefreshParams.Cleanup; // override; {-} begin f_DataForHistory := nil; f_DataSource := nil; f_FormSet := nil; inherited; end;//Cleanup constructor TvcmFormSetRefreshParams.Create(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory; const aDataForHistory : IvcmData); // reintroduce; {-} begin inherited Create; f_DataSource := aDataSource; f_FormSet := aFormSet; f_SaveToHistory := aSaveToHistory; f_DataForHistory := aDataForHistory; end;//Create class function TvcmFormSetRefreshParams.Make(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil): IvcmFormSetRefreshParams; {-} var l_Class: TvcmFormSetRefreshParams; begin l_Class := Create(aDataSource, aFormSet, aSaveToHistory, aDataForHistory); try Result := l_Class; finally FreeAndNil(l_Class); end;{try..finally} end;//Make function TvcmFormSetRefreshParams.pm_GetDataForHistory: IvcmData; begin Result := f_DataForHistory; end;//pm_GetDataForHistory function TvcmFormSetRefreshParams.pm_GetDataSource: IvcmFormSetDataSource; begin Result := f_DataSource; end;//pm_GetDataSource function TvcmFormSetRefreshParams.pm_GetFormSet: IvcmFormSet; begin Result := f_FormSet; end;//pm_GetFormSet function TvcmFormSetRefreshParams.pm_GetSaveToHistory: TvcmSaveFormSetToHistory; begin Result := f_SaveToHistory; end;//pm_GetSaveToHistory procedure TvcmFormSetRefreshParams.pm_SetDataSource(const aValue: IvcmFormSetDataSource); begin f_DataSource := aValue; end;//pm_SetDataSource procedure TvcmFormSetRefreshParams.pm_SetFormSet(const aValue: IvcmFormSet); begin f_FormSet := aValue; end;//pm_SetFormSet end.
{$MODE OBJFPC} {$INLINE ON} program ShufflingMachine; uses Math; const InputFile = 'SHUFFLE.INP'; OutputFile = 'SHUFFLE.OUT'; maxN = 1000000000; maxM = 100000; type PNode = ^TNode; TNode = record inf, sup: Integer; size: Integer; P, L, R: PNode; end; var fi, fo: TextFile; n, m: Integer; root, nilT: PNode; Sentinel: TNode; a: array[1..maxM * 2 + 1] of Integer; w: array[1..maxM * 2 + 1] of Integer; bit: array[1..maxM * 2 + 1] of Integer; id: array[1..maxM * 2 + 1] of Integer; lena: Integer; res: Integer; procedure OpenFiles; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); end; procedure CloseFiles; begin CloseFile(fi); CloseFile(fo); end; procedure Init(n: Integer); begin New(root); root^.inf := 0; root^.sup := 2 * n; root^.size := 2 * n; root^.P := nilT; root^.L := nilT; root^.R := nilT; end; procedure Destroy(x: PNode); begin if x = nilT then Exit; Destroy(x^.L); Destroy(x^.R); Dispose(x); end; procedure SetLink(Parent, Child: PNode; InLeft: Boolean); inline; begin Child^.P := Parent; if InLeft then Parent^.L := Child else Parent^.R := Child; end; function Len(x: PNode): Integer; inline; begin Result := x^.sup - x^.inf; end; procedure Update(x: PNode); inline; begin x^.size := x^.L^.size + x^.R^.size + Len(x); end; procedure UpTree(x: PNode); var y, z, b: PNode; begin y := x^.P; z := y^.P; if x = y^.L then begin b := x^.R; SetLink(y, b, True); SetLink(x, y, False); end else begin b := x^.L; SetLink(y, b, False); SetLink(x, y, True); end; SetLink(z, x, z^.L = y); Update(y); Update(x); end; procedure Splay(x: PNode); var y, z: PNode; begin repeat y := x^.P; if y = nilT then Break; z := y^.P; if z <> nilT then if (y = z^.L) = (x = y^.L) then UpTree(y) else UpTree(x); UpTree(x); until False; end; function NodeAt(T: PNode; i: Integer): PNode; var order1, order2: Integer; x: PNode; begin repeat order1 := T^.L^.size + 1; order2 := order1 + Len(T) - 1; if InRange(i, order1, order2) then Break; if i < order1 then T := T^.L else //i > order2 begin T := T^.R; Dec(i, order2); end; until False; if i < order2 then begin New(x); x^.sup := T^.sup; x^.inf := T^.sup - (order2 - i); SetLink(x, T^.R, False); x^.L := nilT; Update(x); T^.sup := x^.inf; SetLink(T, x, False); Update(T); end; Result := T; end; procedure Split(T: PNode; i: Integer; var TL, TR: PNode); begin if i = 0 then begin TL := nilT; TR := T; Exit; end; TL := NodeAt(T, i); Splay(TL); TR := TL^.R; TL^.R := nilT; TR^.P := nilT; Update(TL); Update(TR); end; function Join(TL, TR: PNode): PNode; begin if TL = nilT then Exit(TR); while TL^.R <> nilT do TL := TL^.R; Splay(TL); SetLink(TL, TR, False); Update(TL); Result := TL; end; procedure DoShuffle(k: Integer); var T1, T2, T3: PNode; begin Split(root, n - Abs(k), T1, T2); Split(T2, 2 * Abs(k), T2, T3); if k > 0 then root := Join(Join(T2, T1), T3) else root := Join(Join(T1, T3), T2); end; procedure ToArray; procedure Visit(x: PNode); begin if x = nilT then Exit; Visit(x^.L); Inc(lena); a[lena] := x^.sup; w[lena] := Len(x); Visit(x^.R); end; begin lena := 0; Visit(root); end; procedure Sort(L, H: Integer); var i, j: Integer; pivot: Integer; begin if L >= H then Exit; i := L + Random(H - L + 1); pivot := id[i]; id[i] := id[L]; i := L; j := H; repeat while (a[id[j]] > a[pivot]) and (i < j) do Dec(j); if i < j then begin id[i] := id[j]; Inc(i); end else Break; while (a[id[i]] < a[pivot]) and (i < j) do Inc(i); if i < j then begin id[j] := id[i]; Dec(j); end else Break; until i = j; id[i] := pivot; Sort(L, i - 1); Sort(i + 1, H); end; procedure UpdateBIT(x: Integer; fx: Integer); inline; begin repeat if fx <= bit[x] then Break; bit[x] := fx; Inc(x, (x and -x)); until x > lena; end; function QueryBIT(x: Integer): Integer; inline; begin Result := 0; while x > 0 do begin Result := Max(Result, bit[x]); x := x and Pred(x); end; end; procedure Optimize; var i, j: Integer; begin FillDWord(bit[1], lena, 0); for i := 1 to lena do begin j := id[i]; UpdateBIT(j, QueryBIT(j - 1) + w[j]); end; res := n shl 1 - QueryBIT(lena); end; procedure SolveAll; var icase: Integer; j: Integer; k: Integer; begin nilT := @sentinel; nilT^.size := 0; nilT^.inf := 1; nilT^.sup := 0; ReadLn(fi, n, m); Init(n); try for j := 1 to m do begin Read(fi, k); DoShuffle(k); end; ReadLn(fi); ToArray; finally Destroy(root); end; for j := 1 to lena do id[j] := j; Sort(1, lena); Optimize; WriteLn(fo, res); end; begin OpenFiles; try SolveAll; finally CloseFiles; end; end. 2 3 2 -2 1 1000000000 3 999999999 -1 2
unit vg_dsgn; {$I vg_define.inc} interface uses SysUtils, Classes, Graphics, Controls, Forms, ExtCtrls, ExtDlgs, Dialogs, StdCtrls, vg_scene, vg_layouts, vg_objects, vg_controls, vg_colors, vg_ani, vg_tabcontrol, vg_textbox, vg_listbox, vg_treeview, vg_inspector, vgComponent, vgCustomObject, vgCustomControl, vgScenePrim, vgObject, vgVisualObject; type TvgBrushDesign = class(TForm) panelSolid: TvgRectangle; panelGradient: TvgRectangle; solidQuad: TvgColorQuad; solidPicker: TvgColorPicker; gradQuad: TvgColorQuad; vgBrushDesigner: TvgScene; solidCont: TvgRectangle; gradEditor: TvgGradientEdit; dsgnRoot: TvgBackground; Layout1: TvgLayout; ext1: TvgLabel; Layout2: TvgLayout; Layout3: TvgLayout; gradPicker: TvgColorPicker; brushTabControl: TvgTabControl; tabNone: TvgTabItem; tabSolid: TvgTabItem; tabGradient: TvgTabItem; Text1: TvgLabel; Text2: TvgLabel; Text3: TvgLabel; brushList: TvgListBox; textSolidR: TvgNumberBox; textSolidG: TvgNumberBox; textSolidB: TvgNumberBox; textSolidA: TvgNumberBox; textGradR: TvgNumberBox; textGradG: TvgNumberBox; textGradB: TvgNumberBox; textGradA: TvgNumberBox; textSolidHex: TvgTextBox; textGradHex: TvgTextBox; gradColorRect: TvgColorBox; solidColorRect: TvgColorBox; tabBitmap: TvgTabItem; panelBitmap: TvgLayout; tabRes: TvgTabItem; panerRes: TvgLayout; bitmapImage: TvgImage; Layout5: TvgLayout; btnSelectBitmap: TvgButton; resList: TvgListBox; Layout6: TvgLayout; btnMakeRes: TvgButton; Label1: TvgLabel; Rectangle1: TvgRectangle; tileModeList: TvgPopupBox; btnCancel: TvgButton; btnOK: TvgButton; makeResLayout: TvgLayout; gradAngle: TvgAngleButton; gradAlabel: TvgLabel; gradKind: TvgPopupBox; gradAngleLabel: TvgLabel; HudWindow1: TvgHudWindow; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure solidQuadChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure gradEditorChange(Sender: TObject); procedure gradQuadChange(Sender: TObject); procedure brushListChange(Sender: TObject); procedure brushTabControlChange(Sender: TObject); procedure textGradRChange(Sender: TObject); procedure textGradHexChange(Sender: TObject); procedure textSolidHexChange(Sender: TObject); procedure btnSelectBitmapClick(Sender: TObject); procedure btnMakeResClick(Sender: TObject); procedure resListChange(Sender: TObject); procedure tileModeListChange(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure textSolidRChange(Sender: TObject); procedure gradAngleChange(Sender: TObject); procedure gradKindChange(Sender: TObject); protected procedure Notification(AComponent: TComponent; Operation: TOperation); //override; function UniqueName(S: string): string; //override; private FBrush: TvgBrush; FScene: IvgScene; FComp: TPersistent; procedure SetBrush(const Value: TvgBrush); procedure SetComp(const Value: TPersistent); procedure rebuilResList; { Private declarations } public { Public declarations } property Comp: TPersistent read FComp write SetComp; property Brush: TvgBrush read FBrush write SetBrush; end; TvgBrushStyles = set of TvgBrushStyle; TvgBrushDialog = class(TComponent) private FShowStyles: TvgBrushStyles; FShowBrushList: boolean; FShowMakeResource: boolean; FBrush: TvgBrush; FComponent: TComponent; FTitle: WideString; procedure SetBrush(const Value: TvgBrush); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: boolean; property Brush: TvgBrush read FBrush write SetBrush; property Component: TComponent read FComponent write FComponent; published property ShowStyles: TvgBrushStyles read FShowStyles write FShowStyles; property ShowBrushList: boolean read FShowBrushList write FShowBrushList default true; property ShowMakeResource: boolean read FShowMakeResource write FShowMakeResource; property Title: WideString read FTitle write FTitle; end; var vgDesign: TvgBrushDesign; procedure SelectInDesign(AObject: TObject; AComp: TPersistent); procedure ShowBrushDialog(const Brush: TvgBrush; const ShowStyles: TvgBrushStyles; const ShowBrushList: boolean = true); procedure ShowGradientDialog(const Gradient: TvgGradient); function ShowColorDialog(const Color: string): string; implementation uses TypInfo, vg_dsgn_bmp, Math, l3Base, vgObjectList, vgAnyObjectList, vgCustomObjectList, vgTypes{, vgNonModelTypes} ; {$IFNDEF FPC} {$R *.dfm} {$ELSE} {$R *.lfm} {$ENDIF} procedure SelectInDesign(AObject: TObject; AComp: TPersistent); begin if vgDesign = nil then begin vgDesign := TvgBrushDesign.Create(Application); try except FreeAndNil(vgDesign); vgDesign := nil; raise; end; end; if AObject = nil then begin vgDesign.Comp := nil; vgDesign.Brush := nil; end; if AObject is TvgBrush then begin vgDesign.Comp := AComp; vgDesign.Brush := TvgBrush(AObject); end; if AObject is TvgObject then begin vgDesign.Comp := TPersistent(AObject); vgDesign.Brush := nil; end; vgDesign.Show; end; { TvgBrushDesign ==============================================================} procedure TvgBrushDesign.FormCreate(Sender: TObject); begin { creeate } end; procedure TvgBrushDesign.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; vgDesign := nil; end; procedure TvgBrushDesign.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FComp) then begin Brush := nil; Comp := nil; end; { if (Operation = opRemove) and (AComponent = IScene) then begin IScene := nil; end;} end; procedure TvgBrushDesign.SetBrush(const Value: TvgBrush); var i: integer; begin FBrush := Value; if FBrush <> nil then begin case FBrush.Style of vgBrushNone: begin brushTabControl.ItemIndex := tabNone.Index; end; vgBrushSolid: begin solidPicker.Color := FBrush.SolidColor; gradEditor.Gradient.Assign(FBrush.Gradient); brushTabControl.ItemIndex := tabSolid.Index; end; vgBrushGradient: begin solidPicker.Color := FBrush.SolidColor; gradEditor.Gradient.Assign(FBrush.Gradient); gradKind.ItemIndex := Integer(gradEditor.Gradient.Style); if gradEditor.Gradient.StopPosition.X - gradEditor.Gradient.StartPosition.X <> 0 then begin if gradEditor.Gradient.StopPosition.X - gradEditor.Gradient.StartPosition.X > 0 then gradAngle.Value := -vgRadToDeg(ArcTan((gradEditor.Gradient.StopPosition.Y - gradEditor.Gradient.StartPosition.Y) / (gradEditor.Gradient.StopPosition.X - gradEditor.Gradient.StartPosition.X))) else gradAngle.Value := -vgRadToDeg(ArcTan((gradEditor.Gradient.StopPosition.Y - gradEditor.Gradient.StartPosition.Y) / (gradEditor.Gradient.StopPosition.X - gradEditor.Gradient.StartPosition.X))) - 180; end; gradAngle.Visible := gradEditor.Gradient.Style = vgLinearGradient; gradQuadChange(Self); brushTabControl.ItemIndex := tabGradient.Index; end; vgBrushVisual: ; vgBrushBitmap: begin brushTabControl.ItemIndex := tabBitmap.Index; bitmapImage.Bitmap.Assign(FBrush.Bitmap.Bitmap); tileModeList.ItemIndex := Integer(FBrush.Bitmap.WrapMode); end; vgBrushResource: begin brushTabControl.ItemIndex := tabRes.Index; rebuilResList; end; end; for i := 0 to brushList.Count - 1 do if (brushList.ItemByIndex(i) <> nil) and (TvgBrush(brushList.ItemByIndex(i).Tag) = Brush) then brushList.ItemIndex := i; end; end; procedure TvgBrushDesign.SetComp(const Value: TPersistent); var i: integer; BrushButton: TvgListBoxItem; BrushText: TvgTextControl; PropCount: integer; PropList: PPropList; PropType: PTypeData; begin FComp := Value; {$IFNDEF NOVCL} if (FComp <> nil) and (FComp is TvgScene) then FScene := TvgScene(FComp); {$ENDIF} if (FComp <> nil) and (FComp is TvgObject) then FScene := TvgObject(FComp).Scene; { find all brushes } Brush := nil; brushList.Clear; brushList.Height := 4; {$IFDEF KS_COMPILER5} PropCount := GetPropList(FComp.ClassInfo, [tkClass], nil); l3System.GetLocalMem(PropList, SizeOf(PPropInfo) * PropCount); try PropCount := GetPropList(FComp.ClassInfo, [tkClass], PropList); {$ELSE} PropCount := GetPropList(FComp.ClassInfo, PropList); try {$ENDIF} for i := 0 to PropCount - 1 do begin if PropList[i].PropType^.Kind <> tkClass then Continue; PropType := GetTypeData(PropList[i].PropType{$IFNDEF FPC}^{$ENDIF}); if PropType = nil then Continue; if not (PropType.ClassType.ClassName = 'TvgBrush') then Continue; BrushButton := TvgListBoxItem.Create(Self); BrushButton.Parent := brushList; BrushButton.Height := 23; BrushButton.Tag := Integer(GetObjectProp(FComp, PropList[i].Name)); BrushText := TvgLabel.Create(Self); BrushText.Parent := BrushButton; BrushText.Align := vaClient; BrushText.HitTest := false; BrushText.Text := PropList[i].Name; brushList.Height := brushList.Height + BrushButton.Height; if Brush = nil then Brush := TvgBrush(GetObjectProp(FComp, PropList[i].Name)); end; brushList.ItemIndex := 0; finally {$IFDEF KS_COMPILER5} l3System.FreeLocalMem(PropList{, SizeOf(PPropInfo) * PropCount}); {$Else KS_COMPILER5} System.FreeMem(PropList); {$EndIF KS_COMPILER5} end;//try..finally end; function TvgBrushDesign.UniqueName(S: string): string; begin if (FComp <> nil) and (FComp is TComponent) and (TComponent(FComp).Owner <> nil) and (TComponent(FComp).Owner is TCustomForm) then Result := TCustomForm(TComponent(FComp).Owner).Designer.UniqueName(S) else if Designer <> nil then Result := Designer.UniqueName(S) else begin Tag := Tag + 1; Result := S + IntToStr(Tag); end; end; procedure TvgBrushDesign.solidQuadChange(Sender: TObject); begin if FBrush = nil then Exit; solidQuad.Alpha := ((FBrush.SolidColor and $FF000000) shr 24) / $FF; FBrush.SolidColor := (FBrush.SolidColor and not $FFFFFF) or ($00FFFFFF and vgHSLtoRGB(solidQuad.Hue, solidQuad.Sat, solidQuad.Lum)); textSolidR.Value := TvgColorRec(FBrush.SolidColor).R; textSolidG.Value := TvgColorRec(FBrush.SolidColor).G; textSolidB.Value := TvgColorRec(FBrush.SolidColor).B; textSolidA.Value := TvgColorRec(FBrush.SolidColor).A; textSolidHex.Text := vgColorToStr(FBrush.SolidColor); end; procedure TvgBrushDesign.textSolidHexChange(Sender: TObject); begin { change solid hex } if FBrush = nil then Exit; FBrush.SolidColor := vgStrToColor(textSolidHex.Text); solidPicker.Color := FBrush.SolidColor; end; procedure TvgBrushDesign.textSolidRChange(Sender: TObject); var Color: TvgColor; begin { solid textbox change } if FBrush = nil then Exit; Color := FBrush.SolidColor; TvgColorRec(Color).R := trunc(textSolidR.Value); TvgColorRec(Color).G := trunc(textSolidG.Value); TvgColorRec(Color).B := trunc(textSolidB.Value); TvgColorRec(Color).A := trunc(textSolidA.Value); FBrush.SolidColor := Color; solidPicker.Color := FBrush.SolidColor; end; procedure TvgBrushDesign.gradEditorChange(Sender: TObject); begin { change gradient } if FBrush = nil then Exit; FBrush.Gradient.Assign(gradEditor.Gradient); end; procedure TvgBrushDesign.gradQuadChange(Sender: TObject); begin { chage color in current point } if FBrush = nil then Exit; gradEditor.Gradient.Points[gradEditor.CurrentPoint].IntColor := (gradEditor.Gradient.Points[gradEditor.CurrentPoint].IntColor and $FF000000) or ($00FFFFFF and vgHSLtoRGB(gradQuad.Hue, gradQuad.Sat, gradQuad.Lum)); FBrush.Gradient.Assign(gradEditor.Gradient); textGradR.Value := TvgColorRec(gradColorRect.Color).R; textGradG.Value := TvgColorRec(gradColorRect.Color).G; textGradB.Value := TvgColorRec(gradColorRect.Color).B; textGradA.Value := TvgColorRec(gradColorRect.Color).A; textGradHex.Text := vgColorToStr(gradColorRect.Color); gradEditor.Repaint; end; procedure TvgBrushDesign.brushListChange(Sender: TObject); begin if FScene = nil then Exit; if FComp = nil then Exit; if Sender <> nil then Brush := TvgBrush(TvgListBoxItem(Sender).Tag); end; procedure TvgBrushDesign.brushTabControlChange(Sender: TObject); begin if FBrush = nil then Exit; if brushTabControl.ItemIndex = tabNone.Index then FBrush.Style := vgBrushNone; if brushTabControl.ItemIndex = tabSolid.Index then FBrush.Style := vgBrushSolid; if brushTabControl.ItemIndex = tabGradient.Index then begin FBrush.Style := vgBrushGradient; gradQuadChange(Sender); gradAngleLabel.Text := InttoStr(Trunc(gradAngle.Value)); end; if brushTabControl.ItemIndex = tabBitmap.Index then FBrush.Style := vgBrushBitmap; if brushTabControl.ItemIndex = tabRes.Index then FBrush.Style := vgBrushResource; btnMakeRes.Visible := (brushTabControl.ItemIndex <> tabRes.Index) and (brushTabControl.ItemIndex <> tabNone.Index); if not btnMakeRes.Visible then rebuilResList; end; procedure TvgBrushDesign.textGradRChange(Sender: TObject); var Color: TvgColor; begin { change grad brush alpha } if FBrush = nil then Exit; Color := gradEditor.Gradient.Points[gradEditor.CurrentPoint].IntColor; TvgColorRec(Color).R := trunc(textGradR.Value); TvgColorRec(Color).G := trunc(textGradG.Value); TvgColorRec(Color).B := trunc(textGradB.Value); TvgColorRec(Color).A := trunc(textGradA.Value); gradEditor.Gradient.Points[gradEditor.CurrentPoint].IntColor := Color; gradEditor.UpdateGradient; end; procedure TvgBrushDesign.gradKindChange(Sender: TObject); begin { change grad type } if FBrush = nil then Exit; gradEditor.Gradient.Style := TvgGradientStyle(gradKind.ItemIndex); gradEditor.UpdateGradient; gradAngle.Visible := gradEditor.Gradient.Style = vgLinearGradient; end; procedure TvgBrushDesign.gradAngleChange(Sender: TObject); var Color: TvgColor; X, Y, Koef: single; begin { change grad brush alpha } if FBrush = nil then Exit; if (Cos(vgDegToRad(gradAngle.Value)) <> 0) and (Abs(1 / Cos(vgDegToRad(gradAngle.Value))) >= 1) and (Abs(1 / Cos(vgDegToRad(gradAngle.Value))) <= 1.42) then X := Abs(1 / Cos(vgDegToRad(gradAngle.Value))) else X := 1; if (Sin(vgDegToRad(gradAngle.Value)) <> 0) and (Abs(1 / Sin(vgDegToRad(gradAngle.Value))) >= 1) and (Abs(1 / Sin(vgDegToRad(gradAngle.Value))) <= 1.42) then Y := Abs(1 / Sin(vgDegToRad(gradAngle.Value))) else Y := 1; Koef := vgMaxFloat(X, Y); Koef := Koef * 0.5; gradEditor.Gradient.StartPosition.Point := vgPoint(0.5 - (Cos(vgDegToRad(gradAngle.Value)) * Koef), 0.5 + (Sin(vgDegToRad(gradAngle.Value)) * Koef)); gradEditor.Gradient.StopPosition.Point := vgPoint(0.5 + (Cos(vgDegToRad(gradAngle.Value)) * Koef), 0.5 - (Sin(vgDegToRad(gradAngle.Value)) * Koef)); gradEditor.UpdateGradient; gradAngleLabel.Text := InttoStr(Trunc(gradAngle.Value)); end; procedure TvgBrushDesign.textGradHexChange(Sender: TObject); begin { change gradient hex } if FBrush = nil then Exit; gradEditor.Gradient.Points[gradEditor.CurrentPoint].IntColor := vgStrToColor(textGradHex.Text); gradEditor.UpdateGradient; end; procedure TvgBrushDesign.btnSelectBitmapClick(Sender: TObject); begin if FBrush = nil then Exit; vgBitmapEditor := TvgBitmapEditor.Create(nil); vgBitmapEditor.AssignFromBitmap(bitmapImage.Bitmap); if vgBitmapEditor.ShowModal = mrOk then begin vgBitmapEditor.AssignToBitmap(bitmapImage.Bitmap); FBrush.Bitmap.Bitmap.Assign(bitmapImage.Bitmap); if (FComp <> nil) and (FComp is TvgVisualObject) then TvgVisualObject(FComp).Repaint; bitmapImage.Repaint; end; FreeAndNil(vgBitmapEditor); end; procedure TvgBrushDesign.rebuilResList; var i: integer; L: TvgCustomObjectList; item: TvgListBoxItem; itemText: TvgTextControl; rect: TvgRectangle; begin if FScene = nil then Exit; if FScene.GetRoot = nil then Exit; if FBrush = nil then Exit; resList.Clear; L := TvgCustomObjectList.Create; try TvgObject(FScene.GetRoot).AddObjectsToList(L); for i := 0 to L.Count - 1 do if TvgObject(L[i]) is TvgBrushObject then begin item := TvgListBoxItem.Create(Self); item.Tag := Integer(L[i]); item.Parent := resList; itemText := TvgLabel.Create(Self); itemText.Parent := item; itemText.Align := vaClient; itemText.HitTest := false; itemText.Text := TvgObject(L[i]).ResourceName; rect := TvgRectangle.Create(Self); rect.Parent := item; rect.Align := vaLeft; rect.HitTest := false; rect.Padding.Rect := vgRect(2, 2, 2, 2); rect.Fill.Style := vgBrushResource; rect.Fill.Resource.Resource := TvgBrushObject(L[i]); rect.Stroke.Color := '#80FFFFFF'; if FBrush.Resource.Resource = TvgBrushObject(L[i]) then resList.ItemIndex := resList.Count - 1; end; finally FreeAndNil(L); end;//try..finally end; procedure TvgBrushDesign.resListChange(Sender: TObject); begin if FScene = nil then Exit; if FScene.GetRoot = nil then Exit; if FBrush = nil then Exit; if Sender = nil then Exit; FBrush.Assign(TvgBrushObject(TvgListBoxItem(Sender).Tag).Brush); FBrush.Resource.Resource := TvgBrushObject(TvgListBoxItem(Sender).Tag); FBrush.Style := vgBrushResource; end; procedure TvgBrushDesign.btnMakeResClick(Sender: TObject); var S: string; B: TvgBrushObject; begin if FBrush = nil then Exit; if FScene = nil then Exit; if FScene.GetRoot = nil then Exit; { make res } S := UniqueName('Brush'); if InputQuery('New TvgBrushObject', 'Enter resource name:', S) then begin B := TvgBrushObject.Create(FScene.GetOwner); B.Parent := TvgObject(FScene.GetRoot); B.ResourceName := S; B.Name := B.ResourceName; B.ResourceName := S; B.Brush.Assign(FBrush); rebuilResList; end; end; procedure TvgBrushDesign.tileModeListChange(Sender: TObject); begin if FBrush = nil then Exit; FBrush.Bitmap.WrapMode := TvgWrapMode(tileModeList.ItemIndex); if (FComp <> nil) and (FComp is TvgVisualObject) then TvgVisualObject(FComp).Repaint; end; procedure TvgBrushDesign.btnOKClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TvgBrushDesign.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; { TvgBrushDialog } procedure ShowBrushDialog(const Brush: TvgBrush; const ShowStyles: TvgBrushStyles; const ShowBrushList: boolean); var Dlg: TvgBrushDialog; begin Dlg := TvgBrushDialog.Create(nil); Dlg.Brush := Brush; Dlg.ShowStyles := ShowStyles; Dlg.ShowBrushList := ShowBrushList; if Dlg.Execute then Brush.Assign(Dlg.Brush); FreeAndNil(Dlg); end; procedure ShowGradientDialog(const Gradient: TvgGradient); var Dlg: TvgBrushDialog; begin Dlg := TvgBrushDialog.Create(nil); Dlg.Brush.Style := vgBrushGradient; Dlg.Brush.Gradient := Gradient; Dlg.ShowStyles := [vgBrushGradient]; Dlg.ShowBrushList := false; if Dlg.Execute then Gradient.Assign(Dlg.Brush.Gradient); FreeAndNil(Dlg); end; function ShowColorDialog(const Color: string): string; var Dlg: TvgBrushDialog; begin Dlg := TvgBrushDialog.Create(nil); Dlg.Brush.Style := vgBrushSolid; Dlg.Brush.Color := Color; Dlg.ShowStyles := [vgBrushSolid]; Dlg.ShowBrushList := false; if Dlg.Execute then begin Result := Dlg.Brush.Color; end; FreeAndNil(Dlg); end; constructor TvgBrushDialog.Create(AOwner: TComponent); begin inherited; FBrush := TvgBrush.Create(vgBrushSolid, $FF808080); FShowStyles := [vgBrushNone, vgBrushSolid, vgBrushGradient, vgBrushBitmap, vgBrushResource]; FShowBrushList := true; FShowMakeResource := false; FTitle := 'Brush'; end; destructor TvgBrushDialog.Destroy; begin FreeAndNil(FBrush); inherited; end; function TvgBrushDialog.Execute: boolean; var Dialog: TvgBrushDesign; EditBrush: TvgBrush; begin Dialog := TvgBrushDesign.Create(Application); Dialog.brushList.Visible := ShowBrushList; if FComponent <> nil then Dialog.Comp := FComponent else Dialog.brushList.Visible := false; Dialog.HudWindow1.Text := FTitle; Dialog.brushTabControl.ItemIndex := -1; Dialog.tabNone.Visible := vgBrushNone in ShowStyles; Dialog.tabSolid.Visible := vgBrushSolid in ShowStyles; Dialog.tabGradient.Visible := vgBrushGradient in ShowStyles; Dialog.tabBitmap.Visible := vgBrushBitmap in ShowStyles; Dialog.tabRes.Visible := vgBrushResource in ShowStyles; Dialog.brushTabControl.Realign; Dialog.btnOK.Visible := true; Dialog.btnCancel.Visible := true; Dialog.Brush := FBrush; Dialog.makeResLayout.Visible := ShowMakeResource; Dialog.dsgnRoot.Height := Dialog.dsgnRoot.Height - 1; // realign Dialog.ClientHeight := Trunc(Dialog.Layout6.Position.Y + Dialog.Layout6.Height + Dialog.HudWindow1.Margins.Top + Dialog.HudWindow1.Margins.Bottom); Result := Dialog.ShowModal = mrOk; FreeAndNil(Dialog); end; procedure TvgBrushDialog.SetBrush(const Value: TvgBrush); begin FBrush.Assign(Value);; end; end.
unit TTSTRANTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSTRANRecord = record PLenderNumber: String[4]; PLoanCif: String[20]; PDateStamp: String[17]; PLineNumber: SmallInt; PTranCode: String[2]; PData: String[120]; PUserID: String[10]; End; TTTSTRANBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSTRANRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSTRAN = (TTSTRANPrimaryKey); TTTSTRANTable = class( TDBISAMTableAU ) private FDFLenderNumber: TStringField; FDFLoanCif: TStringField; FDFDateStamp: TStringField; FDFLineNumber: TSmallIntField; FDFTranCode: TStringField; FDFData: TStringField; FDFUserID: TStringField; procedure SetPLenderNumber(const Value: String); function GetPLenderNumber:String; procedure SetPLoanCif(const Value: String); function GetPLoanCif:String; procedure SetPDateStamp(const Value: String); function GetPDateStamp:String; procedure SetPLineNumber(const Value: SmallInt); function GetPLineNumber:SmallInt; procedure SetPTranCode(const Value: String); function GetPTranCode:String; procedure SetPData(const Value: String); function GetPData:String; procedure SetPUserID(const Value: String); function GetPUserID:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSTRAN); function GetEnumIndex: TEITTSTRAN; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSTRANRecord; procedure StoreDataBuffer(ABuffer:TTTSTRANRecord); property DFLenderNumber: TStringField read FDFLenderNumber; property DFLoanCif: TStringField read FDFLoanCif; property DFDateStamp: TStringField read FDFDateStamp; property DFLineNumber: TSmallIntField read FDFLineNumber; property DFTranCode: TStringField read FDFTranCode; property DFData: TStringField read FDFData; property DFUserID: TStringField read FDFUserID; property PLenderNumber: String read GetPLenderNumber write SetPLenderNumber; property PLoanCif: String read GetPLoanCif write SetPLoanCif; property PDateStamp: String read GetPDateStamp write SetPDateStamp; property PLineNumber: SmallInt read GetPLineNumber write SetPLineNumber; property PTranCode: String read GetPTranCode write SetPTranCode; property PData: String read GetPData write SetPData; property PUserID: String read GetPUserID write SetPUserID; published property Active write SetActive; property EnumIndex: TEITTSTRAN read GetEnumIndex write SetEnumIndex; end; { TTTSTRANTable } procedure Register; implementation function TTTSTRANTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSTRANTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSTRANTable.GenerateNewFieldName } function TTTSTRANTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSTRANTable.CreateField } procedure TTTSTRANTable.CreateFields; begin FDFLenderNumber := CreateField( 'LenderNumber' ) as TStringField; FDFLoanCif := CreateField( 'LoanCif' ) as TStringField; FDFDateStamp := CreateField( 'DateStamp' ) as TStringField; FDFLineNumber := CreateField( 'LineNumber' ) as TSmallIntField; FDFTranCode := CreateField( 'TranCode' ) as TStringField; FDFData := CreateField( 'Data' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; end; { TTTSTRANTable.CreateFields } procedure TTTSTRANTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSTRANTable.SetActive } procedure TTTSTRANTable.SetPLenderNumber(const Value: String); begin DFLenderNumber.Value := Value; end; function TTTSTRANTable.GetPLenderNumber:String; begin result := DFLenderNumber.Value; end; procedure TTTSTRANTable.SetPLoanCif(const Value: String); begin DFLoanCif.Value := Value; end; function TTTSTRANTable.GetPLoanCif:String; begin result := DFLoanCif.Value; end; procedure TTTSTRANTable.SetPDateStamp(const Value: String); begin DFDateStamp.Value := Value; end; function TTTSTRANTable.GetPDateStamp:String; begin result := DFDateStamp.Value; end; procedure TTTSTRANTable.SetPLineNumber(const Value: SmallInt); begin DFLineNumber.Value := Value; end; function TTTSTRANTable.GetPLineNumber:SmallInt; begin result := DFLineNumber.Value; end; procedure TTTSTRANTable.SetPTranCode(const Value: String); begin DFTranCode.Value := Value; end; function TTTSTRANTable.GetPTranCode:String; begin result := DFTranCode.Value; end; procedure TTTSTRANTable.SetPData(const Value: String); begin DFData.Value := Value; end; function TTTSTRANTable.GetPData:String; begin result := DFData.Value; end; procedure TTTSTRANTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TTTSTRANTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TTTSTRANTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNumber, String, 4, N'); Add('LoanCif, String, 20, N'); Add('DateStamp, String, 17, N'); Add('LineNumber, SmallInt, 0, N'); Add('TranCode, String, 2, N'); Add('Data, String, 120, N'); Add('UserID, String, 10, N'); end; end; procedure TTTSTRANTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNumber;LoanCif;DateStamp;LineNumber, Y, Y, N, N'); end; end; procedure TTTSTRANTable.SetEnumIndex(Value: TEITTSTRAN); begin case Value of TTSTRANPrimaryKey : IndexName := ''; end; end; function TTTSTRANTable.GetDataBuffer:TTTSTRANRecord; var buf: TTTSTRANRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNumber := DFLenderNumber.Value; buf.PLoanCif := DFLoanCif.Value; buf.PDateStamp := DFDateStamp.Value; buf.PLineNumber := DFLineNumber.Value; buf.PTranCode := DFTranCode.Value; buf.PData := DFData.Value; buf.PUserID := DFUserID.Value; result := buf; end; procedure TTTSTRANTable.StoreDataBuffer(ABuffer:TTTSTRANRecord); begin DFLenderNumber.Value := ABuffer.PLenderNumber; DFLoanCif.Value := ABuffer.PLoanCif; DFDateStamp.Value := ABuffer.PDateStamp; DFLineNumber.Value := ABuffer.PLineNumber; DFTranCode.Value := ABuffer.PTranCode; DFData.Value := ABuffer.PData; DFUserID.Value := ABuffer.PUserID; end; function TTTSTRANTable.GetEnumIndex: TEITTSTRAN; var iname : string; begin result := TTSTRANPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSTRANPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSTRANTable, TTTSTRANBuffer ] ); end; { Register } function TTTSTRANBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..7] of string = ('LENDERNUMBER','LOANCIF','DATESTAMP','LINENUMBER','TRANCODE','DATA' ,'USERID' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 7) and (flist[x] <> s) do inc(x); if x <= 7 then result := x else result := 0; end; function TTTSTRANBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftSmallInt; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; end; end; function TTTSTRANBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNumber; 2 : result := @Data.PLoanCif; 3 : result := @Data.PDateStamp; 4 : result := @Data.PLineNumber; 5 : result := @Data.PTranCode; 6 : result := @Data.PData; 7 : result := @Data.PUserID; end; end; end.
unit untUtil; interface uses // VCL Windows, SysUtils, Controls, Registry, StdCtrls, ExtCtrls, ComCtrls, Classes, Graphics; function StrToHex(const S: string): string; function HexToStr(const S: string): string; function GetINN(const S: string): string; function GetRNM(const S: string): string; function GetLicense(const S: string): string; function GetSerialNumber(const S: string): string; function ConfirmFiscalization(Wnd: THandle): Boolean; function FMFlagsToStr(NBits: Integer; Driver: OleVariant): string; function ECRFlagsToStr(NBits: Integer; Driver: OleVariant): string; procedure LoadControlParams(const Path: string; Control: TWinControl; Reg: TRegistry); procedure SaveControlParams(const Path: string; Control: TWinControl; Reg: TRegistry); const HighLighting = False; InColor = $99FF99; OutColor = $CCFFFF; implementation function StrToHex(const S: string): string; var i: Integer; begin Result := ''; for i := 1 to Length(S) do Result := Result + IntToHex(Ord(S[i]), 2) + ' '; end; function HexToStr(const S: string): string; function HexStrToChar(const Value: string): Char; begin if Length(Value) in [1..2] then Result := Chr(StrToInt('$'+Value)) else raise Exception.Create('Недопустимый символ в строке'); end; var Data: string; Digit: string; Index: Integer; begin Data := Trim(S) + ' '; Result := ''; Index := Pos(' ', Data); while Index > 0 do begin Digit := Copy(Data, 1, Index-1); Data := Copy(Data, Index + 1, Length(Data)); Result := Result + HexStrToChar(Digit); Index := Pos(' ', Data); end; end; function GetINN(const S: string): string; begin Result := S; if Result = '' then Result := 'не задан' end; function GetRNM(const S: string): string; begin Result := S; if Result = '' then Result := 'не задан' end; function GetLicense(const S: string): string; begin Result := S; if Result = '' then Result := 'не введена' end; function GetSerialNumber(const S: string): string; begin Result := S; if Result = '' then Result := 'не введен' end; function ECRFlagsToStr(NBits: Integer; Driver: OleVariant): string; const BitStr:array[0..15,False..True]of string=( ('<нет>','<есть>'), ('<нет>','<есть>'), ('<нет>','<есть>'), ('<нет>','<есть>'), ('<0 знаков>','<2 знака>'), ('<нет>','<есть>'), ('<нет>','<есть>'), ('<нет>','<есть>'), ('<поднят>','<опущен>'), ('<поднят>','<опущен>'), ('<опущена>','<поднята>'), ('<закрыт>','<открыт>'), ('<нет>','<есть>'), ('<нет>','<есть>'), ('<нет>','<да>'), ('<6 знаков>','<3 знака>')); begin Case NBits of 0: Result := BitStr[0,Boolean(Driver.JournalRibbonIsPresent)]; 1: Result := BitStr[1,Boolean(Driver.ReceiptRibbonIsPresent)]; 2: Result := BitStr[3,Boolean(Driver.SlipDocumentIsMoving)]; 3: Result := BitStr[2,Boolean(Driver.SlipDocumentIsPresent)]; 4: Result := BitStr[4,Boolean(Driver.PointPosition)]; 5: Result := BitStr[5,Boolean(Driver.EKLZIsPresent)]; 6: Result := BitStr[6,Boolean(Driver.JournalRibbonOpticalSensor)]; 7: Result := BitStr[7,Boolean(Driver.ReceiptRibbonOpticalSensor)]; 8: Result := BitStr[8,Boolean(Driver.JournalRibbonLever)]; 9: Result := BitStr[9,Boolean(Driver.ReceiptRibbonLever)]; 10: Result := BitStr[10,Boolean(Driver.LidPositionSensor)]; 11: Result := BitStr[11,Boolean(Driver.isDrawerOpen)]; 12: Result := BitStr[12,Boolean(Driver.isPrinterRightSensorFailure)]; 13: Result := BitStr[13,Boolean(Driver.isPrinterLeftSensorFailure)]; 14: Result := BitStr[14,Boolean(Driver.IsEKLZOverflow)]; 15: Result := BitStr[15,Boolean(Driver.QuantityPointPosition)]; else Result := 'Неправильный номер бита'; end; end; function FMFlagsToStr(NBits: Integer; Driver: OleVariant): string; const BitStr:array[0..7,False..True]of string=( ('<нет>','<есть>'), ('<нет>','<есть>'), ('<не введена>','<введена>'), ('<нет>','<есть>'), ('< <80% >','< >80% >'), ('<корректна>','<повреждена>'), ('<закрыта>','<открыта>'), ('<не кончились>','<кончились>') ); begin Case NBits of 0: Result := BitStr[0,Boolean(Driver.FM1IsPresent)]; 1: Result := BitStr[1,Boolean(Driver.FM2IsPresent)]; 2: Result := BitStr[2,Boolean(Driver.LicenseIsPresent)]; 3: Result := BitStr[3,Boolean(Driver.FMOverflow)]; 4: Result := BitStr[4,Boolean(Driver.IsBatteryLow)]; 5: Result := BitStr[5,Boolean(Driver.IsLastFMRecordCorrupted)]; 6: Result := BitStr[6,Boolean(Driver.IsFMSessionOpen)]; 7: Result := BitStr[7,Boolean(Driver.IsFM24HoursOver)]; else Result := 'Неправильный номер бита'; end; end; function ConfirmFiscalization(Wnd: THandle): Boolean; var S: string; begin S := 'Фискализацию аппарата нельзя отменить.'#13#10+ 'Вы хотите продолжить?'; Result := MessageBox(Wnd, PChar(S), 'Внимание!', MB_ICONEXCLAMATION or MB_YESNO or MB_DEFBUTTON2) = ID_YES; end; procedure LoadControlParams(const Path: string; Control: TWinControl; Reg: TRegistry); var i: Integer; Item: TControl; ValueName: string; begin for i := 0 to Control.ControlCount-1 do begin Item := Control.Controls[i]; if Item is TWinControl then begin ValueName := Path + '.' + Item.Name; LoadControlParams(ValueName, Item as TWinControl, Reg); if Reg.ValueExists(ValueName) then begin if Item is TEdit and (not TEdit(Item).ReadOnly) then TEdit(Item).Text := Reg.ReadString(ValueName); if Item is TComboBox then TComboBox(Item).ItemIndex := Reg.ReadInteger(ValueName); if Item is TCheckBox then TCheckBox(Item).Checked := Reg.ReadBool(ValueName); if Item is TRadioGroup then TRadioGroup(Item).ItemIndex := Reg.ReadInteger(ValueName); if Item is TDateTimePicker then TDateTimePicker(Item).DateTime := Reg.ReadDateTime(ValueName); end; end; end; end; procedure SaveControlParams(const Path: string; Control: TWinControl; Reg: TRegistry); var i: Integer; EditItem: TEdit; Item: TComponent; ValueName: string; begin for i := 0 to Control.ControlCount-1 do begin Item := Control.Controls[i]; if Item is TWinControl then begin ValueName := Path + '.' + Item.Name; SaveControlParams(ValueName, Item as TWinControl, Reg); if Item is TEdit then begin EditItem := Item as TEdit; if not EditItem.ReadOnly then Reg.WriteString(ValueName, EditItem.Text); end; if Item is TComboBox then Reg.WriteInteger(ValueName, TComboBox(Item).ItemIndex); if Item is TCheckBox then Reg.WriteBool(ValueName, TCheckBox(Item).Checked); if Item is TRadioGroup then Reg.WriteInteger(ValueName, TRadioGroup(Item).ItemIndex); if Item is TDateTimePicker then Reg.WriteDateTime(ValueName, TDateTimePicker(Item).DateTime); end; end; end; function RGBToColor(RGB: DWORD): TColor; begin Result := (RGB and $FF) shl 16 or (RGB and $FF00) or (RGB shr 16); end; end.