text
stringlengths
14
6.51M
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {* Find the minimum and maximum values in the matrix. *} procedure MinMax(Mat:T2DByteArray; var Min, Max:Byte); overload; var X,Y,W,H: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); Min := Mat[0][0]; Max := Mat[0][0]; for Y:=0 to H do for X:=0 to W do if Mat[Y][X] > Max then Max := Mat[Y][X] else if Mat[Y][X] < Min then Min := Mat[Y][X]; end; procedure MinMax(Mat:T2DIntArray; var Min, Max:Integer); overload; var X,Y,W,H: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); Min := Mat[0][0]; Max := Mat[0][0]; for Y:=0 to H do for X:=0 to W do if Mat[Y][X] > Max then Max := Mat[Y][X] else if Mat[Y][X] < Min then Min := Mat[Y][X]; end; procedure MinMax(Mat:T2DExtArray; var Min, Max:Extended); overload; var X,Y,W,H: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); Min := Mat[0][0]; Max := Mat[0][0]; for Y:=0 to H do for X:=0 to W do if Mat[Y][X] > Max then Max := Mat[Y][X] else if Mat[Y][X] < Min then Min := Mat[Y][X]; end; procedure MinMax(Mat:T2DDoubleArray; var Min, Max:Double); overload; var X,Y,W,H: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); Min := Mat[0][0]; Max := Mat[0][0]; for Y:=0 to H do for X:=0 to W do if Mat[Y][X] > Max then Max := Mat[Y][X] else if Mat[Y][X] < Min then Min := Mat[Y][X]; end; procedure MinMax(Mat:T2DFloatArray; var Min, Max:Single); overload; var X,Y,W,H: Integer; begin H := High(Mat); if (length(mat) = 0) then NewException('Matrix must be initalized'); W := High(Mat[0]); Min := Mat[0][0]; Max := Mat[0][0]; for Y:=0 to H do for X:=0 to W do if Mat[Y][X] > Max then Max := Mat[Y][X] else if Mat[Y][X] < Min then Min := Mat[Y][X]; end;
unit MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, DW.SystemHelper, System.Sensors, System.Sensors.Components, FMX.Layouts, FMX.Objects; type TfrmMain = class(TForm) CameraPermissionButton: TButton; RequestLocationPermissionsButton: TButton; RequestSMSPermissionsButton: TButton; LocationSensor: TLocationSensor; StatusBarRectangle: TRectangle; procedure CameraPermissionButtonClick(Sender: TObject); procedure RequestLocationPermissionsButtonClick(Sender: TObject); procedure RequestSMSPermissionsButtonClick(Sender: TObject); private FSystemHelper: TSystemHelper; function GetStatusBarHeight: Integer; procedure PermissionsResultHandler(Sender: TObject; const ARequestCode: Integer; const AResults: TPermissionResults); public constructor Create(AOwner: TComponent); override; end; var frmMain: TfrmMain; implementation {$R *.fmx} uses {$IF Defined(Android)} Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Os, Androidapi.Helpers, {$ENDIF} FMX.Platform; const cRequestCodeCamera = 1; cRequestCodeLocation = 2; cRequestCodeContacts = 3; cRequestCodeSMS = 4; cPermissionCamera = 'android.permission.CAMERA'; cPermissionAccessCoarseLocation = 'android.permission.ACCESS_COARSE_LOCATION'; cPermissionAccessFineLocation = 'android.permission.ACCESS_FINE_LOCATION'; cPermissionReadContacts = 'android.permission.READ_CONTACTS'; cPermissionWriteContacts = 'android.permission.WRITE_CONTACTS'; cPermissionSendSMS = 'android.permission.SEND_SMS'; cPermissionReceiveSMS = 'android.permission.RECEIVE_SMS'; cPermissionReadSMS = 'android.permission.READ_SMS'; cPermissionReceiveWAPPush = 'android.permission.RECEIVE_WAP_PUSH'; cPermissionReceiveMMS = 'android.permission.RECEIVE_MMS'; { TfrmMain } constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FSystemHelper := TSystemHelper.Create; FSystemHelper.OnPermissionsResult := PermissionsResultHandler; StatusBarRectangle.Height := GetStatusBarHeight; end; function TfrmMain.GetStatusBarHeight: Integer; {$IF Defined(Android)} var LRect: JRect; LScale: Single; LScreenService: IFMXScreenService; begin Result := 0; if TJBuild_VERSION.JavaClass.SDK_INT >= 24 then begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, LScreenService) then LScale := LScreenService.GetScreenScale else LScale := 1; LRect := TJRect.Create; TAndroidHelper.Activity.getWindow.getDecorView.getWindowVisibleDisplayFrame(LRect); Result := Round(LRect.top / LScale); end; end; {$ELSE} begin Result := 0; end; {$ENDIF} procedure TfrmMain.PermissionsResultHandler(Sender: TObject; const ARequestCode: Integer; const AResults: TPermissionResults); var I: Integer; LDeniedResults: TPermissionResults; LDeniedPermissions: string; begin case ARequestCode of cRequestCodeCamera: begin if AResults.AreAllGranted then ShowMessage('You granted access to the camera') else ShowMessage('You denied access to the camera!'); end; cRequestCodeLocation: begin if AResults.AreAllGranted then begin ShowMessage('You granted access to location'); LocationSensor.Active := True; end else if AResults.DeniedResults.Count = 1 then ShowMessage('Both types of location access are required!') else if not AResults.AreAllGranted then ShowMessage('You denied access to location!'); end; cRequestCodeSMS: begin if not AResults.AreAllGranted then begin LDeniedPermissions := ''; LDeniedResults := AResults.DeniedResults; for I := 0 to LDeniedResults.Count - 1 do LDeniedPermissions := LDeniedPermissions + #13#10 + LDeniedResults[I].Permission; ShowMessage('You denied access to these SMS permissions: ' + LDeniedPermissions); end else ShowMessage('You granted access to all requested SMS permissions'); end; end; end; procedure TfrmMain.CameraPermissionButtonClick(Sender: TObject); begin FSystemHelper.RequestPermissions([cPermissionCamera], cRequestCodeCamera); end; procedure TfrmMain.RequestLocationPermissionsButtonClick(Sender: TObject); begin FSystemHelper.RequestPermissions([cPermissionAccessCoarseLocation, cPermissionAccessFineLocation], cRequestCodeLocation); end; procedure TfrmMain.RequestSMSPermissionsButtonClick(Sender: TObject); begin FSystemHelper.RequestPermissions([cPermissionSendSMS, cPermissionReceiveSMS, cPermissionReadSMS, cPermissionReceiveWAPPush, cPermissionReceiveMMS], cRequestCodeSMS); end; end.
unit G2Mobile.Model.FormaPagamento; interface uses FMX.ListView, uDmDados, uRESTDWPoolerDB, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, FMX.Objects, G2Mobile.Controller.FormaPagamento, FMX.Graphics; const CONST_LIMPATABELAFORMAPAGAMENTO = 'DELETE FROM FORMAPAGTO'; CONST_BUSCAFORMAPAGAMENTOSERVIDOR = 'SELECT COD_FORMA, DESCRICAO, COD_DOC FROM T_FORMA_PGTO union SELECT 0, ''A VISTA'', ISNULL(DOC_AVISTA,0)DOC_AVISTA FROM T_CONFIG'; CONST_POPULAFORMAPAGAMENTOSQLITE = ' INSERT INTO FORMAPAGTO ( COD_DOC, DESCRICAO, COD_FORMA) VALUES ( :COD_DOC, :DESCRICAO, :COD_FORMA)'; CONST_LIMPATABELAPAGAMENTOPESSOA = 'DELETE FROM pessoa_fpgto'; CONST_BUSCAPAGAMENTOPESSOASERVIDOR = 'SELECT COD_PESSOA, COD_FORMA FROM T_PESSOA_FPGTO'; CONST_POPULAPAGAMENTOPESSOASQlITE = ' INSERT INTO PESSOA_FPGTO ( COD_PESSOA, COD_FORMA) VALUES ( :COD_PESSOA, :COD_FORMA)'; CONST_POPULALISTVIEW = 'select pf.cod_pessoa, pf.cod_forma, fp.descricao from pessoa_fpgto pf left outer join formapagto fp on (pf.cod_forma = fp.cod_forma) ' + ' where cod_pessoa = :CLIENTE union select :CLIENTE, 0, ''A VISTA'' '; CONST_BUSCAFORMAPAGAMENTO = ' SELECT DESCRICAO FROM FORMAPAGTO WHERE COD_FORMA = :COD_FORMA'; type TModelFormaPagamento = class(TInterfacedObject, iModelFormaPagamento) private FQry : TFDQuery; FRdwSQL: TRESTDWClientSQL; public constructor create; destructor destroy; override; class function new: iModelFormaPagamento; function BuscaFormaPagamentoServidor(ADataSet: TFDMemTable): iModelFormaPagamento; function PopulaFormaPagamentoSqLite(ADataSet: TFDMemTable): iModelFormaPagamento; function BuscaPagamentoPessoaServidor(ADataSet: TFDMemTable): iModelFormaPagamento; function PopulaPagamentoPessoaSqLite(ADataSet: TFDMemTable): iModelFormaPagamento; function LimpaTabelaFormaPagamento: iModelFormaPagamento; function LimpaTabelaPagamentoPessoa: iModelFormaPagamento; function PopulaListView(Cod: integer; value: TListView; imageForma: Timage): iModelFormaPagamento; function BuscarFormaPagamento(value: integer): String; function BuscaUltimaFormaDePagamentoCliente(value: integer): String; end; implementation { TFormaPagamento } class function TModelFormaPagamento.new: iModelFormaPagamento; begin result := self.create; end; constructor TModelFormaPagamento.create; begin FQry := TFDQuery.create(nil); FQry.Connection := DmDados.ConexaoInterna; FQry.FetchOptions.RowsetSize := 50000; FQry.Active := false; FQry.SQL.Clear; FRdwSQL := TRESTDWClientSQL.create(nil); FRdwSQL.DataBase := DmDados.RESTDWDataBase1; FRdwSQL.BinaryRequest := True; FRdwSQL.FormatOptions.MaxStringSize := 10000; FRdwSQL.Active := false; FRdwSQL.SQL.Clear; end; destructor TModelFormaPagamento.destroy; begin FreeAndNil(FQry); FreeAndNil(FRdwSQL); inherited; end; function TModelFormaPagamento.LimpaTabelaFormaPagamento: iModelFormaPagamento; begin result := self; FQry.ExecSQL(CONST_LIMPATABELAFORMAPAGAMENTO) end; function TModelFormaPagamento.BuscaFormaPagamentoServidor(ADataSet: TFDMemTable): iModelFormaPagamento; begin result := self; FRdwSQL.SQL.Text := CONST_BUSCAFORMAPAGAMENTOSERVIDOR; FRdwSQL.Active := True; FRdwSQL.RecordCount; ADataSet.CopyDataSet(FRdwSQL, [coStructure, coRestart, coAppend]); end; function TModelFormaPagamento.PopulaFormaPagamentoSqLite(ADataSet: TFDMemTable): iModelFormaPagamento; var i: integer; begin result := self; ADataSet.First; for i := 0 to ADataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_POPULAFORMAPAGAMENTOSQLITE; FQry.ParamByName('COD_DOC').AsInteger := ADataSet.FieldByName('COD_DOC').AsInteger; FQry.ParamByName('DESCRICAO').AsString := ADataSet.FieldByName('DESCRICAO').AsString; FQry.ParamByName('COD_FORMA').AsString := ADataSet.FieldByName('COD_FORMA').AsString; FQry.ExecSQL; ADataSet.Next; end; end; function TModelFormaPagamento.LimpaTabelaPagamentoPessoa: iModelFormaPagamento; begin result := self; FQry.ExecSQL(CONST_LIMPATABELAPAGAMENTOPESSOA) end; function TModelFormaPagamento.BuscaPagamentoPessoaServidor(ADataSet: TFDMemTable): iModelFormaPagamento; begin result := self; FRdwSQL.SQL.Text := CONST_BUSCAPAGAMENTOPESSOASERVIDOR; FRdwSQL.Active := True; FRdwSQL.RecordCount; ADataSet.CopyDataSet(FRdwSQL, [coStructure, coRestart, coAppend]); end; function TModelFormaPagamento.PopulaPagamentoPessoaSqLite(ADataSet: TFDMemTable): iModelFormaPagamento; var i: integer; begin result := self; ADataSet.First; for i := 0 to ADataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_POPULAPAGAMENTOPESSOASQlITE; FQry.ParamByName('COD_PESSOA').AsInteger := ADataSet.FieldByName('COD_PESSOA').AsInteger; FQry.ParamByName('COD_FORMA').AsString := ADataSet.FieldByName('COD_FORMA').AsString; FQry.ExecSQL; ADataSet.Next; end; end; function TModelFormaPagamento.BuscarFormaPagamento(value: integer): String; begin FQry.SQL.Text := CONST_BUSCAFORMAPAGAMENTO; FQry.ParamByName('COD_FORMA').AsInteger := value; FQry.Open; if FQry.RecordCount = 0 then result := EmptyStr else result := FQry.FieldByName('DESCRICAO').AsString; end; function TModelFormaPagamento.BuscaUltimaFormaDePagamentoCliente(value: integer): String; begin FQry.SQL.Text := CONST_POPULALISTVIEW + ' order by pf.cod_forma desc'; FQry.ParamByName('CLIENTE').AsInteger := value; FQry.Open; if FQry.RecordCount = 0 then result := EmptyStr else result := FormatFloat('0000', FQry.FieldByName('cod_forma').AsFloat); end; function TModelFormaPagamento.PopulaListView(Cod: integer; value: TListView; imageForma: Timage): iModelFormaPagamento; var x : integer; item: TListViewItem; txt : TListItemText; img : TListItemImage; bmp : TBitmap; foto: TStream; begin result := self; try FQry.SQL.Text := CONST_POPULALISTVIEW; FQry.ParamByName('CLIENTE').AsInteger := Cod; FQry.Open; FQry.First; value.Items.Clear; value.BeginUpdate; for x := 0 to FQry.RecordCount - 1 do begin item := value.Items.Add; with item do begin txt := TListItemText(Objects.FindDrawable('codigo')); txt.Text := FormatFloat('0000', FQry.FieldByName('cod_forma').AsFloat); txt.TagString := FQry.FieldByName('cod_forma').AsString; txt := TListItemText(Objects.FindDrawable('formadepagamento')); txt.Text := FQry.FieldByName('descricao').AsString; img := TListItemImage(Objects.FindDrawable('Image')); img.Bitmap := imageForma.Bitmap; end; FQry.Next end; finally value.EndUpdate; end; end; end.
{+--------------------------------------------------------------------------+ | Unit: mwEPTokenList | Created: 2.98 | Author: Martin Waldenburg | Copyright 1997, all rights reserved. | Description: Enhanced Pascal token list | Version: 1.1 | Status: FreeWare | DISCLAIMER: This is provided as is, expressly without a warranty of any kind. | You use it at your own risc. +--------------------------------------------------------------------------+} unit mwEPTokenList; interface uses mwPasTokenList; type TmInfoKind = (ikAutomated, ikClass, ikClEmpty, ikClFunction, ikClForward, ikClProcedure, ikClReference, ikCompDirect, ikConst, ikConstructor, ikDestructor, ikError, ikField, ikFunction, ikNull, ikGUID, ikImplementation, ikInterface, ikIntEmpty, ikIntForward, ikObEnd, ikObject, ikPrivate, ikProcedure, ikProperty, ikProtected, ikPublic, ikPublished, ikType, ikUnit, ikUses, ikUnknown, ikVar); TmAdditionalInfo = class(TObject) aiUnit: string; constructor Create; end; { TmInfoPas } TmLPasInfo = class(TObject) ID: TmInfoKind; Data: string; StartIndex: Integer; AI: TmAdditionalInfo; constructor Create; destructor Destroy; override; end; { TmInfoPas } TmEPTokenList = class(TPasTokenList) private FInfo: TmLPasInfo; protected public constructor Create; destructor Destroy; override; function GetClassKind: TmInfoKind; function GetInterfaceKind: TmInfoKind; procedure LoadField; procedure LoadNonFieldDeclaration; function NextMember: TmInfoKind; procedure Reset; property Info: TmLPasInfo read FInfo; end; { TmEPTokenList } implementation constructor TmAdditionalInfo.Create; begin inherited Create; aiUnit := ''; end; constructor TmLPasInfo.Create; begin inherited Create; ID := ikUnknown; StartIndex := -1; end; destructor TmLPasInfo.Destroy; begin AI.Free; AI := nil; inherited Destroy; end; destructor TmEPTokenList.Destroy; begin FInfo.Free; FInfo := nil; inherited Destroy; end; { Destroy } constructor TmEPTokenList.Create; begin inherited Create; FInfo := TmLPasInfo.Create; end; { Create } procedure TmEPTokenList.Reset; begin end; { Reset } function TmEPTokenList.GetClassKind: TmInfoKind; var TempRunIndex: Longint; begin FInfo.ID := ikClass; Result := FInfo.ID; if Searcher.ClassList.Count > 0 then begin Visibility := tkUnKnown; FInfo.StartIndex := RunIndex; NextID(tkClass); TempRunIndex := RunIndex; FInfo.Data := GetSubString(TokenPosition[FInfo.StartIndex], TokenPosition[RunIndex + 1]); NextNonJunk; Case RunID of tkEnd: begin FInfo.ID := ikClEmpty; Next; end; tkAutomated, tkClass, tkPrivate, tkProtected, tkPublic, tkPublished: FInfo.ID := ikClass; tkSemiColon: begin FInfo.ID := ikClForward; EndCount := 0; FInfo.Data := FInfo.Data + ';'; Next; end; tkOf: begin FInfo.ID := ikClReference; repeat Next; until RunID = tkSemiColon; FInfo.Data := FInfo.Data + GetSubString(TokenPosition[TempRunIndex + 1], TokenPosition[RunIndex + 1]); EndCount := 0; Next; end; tkRoundOpen: begin FInfo.ID := ikClass; FInfo.Data := FInfo.Data + '('; NextNonComment; while RunID <> tkRoundClose do begin Case RunID of tkCRLF, tkSpace: FInfo.Data := FInfo.Data + ' '; else FInfo.Data := FInfo.Data + RunToken; end; NextNonComment; end; FInfo.Data := FInfo.Data + ')'; NextNonJunk; if RunID = tkSemiColon then begin FInfo.ID := ikClEmpty; FInfo.Data := FInfo.Data + ';'; Next; end else if RunId = tkEnd then begin FInfo.ID := ikClEmpty; FInfo.Data := FInfo.Data + RunToken + ';'; Next; end else if RunId in IdentDirect then Visibility := tkPublic; end; else if RunId in IdentDirect then begin FInfo.ID := ikClass; Visibility := tkPublic; end; end; Result := FInfo.ID; end; end; { GetClassKind } procedure TmEPTokenList.LoadField; var RunningIndex: Longint; begin FInfo.ID := ikField; FInfo.StartIndex := RunIndex; RoundCount := 0; SquareCount := 0; FInfo.Data := RunToken; NextNonJunk; if RunID = tkComma then begin RunningIndex := RunIndex; while TokenID[RunningIndex] <> tkColon do Inc(RunningIndex); while (not ((TokenID[RunningIndex] = tkSemiColon) and (RoundCount = 0) and (SquareCount = 0))) and (TokenID[RunningIndex] <> tkNull) do begin Case TokenID[RunningIndex] of tkCRLF, tkSpace: FInfo.Data := FInfo.Data + ' '; tkBorComment, tkAnsiComment, tkSlashesComment: Inc(RunningIndex); else FInfo.Data := FInfo.Data + Token[RunningIndex]; end; if (TokenID[RunningIndex] in [tkAutomated, tkClass, tkCompDirect, tkConstructor, tkDestructor, tkEnd, tkFunction, tkPrivate, tkProcedure, tkProperty, tkProtected, tkPublic, tkPublished]) then begin FInfo.ID := ikError; FInfo.Data := ''; Break; end; Inc(RunningIndex); end; end else while (not ((RunId = tkSemiColon) and (RoundCount = 0) and (SquareCount = 0))) and (RunID <> tkNull) do begin Case RunID of tkCRLF, tkSpace: FInfo.Data := FInfo.Data + ' '; else FInfo.Data := FInfo.Data + RunToken; end; if (RunId in [tkAutomated, tkClass, tkCompDirect, tkConstructor, tkDestructor, tkEnd, tkFunction, tkPrivate, tkProcedure, tkProperty, tkProtected, tkPublic, tkPublished]) then begin FInfo.ID := ikError; FInfo.Data := ''; Break; end; NextNonComment; end; FInfo.Data := FInfo.Data + ';'; Next; end; { LoadField } procedure TmEPTokenList.LoadNonFieldDeclaration; begin RoundCount := 0; SquareCount := 0; while (not ((RunId = tkSemiColon) and (RoundCount = 0) and (SquareCount = 0))) and (RunID <> tkNull) do begin Case RunID of tkCRLF, tkSpace: FInfo.Data := FInfo.Data + ' '; else FInfo.Data := FInfo.Data + RunToken; end; NextNonComment; end; FInfo.Data := FInfo.Data + ';'; NextNonComment; while (not (RunId in [tkAutomated, tkClass, tkCompDirect, tkConstructor, tkDestructor, tkEnd, tkFunction, tkPrivate, tkProcedure, tkProperty, tkProtected, tkPublic, tkPublished])) and (RunID <> tkNull) do begin Case RunID of tkCRLF, tkSpace: FInfo.Data := FInfo.Data + ' '; else FInfo.Data := FInfo.Data + RunToken; end; NextNonComment; end; end; { LoadNonFieldDeclaration } function TmEPTokenList.NextMember: TmInfoKind; begin if RunID <> tkNull then begin if IsJunk then NextNonJunk; Case RunID of tkSquareOpen: begin FInfo.ID := ikGUID; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; repeat Next; FInfo.Data := FInfo.Data + RunToken; until RunID = tkSquareClose; NextNonJunk; end; tkAutomated: begin Visibility := tkAutomated; FInfo.ID := ikAutomated; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; end; tkClass: begin FInfo.StartIndex := RunIndex; FInfo.Data := RunToken + ' '; NextNonJunk; Case RunID of tkFunction: begin FInfo.ID := ikClFunction; LoadNonFieldDeclaration; end; tkProcedure: begin FInfo.ID := ikClProcedure; LoadNonFieldDeclaration; end; end; end; tkCompDirect: begin FInfo.ID := ikCompDirect; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; end; tkConstructor: begin FInfo.ID := ikConstructor; FInfo.StartIndex := RunIndex; FInfo.Data := ''; LoadNonFieldDeclaration; end; tkDestructor: begin FInfo.ID := ikDestructor; FInfo.StartIndex := RunIndex; FInfo.Data := ''; LoadNonFieldDeclaration; end; tkEnd: begin Visibility := tkUnKnown; FInfo.ID := ikObEnd; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; FInfo.Data := FInfo.Data + RunToken; Next; end; tkFunction: begin FInfo.ID := ikFunction; FInfo.StartIndex := RunIndex; FInfo.Data := ''; LoadNonFieldDeclaration; end; tkIdentifier: begin FInfo.Data := ''; LoadField; end; tkPrivate: begin Visibility := tkPrivate; FInfo.ID := ikPrivate; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; end; tkProcedure: begin FInfo.ID := ikProcedure; FInfo.StartIndex := RunIndex; FInfo.Data := ''; LoadNonFieldDeclaration; end; tkProperty: begin FInfo.ID := ikProperty; FInfo.StartIndex := RunIndex; FInfo.Data := ''; LoadNonFieldDeclaration; end; tkProtected: begin Visibility := tkProtected; FInfo.ID := ikProtected; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; end; tkPublic: begin Visibility := tkPublic; FInfo.ID := ikPublic; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; end; tkPublished: begin Visibility := tkPublished; FInfo.ID := ikPublished; FInfo.StartIndex := RunIndex; FInfo.Data := RunToken; NextNonJunk; end; else if RunID in IdentDirect then begin FInfo.Data := ''; LoadField; end else begin FInfo.ID := ikError; FInfo.Data := ''; end; end; end; Result := FInfo.ID; end; { NextMember } function TmEPTokenList.GetInterfaceKind: TmInfoKind; begin Result := ikUnKnown; if Searcher.InterfaceList.Count > 0 then begin Visibility := tkUnKnown; FInfo.StartIndex := RunIndex; NextNonJunk; while (RunID <> tkInterFace) and (RunID <> tkDispInterFace) do NextNonJunk; FInfo.Data := GetSubString(TokenPosition[FInfo.StartIndex], TokenPosition[RunIndex + 1]); NextNonJunk; Case RunID of tkEnd: begin FInfo.ID := ikIntEmpty; Next; end; tkSquareOpen: FInfo.ID := ikInterface; tkSemiColon: begin FInfo.ID := ikIntForward; EndCount := 0; FInfo.Data := FInfo.Data + ';'; Next; end; tkRoundOpen: begin FInfo.ID := ikInterface; FInfo.Data := FInfo.Data + '('; NextNonComment; while RunID <> tkRoundClose do begin Case RunID of tkCRLF, tkSpace: FInfo.Data := FInfo.Data + ' '; else FInfo.Data := FInfo.Data + RunToken; end; NextNonComment; end; FInfo.Data := FInfo.Data + ')'; NextNonJunk; if RunID = tkSemiColon then begin FInfo.ID := ikIntEmpty; FInfo.Data := FInfo.Data + ';'; Next; end else if RunId = tkEnd then begin FInfo.ID := ikIntEmpty; FInfo.Data := FInfo.Data + RunToken + ';'; Next; end; end; end; Result := FInfo.ID; end; end; { GetInterfaceKind } end.
unit notifywindow; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, sliding_window; type TNotify_frm_grp = class; Tfrm_notify_class = class of Tfrm_notify; Tfrm_notify = class(TSlidingForm) procedure FormCreate(Sender: TObject); private { Private-Deklarationen } protected group_owner: TNotify_frm_grp; public priority: integer; PROCEDURE CreateParams(VAR Params: TCreateParams); OVERRIDE; destructor Destroy; override; constructor Create(AOwner: TComponent; aGroup: TNotify_frm_grp); reintroduce; end; TNotify_frm_grp = class private owner: TComponent; window_list: TList; procedure Sort; protected procedure RemoveNotifyWindow(frm: Tfrm_notify); public procedure refresh_positions; constructor Create(aOwner: TComponent); destructor Destroy; override; function NewNotifyWindow: Tfrm_notify; overload; function NewNotifyWindow(aClass: Tfrm_notify_class): Tfrm_notify; overload; function Count: integer; function window(index: integer): Tfrm_notify; end; function WindowListCompare(Item1, Item2: Pointer): Integer; implementation {$R *.dfm} constructor Tfrm_notify.Create(AOwner: TComponent; aGroup: TNotify_frm_grp); begin group_owner := aGroup; inherited Create(AOwner); end; PROCEDURE Tfrm_notify.CreateParams(VAR Params: TCreateParams); begin INHERITED; begin (*Params.ExStyle := Params.ExStyle //AND (not WS_EX_APPWINDOW) //OR WS_EX_TOOLWINDOW ;*) Params.WndParent := 0;//Application.Handle; end; end; function TNotify_frm_grp.Count: integer; begin Result := window_list.Count; end; constructor TNotify_frm_grp.Create(aOwner: TComponent); begin inherited Create; window_list := TList.Create; owner := aOwner; end; destructor TNotify_frm_grp.Destroy; begin while window_list.Count > 0 do window(0).free; window_list.free; inherited; end; function TNotify_frm_grp.NewNotifyWindow: Tfrm_notify; begin Result := NewNotifyWindow(Tfrm_notify); end; function TNotify_frm_grp.NewNotifyWindow(aClass: Tfrm_notify_class): Tfrm_notify; var frm: Tfrm_notify; begin frm := aClass.Create(nil, Self); window_list.Add(frm); frm.Left := (Screen.Width - frm.Width) div 2; frm.Top := (Screen.Height - frm.Height) div 2; refresh_positions; Result := frm; end; procedure TNotify_frm_grp.refresh_positions; var i: integer; height: integer; frm: Tfrm_notify; begin Sort; height := 0; for i := window_list.Count-1 downto 0 do begin frm := Tfrm_notify(window_list.Items[i]); height := height + frm.Height+5; frm.SlideTo(Screen.Width - frm.Width, Screen.Height - height - 35); end; end; procedure TNotify_frm_grp.RemoveNotifyWindow(frm: Tfrm_notify); begin window_list.Remove(frm); refresh_positions; end; procedure TNotify_frm_grp.Sort; begin window_list.Sort(WindowListCompare); end; function TNotify_frm_grp.window(index: integer): Tfrm_notify; begin Result := Tfrm_notify(window_list[index]); end; destructor Tfrm_notify.Destroy; begin if group_owner <> nil then group_owner.RemoveNotifyWindow(self); inherited; end; procedure Tfrm_notify.FormCreate(Sender: TObject); begin ShowWindow(Handle, SW_HIDE) ; SetWindowLong(Handle, GWL_EXSTYLE, getWindowLong(Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW) ; ShowWindow(Handle, SW_SHOW) ; DoubleBuffered := True; end; function WindowListCompare(Item1, Item2: Pointer): Integer; begin Result := Tfrm_notify(Item1).priority - Tfrm_notify(Item2).priority; end; end.
unit MFichas.Controller.Types; interface type TEvDoClickConfirm = procedure(Sender: TObject) of object; TEvDoClickCancel = procedure(Sender: TObject) of object; TTypeStatusCaixa = (scFechado, scAberto); TTypeOperacoesCaixa = (ocSangria, ocSuprimento); TTypeTipoVenda = (tvCancelamento, tvVenda, tvDevolucao); TTypeStatusVenda = (svFechada, svAberta, svCancelada, svDevolvida); TTypeTipoPagamento = (tpDinheiro, tpCartaoDebito, tpCartaoCredito); TTypeStatusPagamento = (spEstornado, spProcessado); TTypeStatusAtivoInativo = (saiInativo, saiAtivo); TTypeTipoUsuario = (tuCaixa, tuFiscal, tuGerente); TTypePermissoesUsuario = ( puAbrirCaixa, puFecharCaixa, puSuprimentoCaixa, puSangriaCaixa, puCadastrarProdutos, puCadastrarGrupos, puCadastrarUsuarios, puAcessarRelatorios, puAcessarConfiguracoes, puExcluirProdutosPosImpressao ); TTypeTipoPedido = (tpDevolucao, tpNovoPedido); implementation end.
unit libSeznam; interface type data = integer; uPrvek = ^Prvek; Prvek = record data : data; dalsi : uPrvek; end; Seznam = object hlava, konec : uPrvek; constructor init; function vyjmiPrvni : uPrvek; function nty(kolikaty : integer) : uPrvek; procedure vlozNaKonec(var co : data); procedure vlozNaZacatek(var co : data); procedure vlozZa(p : uPrvek; var co : data); procedure vlozNamisto(p : uPrvek; var co : data); procedure smazZa(p : uPrvek); procedure smaz(p : uPrvek); procedure prohod(var p1,p2 : uPrvek); procedure vypsat; function velikost : integer; function kolikaty(ktery : uPrvek) : integer; end; function seznamZeSouboru(jmenoS : string) : seznam; implementation {----------------------------metody seznamu----------------------------} constructor Seznam.init; begin new(hlava); konec := hlava; hlava^.dalsi := nil; end; procedure Seznam.vlozNaKonec(var co : data); begin konec^.data := co; new(konec^.dalsi); konec := konec^.dalsi; konec^.dalsi := nil; end; procedure Seznam.vlozNaZacatek(var co : data); var pom : uPrvek; begin new(pom); pom^.data := co; pom^.dalsi := hlava; hlava := pom; end; function Seznam.vyjmiPrvni : uPrvek; var pom : uPrvek; begin pom := hlava; hlava:=pom^.dalsi; vyjmiPrvni := pom; end; function Seznam.nty(kolikaty : integer) : uPrvek; var pom : uPrvek; i : integer; begin pom := hlava; i := 1; while i<>kolikaty do begin inc(i); pom := pom^.dalsi; end; nty := pom; end; procedure Seznam.vlozZa(p : uPrvek; var co : data); var novy : uPrvek; begin new(novy); novy^.data := co; novy^.dalsi := p^.dalsi; p^.dalsi := novy; end; procedure Seznam.vlozNamisto(p : uPrvek; var co : data); begin Seznam.vlozZa(p, p^.data); p^.data:=co; end; procedure Seznam.smazZa(p : uPrvek); var q : uPrvek; begin q := p^.dalsi; p^.dalsi := p^.dalsi^.dalsi; dispose(q); end; procedure Seznam.smaz(p : uPrvek); begin if p^.dalsi <> konec then begin p^.data := p^.dalsi^.data; smazZa(p); end else begin dispose(konec); konec:=p; konec^.dalsi := nil; end; end; procedure Seznam.prohod(var p1,p2 : uPrvek); var pom : Prvek; begin pom.data := p2^.data; p2^.data := p1^.data; p1^.data := pom.data; end; procedure Seznam.vypsat; var pom : uPrvek; begin pom := hlava; while pom^.dalsi<>nil do begin writeln(pom^.data); pom:=pom^.dalsi; end; end; function Seznam.velikost : integer; var pom : uPrvek; i : integer; begin pom := hlava; i := 1; while pom^.dalsi <> konec do begin inc(i); pom := pom^.dalsi; end; velikost := i; end; function Seznam.kolikaty(ktery : uPrvek) : integer; var i : integer; x : uPrvek; begin new(x); x := hlava; i:=1; while x<>ktery do begin x:=x^.dalsi; inc(i); end; kolikaty:=i; end; {----------------------------------------------------------------------} function seznamZeSouboru(jmenoS : string) : seznam; var userFile : text; d : data; sez : seznam; begin sez.init; assign(userFile, jmenoS); reset(userFile); repeat readln(userFile, d); sez.vlozNaKonec(d); until eof(userFile); close(userFile); seznamZeSouboru := sez; end; end.
{$I TMSDEFS.INC} {***********************************************************************} { TPlanner component } { for Delphi & C++Builder & Kylix } { for Delphi & C++Builder } { } { written by TMS Software } { copyright © 1999-2012 } { Email: info@tmssoftware.com } { Web: http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed,} { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {***********************************************************************} unit PlanObj; interface uses Classes, Graphics; const NumColors = 288; type TNumColorsRange = 0..NumColors; TCellState = record Color: TColor; Selected: Integer; end; TPlannerColorArray = array[TNumColorsRange] of TCellState; PPlannerColorArray = ^TPlannerColorArray; TColorChangeEvent = procedure(Sender: TObject; Index: Integer) of object; TPlannerColorArrayList = class(TList) private FOnChange: TColorChangeEvent; procedure SetArray(Index: Integer; Value: PPlannerColorArray); function GetArray(Index: Integer): PPlannerColorArray; public constructor Create; destructor Destroy; override; property Items[Index: Integer]: PPlannerColorArray read GetArray write SetArray; function Add: PPlannerColorArray; procedure Delete(Index: Integer); property OnChange: TColorChangeEvent read FOnChange write FOnChange; end; implementation { TPlannerColorArrayList } function TPlannerColorArrayList.Add: PPlannerColorArray; begin New(Result); inherited Add(Result); end; constructor TPlannerColorArrayList.Create; begin inherited; end; procedure TPlannerColorArrayList.Delete(Index: Integer); begin if Assigned(Items[Index]) then Dispose(Items[Index]); inherited Delete(Index); end; destructor TPlannerColorArrayList.Destroy; var Index: Integer; begin for Index := 0 to Self.Count - 1 do if Assigned(Items[Index]) then Dispose(Items[Index]); inherited; end; function TPlannerColorArrayList.GetArray( Index: Integer): PPlannerColorArray; begin Result := PPlannerColorArray(inherited Items[Index]); end; procedure TPlannerColorArrayList.SetArray(Index: Integer; Value: PPlannerColorArray); begin inherited Items[Index] := Value; end; end.
unit AddAddressNoteUnit; interface uses SysUtils, BaseExampleUnit; type TAddAddressNote = class(TBaseExample) public procedure Execute(RouteId: String; AddressId: integer); end; implementation uses NoteParametersUnit, AddressNoteUnit, EnumsUnit; procedure TAddAddressNote.Execute(RouteId: String; AddressId: integer); var ErrorString: String; Parameters: TNoteParameters; Contents: String; Note: TAddressNote; begin Parameters := TNoteParameters.Create(); try Parameters.RouteId := RouteId; Parameters.AddressId := AddressId; Parameters.Latitude := 33.132675170898; Parameters.Longitude := -83.244743347168; Parameters.DeviceType := TDeviceType.Web; Parameters.ActivityType := TStatusUpdateType.DropOff; Contents := 'Test Note Contents ' + DateTimeToStr(Now); Note := Route4MeManager.AddressNote.Add(Parameters, Contents, ErrorString); try WriteLn(''); if (Note <> nil) then begin WriteLn('AddAddressNote executed successfully'); WriteLn(Format('Note ID: %d', [Note.NoteId.Value])); end else WriteLn(Format('AddAddressNote error: "%s"', [ErrorString])); finally FreeAndNil(Note); end; finally FreeAndNil(Parameters); end; end; end.
{ File: ConditionalMacros.p Contains: Set up for compiler independent conditionals Version: Technology: Universal Interface Files Release: Universal Interfaces 3.4.2 Copyright: © 1993-2002 by Apple Computer, Inc., all rights reserved Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit ConditionalMacros; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} {$ALIGN MAC68K} {*************************************************************************************************** UNIVERSAL_INTERFACES_VERSION 0x0400 --> version 4.0 (Mac OS X only) 0x0341 --> version 3.4.1 0x0340 --> version 3.4 0x0331 --> version 3.3.1 0x0330 --> version 3.3 0x0320 --> version 3.2 0x0310 --> version 3.1 0x0301 --> version 3.0.1 0x0300 --> version 3.0 0x0210 --> version 2.1 This conditional did not exist prior to version 2.1 ***************************************************************************************************} {*************************************************************************************************** TARGET_CPU_Å These conditionals specify which microprocessor instruction set is being generated. At most one of these is true, the rest are false. TARGET_CPU_PPC - Compiler is generating PowerPC instructions TARGET_CPU_68K - Compiler is generating 680x0 instructions TARGET_CPU_X86 - Compiler is generating x86 instructions TARGET_CPU_MIPS - Compiler is generating MIPS instructions TARGET_CPU_SPARC - Compiler is generating Sparc instructions TARGET_CPU_ALPHA - Compiler is generating Dec Alpha instructions TARGET_OS_Å These conditionals specify in which Operating System the generated code will run. At most one of the these is true, the rest are false. TARGET_OS_MAC - Generate code will run under Mac OS TARGET_OS_WIN32 - Generate code will run under 32-bit Windows TARGET_OS_UNIX - Generate code will run under some unix TARGET_RT_Å These conditionals specify in which runtime the generated code will run. This is needed when the OS and CPU support more than one runtime (e.g. MacOS on 68K supports CFM68K and Classic 68k). TARGET_RT_LITTLE_ENDIAN - Generated code uses little endian format for integers TARGET_RT_BIG_ENDIAN - Generated code uses big endian format for integers TARGET_RT_MAC_CFM - TARGET_OS_MAC is true and CFM68K or PowerPC CFM (TVectors) are used TARGET_RT_MAC_MACHO - TARGET_OS_MAC is true and Mach-O style runtime TARGET_RT_MAC_68881 - TARGET_OS_MAC is true and 68881 floating point instructions used TARGET__API_Å_Å These conditionals are used to differentiate between sets of API's on the same processor under the same OS. The first section after _API_ is the OS. The second section is the API set. Unlike TARGET_OS_ and TARGET_CPU_, these conditionals are not mutally exclusive. This file will attempt to auto-configure all TARGET_API_Å_Å values, but will often need a TARGET_API_Å_Å value predefined in order to disambiguate. TARGET_API_MAC_OS8 - Code is being compiled to run on System 7 through Mac OS 8.x TARGET_API_MAC_CARBON - Code is being compiled to run on Mac OS 8 and Mac OS X via CarbonLib TARGET_API_MAC_OSX - Code is being compiled to run on Mac OS X PRAGMA_Å These conditionals specify whether the compiler supports particular #pragma's PRAGMA_IMPORT - Compiler supports: #pragma import on/off/reset PRAGMA_ONCE - Compiler supports: #pragma once PRAGMA_STRUCT_ALIGN - Compiler supports: #pragma options align=mac68k/power/reset PRAGMA_STRUCT_PACK - Compiler supports: #pragma pack(n) PRAGMA_STRUCT_PACKPUSH - Compiler supports: #pragma pack(push, n)/pack(pop) PRAGMA_ENUM_PACK - Compiler supports: #pragma options(!pack_enums) PRAGMA_ENUM_ALWAYSINT - Compiler supports: #pragma enumsalwaysint on/off/reset PRAGMA_ENUM_OPTIONS - Compiler supports: #pragma options enum=int/small/reset FOUR_CHAR_CODE This conditional does the proper byte swapping to assue that a four character code (e.g. 'TEXT') is compiled down to the correct value on all compilers. FourCharCode('abcd') - Convert a four-char-code to the correct 32-bit value TYPE_Å These conditionals specify whether the compiler supports particular types. TYPE_LONGLONG - Compiler supports "long long" 64-bit integers TYPE_BOOL - Compiler supports "bool" TYPE_EXTENDED - Compiler supports "extended" 80/96 bit floating point TYPE_LONGDOUBLE_IS_DOUBLE - Compiler implements "long double" same as "double" FUNCTION_Å These conditionals specify whether the compiler supports particular language extensions to function prototypes and definitions. FUNCTION_PASCAL - Compiler supports "pascal void Foo()" FUNCTION_DECLSPEC - Compiler supports "__declspec(xxx) void Foo()" FUNCTION_WIN32CC - Compiler supports "void __cdecl Foo()" and "void __stdcall Foo()" ***************************************************************************************************} {*************************************************************************************************** Backward compatibility for clients expecting 2.x version on ConditionalMacros.h GENERATINGPOWERPC - Compiler is generating PowerPC instructions GENERATING68K - Compiler is generating 68k family instructions GENERATING68881 - Compiler is generating mc68881 floating point instructions GENERATINGCFM - Code being generated assumes CFM calling conventions CFMSYSTEMCALLS - No A-traps. Systems calls are made using CFM and UPP's PRAGMA_ALIGN_SUPPORTED - Compiler supports: #pragma options align=mac68k/power/reset PRAGMA_IMPORT_SUPPORTED - Compiler supports: #pragma import on/off/reset CGLUESUPPORTED - Clients can use all lowercase toolbox functions that take C strings instead of pascal strings ***************************************************************************************************} {*************************************************************************************************** OLDROUTINENAMES - "Old" names for Macintosh system calls are allowed in source code. (e.g. DisposPtr instead of DisposePtr). The names of system routine are now more sensitive to change because CFM binds by name. In the past, system routine names were compiled out to just an A-Trap. Macros have been added that each map an old name to its new name. This allows old routine names to be used in existing source files, but the macros only work if OLDROUTINENAMES is true. This support will be removed in the near future. Thus, all source code should be changed to use the new names! You can set OLDROUTINENAMES to false to see if your code has any old names left in it. ***************************************************************************************************} {*************************************************************************************************** TARGET_CARBON - default: false. Switches all of the above as described. Overrides all others - NOTE: If you set TARGET_CARBON to 1, then the other switches will be setup by ConditionalMacros, and should not be set manually. If you wish to do development for pre-Carbon Systems, you can set the following: OPAQUE_TOOLBOX_STRUCTS - default: false. True for Carbon builds, hides struct fields. OPAQUE_UPP_TYPES - default: false. True for Carbon builds, UPP types are unique and opaque. ACCESSOR_CALLS_ARE_FUNCTIONS - default: false. True for Carbon builds, enables accessor functions. CALL_NOT_IN_CARBON - default: true. False for Carbon builds, hides calls not supported in Carbon. Specifically, if you are building a non-Carbon application (one that links against InterfaceLib) but you wish to use some of the accessor functions, you can set ACCESSOR_CALLS_ARE_FUNCTIONS to 1 and link with CarbonAccessors.o, which implements just the accessor functions. This will help you preserve source compatibility between your Carbon and non-Carbon application targets. MIXEDMODE_CALLS_ARE_FUNCTIONS - deprecated. ***************************************************************************************************} end.
unit ufrmDefaultLaporan; 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, ClientModule, uAppUtils, uDBUtils, uDMReport, Data.FireDACJSONReflect, System.DateUtils; type TfrmDefaultLaporan = class(TfrmDefault) cbbGudang: TcxExtLookupComboBox; lblGudang: TLabel; lblCabang: TLabel; cbbCabang: TcxExtLookupComboBox; procedure FormCreate(Sender: TObject); procedure cbbCabangPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); private { Private declarations } protected FCDSCabang: tclientDataSet; FCDSGudang: tclientDataSet; procedure InisialisasiGudang; procedure InisialisasiCabang; public { Public declarations } end; var frmDefaultLaporan: TfrmDefaultLaporan; implementation {$R *.dfm} procedure TfrmDefaultLaporan.cbbCabangPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin inherited; FCDSGudang.Filtered := False; FCDSGudang.Filter := 'cabang = ' + QuotedStr(cbbCabang.EditValue); FCDSGudang.Filtered := True; end; procedure TfrmDefaultLaporan.FormCreate(Sender: TObject); begin inherited; dtpAwal.DateTime := StartOfTheMonth(Now); dtpAkhir.DateTime := EndOfTheDay(Now); InisialisasiGudang; InisialisasiCabang; end; procedure TfrmDefaultLaporan.InisialisasiGudang; begin with ClientDataModule.DSDataCLient do begin FCDSGudang := TDBUtils.DSToCDS(DS_GudangLookUp(), Self); cbbGudang.Properties.LoadFromCDS(FCDSGudang, 'id','nama',['id','cabang'], Self); cbbGudang.Properties.SetMultiPurposeLookup(); end; end; procedure TfrmDefaultLaporan.InisialisasiCabang; begin with ClientDataModule.DSDataCLient do begin FCDSCabang := TDBUtils.DSToCDS(DS_CabangLookUp(), Self); cbbCabang.Properties.LoadFromCDS(FCDSCabang, 'id','cabang',['id'], Self); cbbCabang.Properties.SetMultiPurposeLookup(); cbbCabang.EditValue := ClientDataModule.Cabang.ID; end; end; end.
unit RttiUtils; interface uses Vcl.Forms, System.Classes; type TTypeComponent = (tcEdit, tcMemo, tcButton); Form = class(TCustomAttribute) private FWidth: Integer; FTypeComponent: TTypeComponent; FName: String; procedure SetTypeComponent(const Value: TTypeComponent); procedure SetWidth(const Value: Integer); procedure SetName(const Value: String); public constructor Create( aTypeComponent : TTypeComponent; Name : String; aWidth : Integer); property TypeComponent : TTypeComponent read FTypeComponent write SetTypeComponent; property Width : Integer read FWidth write SetWidth; property Name : String read FName write SetName; end; TRttiUtils = class private public class procedure ClassToFormCreate<T : class> ( aEmbeded : TForm ); end; implementation uses System.RTTI, System.TypInfo, Vcl.StdCtrls; { Form } constructor Form.Create( aTypeComponent : TTypeComponent; Name : String; aWidth : Integer); begin FTypeComponent := aTypeComponent; FWidth := aWidth; FName := Name; end; procedure Form.SetName(const Value: String); begin FName := Value; end; procedure Form.SetTypeComponent(const Value: TTypeComponent); begin FTypeComponent := Value; end; procedure Form.SetWidth(const Value: Integer); begin FWidth := Value; end; { TRttiUtils } class procedure TRttiUtils.ClassToFormCreate<T>(aEmbeded: TForm); var ctxContext : TRttiContext; typRtti : TRttiType; Info : PTypeInfo; prpRtti : TRttiProperty; cusAtt : TCustomAttribute; aEdit : TEdit; aLabel : TLabel; aButton : TButton; aMemo : TMemo; FCountTop : Integer; FCountLeft : Integer; begin ctxContext := TRttiContext.Create; Info := System.TypeInfo(T); FCountTop := 10; FCountLeft := 10; try typRtti := ctxContext.GetType(Info); for prpRtti in typRtti.GetProperties do for cusAtt in prpRtti.GetAttributes do begin if cusAtt is Form then begin if Form(cusAtt).TypeComponent = tcEdit then begin aLabel := TLabel.Create(aEmbeded); aLabel.Parent := aEmbeded; aLabel.Caption := Form(cusAtt).Name; aLabel.Name := 'lbl'+ Form(cusAtt).Name; aLabel.Top := FCountTop; aLabel.Left := FCountLeft; FCountTop := FCountTop + 15; aEdit := TEdit.Create(aEmbeded); aEdit.Parent := aEmbeded; aEdit.Name := 'edt'+ Form(cusAtt).Name; aEdit.Width := Form(cusAtt).Width; aEdit.Top := FCountTop; aEdit.Text := ''; aEdit.Left := FCountLeft; FCountTop := FCountTop + 30; end; if Form(cusAtt).TypeComponent = tcButton then begin aButton := TButton.Create(aEmbeded); aButton.Caption := Form(cusAtt).Name; aButton.Name := 'btn' + Form(cusAtt).Name; aButton.Top := FCountTop; aButton.Left := FCountLeft; aButton.Parent := aEmbeded; aButton.Width := Form(cusAtt).Width; FCountTop := FCountTop + 30; end; if Form(cusAtt).TypeComponent = tcMemo then begin aLabel := TLabel.Create(aEmbeded); aLabel.Parent := aEmbeded; aLabel.Caption := Form(cusAtt).Name; aLabel.Name := 'lbl'+ Form(cusAtt).Name; aLabel.Top := FCountTop; aLabel.Left := FCountLeft; FCountTop := FCountTop + 15; aMemo := TMemo.Create(aEmbeded); aMemo.Name := 'memo' + Form(cusAtt).Name; aMemo.Top := FCountTop; aMemo.Left := FCountLeft; aMemo.Parent := aEmbeded; aMemo.Width := Form(cusAtt).Width; aMemo.Lines.Clear; FCountTop := FCountTop + 100; end; end; end; finally ctxContext.Free; end; end; end.
unit GX_EditorShortcut; interface uses Classes, Controls, StdCtrls, ComCtrls, Forms, GX_BaseForm; type TfmEditorShortcut = class(TfmBaseForm) gbxShortCut: TGroupBox; lblShortCut: TLabel; btnCancel: TButton; btnOK: TButton; hkyShortCut: THotKey; btnDefault: TButton; procedure btnDefaultClick(Sender: TObject); public FDefault: TShortCut; class function Execute(Owner: TWinControl; const Expert: string; var ShortCut: TShortCut; const Default: TShortCut): Boolean; end; implementation {$R *.dfm} uses SysUtils, Menus, GX_dzVclUtils; { TfmEditorShortcut } class function TfmEditorShortcut.Execute(Owner: TWinControl; const Expert: string; var ShortCut: TShortCut; const Default: TShortCut): Boolean; var Dlg: TfmEditorShortcut; begin Dlg := TfmEditorShortcut.Create(Owner); try Dlg.FDefault := Default; Dlg.gbxShortCut.Caption := Expert; THotkey_SetHotkey(Dlg.hkyShortCut, ShortCut); Dlg.btnDefault.Caption := ShortCutToText(Default); Result := (Dlg.ShowModal = mrOk); if Result then ShortCut := THotkey_GetHotkey(Dlg.hkyShortCut); finally FreeAndNil(Dlg); end; end; procedure TfmEditorShortcut.btnDefaultClick(Sender: TObject); begin hkyShortCut.HotKey := FDefault; end; end.
unit cmdlinecfgparser; interface {$mode delphi} uses Classes, SysUtils, cmdlinecfg, cmdlinecfgutils; type { TCmdLineOptionParse } TOptionParse = class(TObject) key : string; opt : TCmdLineCfgOption; isDelimited : Boolean; // the value comes with a white-space after the key isParameter : Boolean; constructor Create(aopt: TCmdLineCfgOption; const akey: string; AisDelim: Boolean; AisParam: Boolean); end; { TCmdLineArgsParser } TCmdLineArgsParser = class(TObject) private fKeyPrefix : TStrings; fCfg : TCmdLineCfg; fisValid : Boolean; fMasters : TStringList; MaxMasterLen : Integer; MinMasterLen : Integer; fOptions : TStringList; MaxKeyLen : Integer; MinKeyLen : Integer; protected procedure SetCfg(ACfg: TCmdLineCfg); procedure PrepareConfig; function FindMasterKey(const arg: string): string; function FindParseOption(const arg: string): TOptionParse; function CreateMasterKeyValues(const ArgValue, MasterKey: string; Vals: TList): Boolean; public constructor Create; destructor Destroy; override; // if an argumant doesn't have a corresponding cmd line option; // .Option field will be set to nil. The next "unkey" option will be set as a value; // KeyPrefix - would be used to find values that are not part of arguments only; // the method will create TCmdLineOptionValue objects and add them to values list // it doesn't check for their existance, just adds them! function Parse(Args: TStrings; Vals: TList {of TCmdLineOptionValue}): Boolean; property CmdLineCfg: TCmdLineCfg read fCfg write SetCfg; property KeyPrefix : TStrings read fKeyPrefix; end; // note that KeyPrefix defaults to unix keys = "-". On Windows, many MS commandlines // are using "/" as the key prefix procedure CmdLineMatchArgsToOpts(CmdLineCfg: TCmdLineCfg; Args: TStrings; Vals: TList {of TCmdLineOptionValue}; const KeyPrefix: string = '-'); overload; procedure CmdLineMatchArgsToOpts(CmdLineCfg: TCmdLineCfg; const CmdLine: string; Vals: TList {of TCmdLineOptionValue}; const KeyPrefix: string = '-'); overload; implementation procedure CmdLineMatchArgsToOpts(CmdLineCfg: TCmdLineCfg; Args: TStrings; Vals: TList; const KeyPrefix: string); var parser : TCmdLineArgsParser; begin parser := TCmdLineArgsParser.Create; try parser.CmdLineCfg:=CmdLineCfg; parser.KeyPrefix.Add(KeyPrefix); parser.Parse(Args, Vals); finally parser.Free; end; end; procedure CmdLineMatchArgsToOpts(CmdLineCfg: TCmdLineCfg; const CmdLine: string; Vals: TList; const KeyPrefix: string); var args : TStringList; begin args:=TstringList.Create; try CmdLineParse(cmdLine, args); CmdLineMatchArgsToOpts(cmdlinecfg, args, vals, KeyPrefix); finally args.Free; end; end; { TOptionParse } constructor TOptionParse.Create(aopt: TCmdLineCfgOption; const akey: string; AisDelim: Boolean; AisParam: Boolean); begin inherited Create; opt:=Aopt; key:=akey; isDelimited:=AisDelim; isParameter:=AisParam; end; { TCmdLineArgsParse } procedure TCmdLineArgsParser.SetCfg(ACfg: TCmdLineCfg); begin if fCfg<>ACfg then begin fisValid:=false; fCfg:=ACfg; end; end; procedure MaxMinOptionLen(options: TStrings; var minlen, maxlen: Integer); var i : Integer; j : Integer; ln : Integer; k : string; begin maxlen:=0; minlen:=0; if options.Count=0 then Exit; for i:=0 to options.Count-1 do begin ln:=length(options[i]); if ln>maxlen then maxlen:=ln; end; j:=0; repeat inc(minlen); k:=Copy(options[0],1,minlen); for i:=0 to options.Count-1 do if Pos(k, options[i])<>1 then begin inc(j); break; end; until (j<>0) or (minlen>maxlen); dec(minlen); end; procedure TCmdLineArgsParser.PrepareConfig; var i : integer; ov : TCmdLineCfgOption; k : string; j : integer; y : integer; begin if not Assigned(fCfg) then Exit; fMasters.Clear; fOptions.Clear; fMasters.Duplicates:=dupIgnore; for i:=0 to fCfg.Options.Count-1 do begin ov:=TCmdLineCfgOption(fCfg.Options[i]); if not Assigned(ov) then Continue; k:=Trim(ov.Key); if ov.MasterKey<>'' then fMasters.Add(ov.MasterKey); // preparing keys for values with parameters, like -Cp%test% or -Cp %test% j:=Pos('%', k); y:=Pos(' ', k); if (y>0) and ((y<j) or (j=0)) then k:=Copy(k, 1, y-1) else if j>0 then k:=Copy(k, 1, j-1); fOptions.AddObject(k, TOptionParse.Create(ov, k, y>0, j>0) ); end; MaxMinOptionLen(fMasters, MinMasterLen, MaxMasterLen); MaxMinOptionLen(fOptions, MinKeyLen, MaxKeyLen); fOptions.Sort; fisValid:=true; end; function TCmdLineArgsParser.FindMasterKey(const arg: string): string; var i : integer; t : string; j : integer; begin for i:=MinMasterLen to MaxMasterLen do begin t:=Copy(arg, 1, i); j:=fMasters.IndexOf(t); if j>=0 then begin Result:=fMasters[j]; Exit; end; end; Result:=''; end; function TCmdLineArgsParser.FindParseOption(const arg: string): TOptionParse; var k : string; j : Integer; i : Integer; begin for i:=MinKeyLen to MaxKeyLen do begin k:=Copy(arg, 1, i); j:=fOptions.IndexOf(k); if j>=0 then begin Result:=TOptionParse( fOptions.Objects[j] ); Exit; end; end; Result:=nil; end; function TCmdLineArgsParser.CreateMasterKeyValues(const ArgValue, MasterKey: string; Vals: TList): Boolean; var i : Integer; k : string; j : Integer; op : TOptionParse; begin Result:=False; for i:=length(MasterKey)+1 to length(ArgValue) do begin k:=MasterKey + ArgValue[i]; j:=fOptions.IndexOf(k); if j>=0 then begin Result:=True; op:=TOptionParse(fOptions.Objects[j]); Vals.Add( TCmdLineOptionValue.Create ( op.opt, '1')) end else begin Vals.Add( TCmdLineOptionValue.Create ( nil, k)); end; end; end; constructor TCmdLineArgsParser.Create; begin fKeyPrefix := TStringList.Create; TStringList(fKeyPrefix).CaseSensitive:=true; fMasters := TStringList.Create; TStringList(fMasters).CaseSensitive:=true; fOptions := TStringList.Create; TStringList(fOptions).CaseSensitive:=true; TStringList(fOptions).OwnsObjects:=true; end; destructor TCmdLineArgsParser.Destroy; begin fMasters.Free; fOptions.Clear; fOptions.Free; fKeyPrefix.Free; inherited Destroy; end; function TCmdLineArgsParser.Parse(Args: TStrings; Vals: TList): Boolean; var i : integer; v : string; mk : string; op : TOptionParse; begin Result:=Assigned(fCfg); if not Result then Exit; if not fisValid then PrepareConfig; i:=0; while i<Args.Count do begin v:=Args[i]; mk:=FindMasterKey(v); if mk<>'' then begin // todo: test if there's any known value among keys! CreateMasterKeyValues(v, mk, Vals); end else begin op:=FindParseOption(v); if not Assigned(op) then Vals.Add ( TCmdLineOptionValue.Create(nil, v)) else begin if op.isParameter then begin if op.isDelimited then begin inc(i); if i<Args.Count then v:=args[i] else v:=''; end else v:=Copy(v, length(op.key)+1, length(v)); end else v:='1'; // is switch, is enabled! Vals.Add( TCmdLineOptionValue.Create(op.opt, v)); end; end; inc(i); end; end; end.
program PCODE_TRANSLATOR ( PCODE , PCODE1 , PCODE2 , PCODE3 , OUTPUT , OBJCODE , LIST002 , TRACEF ) ; (********************************************************************) (*$D-,N+ *) (********************************************************************) (* *) (* P_CODE (POST) PROCESSOR *) (* ----------------------- *) (* *) (* COPYRIGHT 1976, STANFORD LINEAR ACCELERATOR CENTER. *) (* *) (* THIS IS A TRANSLATOR FOR THE MODIFIED P-CODE GENERATED BY *) (* THE SLAC PASCAL COMPILER. THE TRANSLATOR TRANSLATES THE *) (* P_CODE INTO IBM/370 ASSEMBLY LANGUAGE OR STANDARD OS/370 *) (* OBJECT MODULE WHICH COULD BE RUN ON THE 370 USING A SMALL *) (* I/O PACKAGE. ALSO THE IMMEDIATE TARGET MACHINE OF THE *) (* TRANSLATOR IS THE 360/370 COMPUTERS, THE MACHINE DEPENDENT *) (* MODULES IN THE PROGRAM ARE RELATIVELY ISOLATED SUCH THAT *) (* CONVERSIONS FOR OTHER REGISTER ORIENTED TARGET MACHINES *) (* SHOULD BE STRAIGHTFORWARD. *) (* *) (* REFER TO THE 'THE PASCAL P COMPILER: IMPLEMENTATION NOTES, *) (* U. AMMANN, K. JENSEN, H. NAGELI, AND K. NORI, DEC. 74.' *) (* FOR THE DEFINITION OF THE P_MACHINE AND THE P SUBSET OF THE *) (* PROGRAMMING LANGUAGE "PASCAL". *) (* *) (********************************************************************) (* *) (* -THE ERROR MESSAGES ISSUED BY THE TRANSLATOR ARE USUALLY *) (* ACCOMPANIED BY THE APPROXIMATE LINE NUMBER OF THE SOURCE *) (* STATEMENT. THESE NUMBERS APPEAR ON THE LEFT OF THE SOURCE *) (* PROGRAM LISTING AND THE ERROR SHOULD BE LOCATED BETWEEN THE *) (* STATEMENT WITH THE GIVEN NUMBER AND THAT NUMBER+1. THESE *) (* ERROR CODES SHOULD BE INTERPRETED ACCORDING TO THE FOLLOWING *) (* TABLE: *) (* *) (* 253- PROCEDURE TOO LONG (LARGER THAN 8K BYTES). *) (* --> SUBDIVIDE THE PROCEDURE. *) (* 254- PROCEDURE TOO LONG (LARGER THAN 8K BYTES) - other place *) (* --> SUBDIVIDE THE PROCEDURE. *) (* 255- PROCEDURE TOO LONG (LARGER THAN 8K BYTES) - other place *) (* --> SUBDIVIDE THE PROCEDURE. *) (* 256- TOO MANY PROCEDURES/FUNCTIONS REFERENCED IN THIS PROC. *) (* --> RECOMPILE THE POST_PROCESSOR WITH A LARGER VALUE *) (* FOR PRCCNT. *) (* 259- EXPRESSION TOO COMPLICATED. *) (* --> SIMPLIFY THE EXPRESSION BY REARRANGING AND/OR *) (* BREAKING. *) (* 263- TOO MANY (COMPILER GENERATED) LABELS IN THIS PROCEDURE. *) (* --> RECOMPILE THE POST_PROCESSOR WITH A LARGER VALUE *) (* FOR LBLCNT. *) (* 300- DIVIDE BY ZERO (RESULT OF CONSTANT PROPAGATION). *) (* --> FIX UP THE (CONSTANT) EXPRESSION EVALUATING TO ZERO. *) (* 301- RANGE ERROR IN STRUCTURED CONSTANT. *) (* --> CORRECT INITIAL VALUE FOR FIELD/ELEMENT OF CONSTANT. *) (* 302- SUBSCRIPTRANGE ERROR (RESULT OF CONSTANT PROPAGATION). *) (* --> FIX UP THE CONSTANT SUBSCRIPT EXPRESSION. *) (* 303- CONSTANT SET TOO LARGE FOR TARGET VARIABLE IN AN ASSMT. *) (* --> CORRECT DECLARATION FOR VARIABLE. *) (* *) (* 504- SIZE OF ARRAY ELEMENT TOO LARGE. *) (* --> REORDER THE DIMENSIONS OF THE ARRAY (SO THAT THE *) (* THE LARGER DIMENSIONS ARE FIRST) OR REDUCE THE RANGE *) (* OF THE LOW ORDER (LAST) INDICES. *) (* *) (* THE FOLLOWING ERRORS NORMALLY INDICATE AN INCONSISTENCY IN *) (* THE COMPILER AND OR THE POST_PROCESSOR. *) (* *) (* 601- TYPE CONFLICT OF OPERANDS IN THE P_PROGRAM. *) (* 602- OPERAND SHOULD BE OF TYPE 'ADR'. *) (* 604- ILLEGAL TYPE FOR RUN TIME CHECKING. *) (* 605- OPERAND SHOULD BE OF TYPE 'BOOL'. *) (* 606- UNDEFINED P_INSTRUCTION CODE. *) (* 607- UNDEFINED STANDARD PROCEDURE NAME. *) (* 608- DISPLACEMENT FIELD OUT OF RANGE *) (* 609- SMALL PROC IS LARGER THAN 4K, RESET SHRT_PROC = 350 *) (* 610- BAD HALFWORD INTEGER ALIGNMENT *) (* 611- BAD INTEGER ALIGNMENT. *) (* 612- BAD REAL ALIGNMENT. *) (* 614- THE PRE_PASS FILE (PRD) IS INCONSISTENT. *) (* 615- OPERAND SHOULD BE OF TYPE 'SET'. *) (* 616- CONSISTENCY CHECK ON 'SET' OPS FAILED. *) (* 617- BAD DISPLACEMENT FOR STRUCTURED CONSTANT. *) (* 618- UNEXPECTED END-OF-LINE WHEN READING P-CODE. *) (* 619- BAD OPERANDS FOR PACK/UNPACK PROCEDURE. *) (* 620- no implementation for P-Code in proc ASMNXTINST *) (* *) (* new errors from 2016 and later (Bernd Oppolzer): *) (* *) (* 701- top of stack is not 1 at beginning of statement *) (* 710- % directive is not %INCLUDE *) (* 711- %INCLUDE does not specify pcodex *) (* 712- %INCLUDE pcodex but not pcode1, 2 or 3 *) (* 75x- registers are not available (different variants) *) (* 750- no single register available *) (* 751- no register pair available (for string operations) *) (* 752- no floating point register available *) (* etc. etc. *) (* *) (* THIS PROGRAM SHOULD NOT BE COMPILED WITH THE 'D+' OPTION. *) (* *) (* *) (* S. HAZEGHI, *) (* *) (* COMPUTATION RESEARCH GROUP *) (* STANFORD LINEAR ACCELARATOR CENTER *) (* STANFORD, CA. 94305. *) (* *) (* *) (* EXTENSIVE MODIFICATIONS MADE BY: *) (* *) (* R. NIGEL HORSPOOL *) (* *) (* SCHOOL OF COMPUTER SCIENCE *) (* MCGILL UNIVERSITY *) (* 805 SHERBROOKE STREET WEST *) (* MONTREAL *) (* QUEBEC H3A 2K6 CANADA *) (* *) (********************************************************************) (* *) (* AUTHOR OF This VERSION (Oppolzer Version): *) (* *) (* Bernd Oppolzer *) (* Diplom-Informatiker *) (* Baerenhofstr. 23 *) (* D-70771 Leinfelden-Echterdingen *) (* Germany *) (* *) (********************************************************************) (* *) (* History records - newest first *) (* *) (********************************************************************) (* *) (* May 2021 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Fix error in GETOP_SIMPLE - generated LR Rx,0 instead of *) (* XR Rx,Rx - which in turn lead to wrong behaviour in *) (* MFI operation, which in turn made PASFORM signal EOF *) (* at the very beginning of the source file :-(( *) (* *) (* It is really time to rewrite the P-Code to 370 translator *) (* *) (* but this is a really big task, because the existing *) (* translator does a really good job with respect to *) (* optimization (the older parts, at least). *) (* *) (********************************************************************) (* *) (* May 2021 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* PASCAL2 abended when compiling PASFORM - no error with *) (* other modules !! *) (* *) (* After some checking I found out that the error seems to *) (* be an initialization problem. The error was resolved by *) (* adding some initializations to the local variables of *) (* procedure ASMNXTINST. *) (* *) (* This motivated me to add an option $I - if this option is *) (* set, the compiler generates code to initialize the *) (* automatic area to hex zeroes on every block entry. *) (* This is a performance nightmare, of course, so this *) (* should be used only as a last resort, if no other *) (* remedy for strange runtime errors can be found. *) (* *) (* The $I option is implemented in PASCAL1 and passed to *) (* PASCAL2 (see the format changes in the ENT instruction), *) (* but not yet fully implemented in PASCAL2. *) (* *) (* BTW: ENT now can handle more "boolean" options without *) (* much effort - see the new ENT format (there is one *) (* string of booleans of variable length) *) (* *) (* ... and a side note: I don't want to invest much time *) (* in PASCAL2, because a new PCODE translator will be built *) (* in the next months, called PASCAL3, with the following *) (* features: *) (* *) (* - completely re-structured *) (* - maybe 31 bit ready *) (* - maybe generates code for other platforms, too *) (* *) (********************************************************************) (* *) (* Mar 2021 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Allow comments in P-Code instructions (Compiler adds *) (* Variable names to certain instructions like LDA, LOD and *) (* STR). Comments are separated by a semicolon. *) (* *) (* First use of READSTR in compiler. (To be portable to *) (* other platforms, it is sufficient that the compiler can *) (* compile itself; it is not necessary that the compiler can *) (* be compiled by other dialects of Pascal. The port can be *) (* done by migrating the P-Code variant of the compiler, *) (* after all). *) (* *) (********************************************************************) (* *) (* Feb 2021 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Some corrections: *) (* *) (* - compare_carr had some errors - corrected (SCRATCHPOS used) *) (* *) (* - VCC had some strange errors - corrected (SCRATCHPOS used) *) (* *) (********************************************************************) (* *) (* Feb 2021 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* PCODE instruction ENT now contains address of 8 byte *) (* scratchpad area, which can be used for temporary *) (* storage. Location is contained in PIAKT record and *) (* named SCRATCHPOS. *) (* *) (* SCRATCHPOS is not used by PASCAL1; instead the position *) (* is passed to PASCAL2 (for every block) in the ENT instruction *) (* and so PASCAL2 can generate code to make use of it. *) (* *) (* SCRATCHSIZE is a constant in PASCAL1 (8 at the moment) *) (* *) (********************************************************************) (* *) (* Oct 2020 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* PCODE output in different parts using %INCLUDE directive *) (* because file size (maximum number of lines) is limited *) (* on the VM/CMS platform *) (* *) (* PASCAL2 has to read the PCODE input and implement the *) (* %INCLUDE statement *) (* *) (********************************************************************) (* *) (* Oct 2020 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* New P-Code instruction MV1 to allow easier initialization *) (* of a series of variables at block entry. MV1 is the same *) (* as MOV, but leaves one of the addresses on the stack *) (* (the source address in this case), this allows for the *) (* source address being incremented for the following moves. *) (* *) (********************************************************************) (* *) (* Aug 2020 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* fixed a strange error caused by the new runtime functions *) (* written in Pascal; the file register (FILADR = reg. 9) *) (* was not set correctly, because after SIO no real runtime *) (* CSP (like RDI) was called ... $PASRDI instead, which does *) (* not need FILADR = reg 9 ... but the following normal CSP *) (* like RLN (readln) expected FILADR being set. *) (* *) (* I fixed this by adding a new variable FILADR_LOADED, which *) (* does not only control the reservation of register FILADR, *) (* but the real loading. *) (* *) (********************************************************************) (* *) (* Apr 2020 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - see PASCAL1 - no changes here *) (* *) (********************************************************************) (* *) (* Jan 2020 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - some corrections to the LAST_FILE structure and its *) (* logic / see SAVE_FILEOPERAND. The P-Codes SIO and EIO *) (* are importand for invalidating the information about *) (* files recently used. *) (* *) (* - CHK E implemented to support runtime exceptions on the *) (* mainframe (new Pascal procedure $ERROR). *) (* *) (********************************************************************) (* *) (* Nov 2019 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - See PASCAL1; support negative length parameter on *) (* VMV operation (varchar move) - if negative then the *) (* the order of the operands on the stack is reversed. *) (* *) (********************************************************************) (* *) (* Sep 2019 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - To allow the compiler to compile the P5 compiler, it *) (* is necessary to allow set expressions [ a .. b ], *) (* where a and b are variable expressions. *) (* *) (* - This implies the creation of a new P-Code instruction *) (* ASR, which sets a range of elements in a set *) (* (add set range ... similar to ASE, add set element). *) (* ASR fetches three arguments from the stack: the set *) (* and two elements: the two elements define the range. *) (* *) (********************************************************************) (* *) (* Jun 2019 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - Code generation errors with a combination of SUBSTR and *) (* concatenation, when inside WRITELN ... example: *) (* *) (* WRITELN ( 'stab/5 = <' , *) (* SUBSTR ( STAB [ N - 1 ] , 1 , 1 ) || *) (* STAB [ N ] || *) (* SUBSTR ( STAB [ N ] , 1 , 1 ) , '>' ) ; *) (* *) (* it turned out, that the WRITELN instruction took the *) (* registers 8 and 9 from the beginning, so that not *) (* enough register pairs could be found to do the *) (* complicated string concatenation, hence the error 259 *) (* in PASCAL2. I allowed the procedure FINDRP (find *) (* register pair) to take the CSP registers 8 and 9, *) (* if needed, which may leed to subsequent load instructions *) (* (when the WRITE CSP has to be finally executed). *) (* *) (* The concatenation was successful, if coded outside the *) (* WRITE :-) after this modification, it worked inside the *) (* WRITE, too. *) (* *) (* - Other errors with concatenation (P-Code VCC) repaired *) (* *) (********************************************************************) (* *) (* May 2019 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - Code generation errors with builtin functions LENGTH *) (* and MAXLENGTH, when the lengths are known at compile time *) (* *) (* When the LENGTH or MAXLENGTH function was related to an *) (* array element, the compiler generated code for the *) (* addressing of the element, although not needed. What made *) (* things worse: this code left an unneeded item (the address *) (* of the element) on the stack, which was not removed and led *) (* to problems in the PASCAL2 code generation (the PCINT *) (* interpreter doesn't complain, although the memory leak *) (* - or stack leak in this case - is clearly visible in *) (* debug mode). *) (* *) (* The solution found is: *) (* *) (* to invalidate the generated code using two new P-Code *) (* instructions XBG and XEN. *) (* *) (* XBG <seqno> is generated, when a critical code sequence *) (* starts. *) (* *) (* If later the compiler decides that the code starting from *) (* the last scheduled XBG is not needed, it generates a *) (* XEN <seqno>,0 ... otherwise XEN <seqno>,1 *) (* *) (* It is important that the compiler knows the seqno of the *) (* XBG to write it on the XEN ... and: it should write the *) (* XEN unconditionally, because PASCAL2 and the P-Code *) (* interpreter will look for it (if no XEN for a particular *) (* XBG is found, the code is generated, that is, an *) (* XEN <seqno>,1 is implied). *) (* *) (********************************************************************) (* *) (* May 2019 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* - Some errors were reported by Ed Lott (thanks) *) (* *) (* a) when the compiler generated calls to the CSP WRV *) (* (write strings), it did not make sure that the *) (* FCB address was loaded (see PASCAL2, LOADFCBADDRESS). *) (* Corrected 13.05.2019 *) (* *) (* b) when accessing static strings, the compiler did not *) (* add the offset of the string in the STATIC CSECT *) (* during address computation (in some situations) *) (* Corrected 14.05.2019 *) (* *) (* c) when accessing the length field of a string, *) (* the compiler did not compute the address correctly *) (* (especially when the string was an array element). *) (* The function GETADR2 must be used in this case. *) (* Corrected 15.05.2019 *) (* *) (* d) wrong code was generated, when a string array *) (* component was passed to a procedure (again, using *) (* GETADR2 solved the problem). *) (* Corrected 17.05.2019 *) (* *) (********************************************************************) (* *) (* Jun.2018 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* MEMCMP added as standard function, similar to MEMCPY. *) (* Two new PCODE instructions added to implement MEMCMP inline *) (* (MCC and MCV) *) (* *) (********************************************************************) (* *) (* Jun.2018 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Some optimization has been applied to the literal pool; *) (* leading to errors 257 first. There was an interesting *) (* story about an old optimization strategy targetting *) (* series of MVCs, which lead to unused literals and errors *) (* 257 ... see compiler Facebook page. *) (* *) (* This was fixed by adding field OPTIMIZED into LITTBL *) (* *) (* Look into procedure SOPERATION, the code following the *) (* comment: CONSECUTIVE MVC INSTS *) (* *) (********************************************************************) (* *) (* May 2018 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* The P-Codes for Strings (starting with the letter V) *) (* are now recognized and translated to 370 machine code; *) (* this was a hard piece of work and finally seems to work *) (* correctly with the 2018.05 release. There still remains *) (* some work to do: some of the length checks which should *) (* be in place for the strings to work correctly are still *) (* not yet implemented. Error handling should be improved and *) (* consolidated. *) (* *) (********************************************************************) (* *) (* Mar.2018 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Implementing the new P-Code instructions to support *) (* Strings aka VarChars ... the new P-Codes all start with *) (* the letter V and are described elsewhere. *) (* *) (* The handling and administration of the literal pool *) (* has been improved, see type literal_pool_control; *) (* character string literals are stored only once, if *) (* they appear more than once in a procedure or function; *) (* this is also true if one string is the beginning or ending *) (* part of another string (the longer string must have *) (* appeared first in the source). *) (* *) (* Many minor improvements to PASCAL2 to make the String *) (* implementation possible :-) *) (* *) (* The new P-Codes: *) (* *) (* 'VC1' , 'VC2' , 'VCC' , 'VLD' *) (* 'VST' , 'VMV' , 'VSM' , 'VLM' *) (* 'VPU' , 'VPO' , 'VIX' , 'VRP' *) (* *) (* see procedure STRINGOPS (and others) *) (* *) (********************************************************************) (* *) (* Dec.2017 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* New P-Code instructions to better support block moves *) (* like memcpy and memset: *) (* *) (* - PCODE_MFI = 80 ; // memory fill - constant length *) (* - PCODE_MCP = 81 ; // memcpy - three parameters *) (* - PCODE_MSE = 82 ; // memset - three parameters *) (* - PCODE_MZE = 84 ; // memory zero - constant length *) (* *) (* and a new DBG instruction, which should be ignored: *) (* *) (* - PCODE_DBG = 83 ; // one parameter, ignored at the moment *) (* *) (********************************************************************) (* *) (* Aug.2017 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Some corrections on the implementation of Pascal sets, *) (* sets can have up to 2000 elements now ... see constants *) (* MXPLNGTH etc. *) (* *) (* More improvements on sets will follow *) (* *) (********************************************************************) (* *) (* May.2017 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* The compiler now runs on MVS (Hercules), too. *) (* Same source code (PASCAL1, PASCAL2) as with CMS, *) (* same runtime (PASMONN) - although there are some *) (* CMS dependencies, controlled by SYSPARM(CMS). *) (* Different PASSNAP ... see below. *) (* *) (* See more comments in PASCAL1.PAS *) (* *) (********************************************************************) (* *) (* Jan.2017 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* From some discussions on the FPC mailing list, I got the *) (* idea to support bit operations on integer operands, too. *) (* *) (* The operations AND, OR, NOT have been extended to do *) (* bit operations, when being used with integers (was error *) (* 134 before). Another operation XOR is provided (new *) (* reserved symbol) for exclusive or operation; can be used *) (* with integer or boolean operands. *) (* *) (* New P-Code instruction XOR; the P-Code instructions *) (* AND, IOR, NOT and XOR have a type parameter (B or I). *) (* *) (* PASCAL2 was extended to support the integer operands *) (* with AND, IOR and NOT and the new P-Code instruction XOR; *) (* the constant XOR had to be renamed to XORX, because *) (* XOR now is a reserved word. *) (* *) (********************************************************************) (* *) (* Dec.2016 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* The generation of the STATIC and CODE CSECTs was changed. *) (* *) (* The STATIC CSECT contains its own size at offset 8; *) (* the real data starts at offset 16 (10 to 15 are free). *) (* *) (* The CODE CSECT contains the Pascal procedure name also *) (* in the NODEBUG case in the CSECT identifier, and the *) (* stacksize at a certain position (see GEN_CSECT and *) (* INIT_CSECT for details). *) (* *) (* This way it is possible for PASSNAP to show the areas *) (* in their correct length also in the NODEBUG case in *) (* hex dump format; and with the real Pascal proc names *) (* (but no Pascal variable names; to do this, the DEBUG *) (* switch and a DBGINFO file is needed). *) (* *) (********************************************************************) (* *) (* Dec.2016 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* Another portability issue: *) (* *) (* the branch table used with case statements implies the *) (* EBCDIC char set, if the case control variable is of type *) (* char. I changed the XJP logic to a portable representation *) (* of the branch table and shifted the construction of the *) (* "real" branch table to the second pass. This way, XJP *) (* instructions and "portable branch tables" can be moved *) (* to foreign platforms with foreign character sets. *) (* *) (* see boolean constant 'PORTABLE_BRANCHTABLE' in pass 1 *) (* *) (* this is the second pass (the P-Code translator); *) (* it recognizes and handles both variants of branch tables, *) (* portable and non-portable *) (* *) (********************************************************************) (* *) (* Nov.2016 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* To enable the port to ASCII platforms, the following *) (* changes have been made: *) (* *) (* - set constants of set of char have a new representation *) (* in the P-Code, envolving char representation of the *) (* chars contained in the set *) (* *) (* - not related to the port: set constants in P-Code are *) (* represented by hexa byte strings instead of integer *) (* strings, which makes them much better readable *) (* *) (* See procedure READSET *) (* *) (********************************************************************) (* *) (* Oct.2016 - Extensions to the Compiler by Bernd Oppolzer *) (* (berndoppolzer@yahoo.com) *) (* *) (* modification to support static variables and to provide *) (* informations for SNAPSHOT, so that static variables can *) (* be found at run time. See pass 1 (PASCAL1.PAS) for details, *) (* and some comments in INIT_CSECT and GEN_CSECT. *) (* *) (********************************************************************) (* *) (* modification in 2016 by bernd oppolzer / stuttgart / germany *) (* *) (* berndoppolzer@yahoo.com *) (* *) (* to allow longer variable names, some constants had to *) (* be changed (and places, where numeric constants were used *) (* instead of symbolic constants had to be identified and *) (* changed, too) *) (* *) (* idlngth changed from 12 to 20 *) (* hdrlngth changed from 32 to 40 *) (* *) (* input routines affected for the following P-Code instructions: *) (* ENT, CST, BGN - format specification IDLNGTH + 2 instead of 14 *) (* *) (* Header for Object Code output extended from 32 to 40 bytes; *) (* Jump over Header adjusts automatically *) (* *) (* longer function names appear in Objekt Code, for example *) (* PASCALCOMPILER (name of pass1) and function names like *) (* ENTERSTDTYPES without truncation *) (* *) (* will SNAPSHOT etc. still work ? *) (* *) (********************************************************************) (* *) (* modification in 2016 by bernd oppolzer / stuttgart / germany *) (* *) (* berndoppolzer@yahoo.com *) (* *) (* there was a need to do an explicit reset(input) at the *) (* beginning of the main procedure, because the compiler *) (* doesn't insert it any more automatically due to some *) (* improvements (in my opinion); but pascal2.pas checks for *) (* eof(input) before first read, and therefore the reset has *) (* to be done before the first read (the implicit reset at the *) (* time of the first read call is not sufficient). *) (* *) (* see some comments in pasmonn.ass for details. *) (* *) (********************************************************************) (* *) (* modification in 2016 by bernd oppolzer / stuttgart / germany *) (* *) (* berndoppolzer@yahoo.com *) (* *) (* the procedure names applied to the object file in case of *) (* the active debug switch had to be extended to 20 chars, *) (* so that SNAPSHOT could get the long names correctly. *) (* the branches around those names had to be adjusted. *) (* *) (********************************************************************) (* *) (* modification in 2011 by bernd oppolzer / stuttgart / germany *) (* *) (* berndoppolzer@yahoo.com *) (* *) (* - activate output of assembler mnemonics to list002 *) (* to make analyzing the object code easier. *) (* the final goal is to create other pcode translators *) (* for other platforms, e.g. windows and linux *) (* *) (********************************************************************) const VERSION = '2021.03' ; // Version for display message VERSION2 = 0x2103 ; // Version for load module VERSION3 = 'XL2''2103''' ; // Version for LIST002 listing MXADR = 65535 ; SHRTINT = 4095 ; HALFINT = 32700 ; STKDPTH = 100 ; // was 15 - reset when work finished MXLVL = 16 ; (*******************************************) (* cixmax: maximum difference of highest *) (* and lowest case label *) (* must be coherent with pass 1 *) (* should be communicated via OBJCODE file *) (* *) (*******************************************) CIXMAX = 400 ; IDLNGTH = 20 ; // length of identifiers RGCNT = 9 ; // register count FPCNT = 6 ; // FLOATING POINT REG. COUNT GBR = 12 ; // GLOBAL BASE REGITER LBR = 13 ; // local base register JREG = 15 ; // JUMP (BRANCH) REGISTER RTREG = 14 ; // RETURN ADDR. REGISTER TRG0 = 0 ; // PARAMETER REGISTER FPR0 = 0 ; // FLOATING POINT REGISTER 0 TRG1 = 1 ; // TEMPORARY VALUE/BASE REGISTERS TRG13 = 13 ; // SAVE AREA/LOCAL STACK FRAME TRG14 = 14 ; TRG15 = 15 ; TRG9 = 9 ; PBR1 = 10 ; PBR2 = 11 ; FILADR = 9 ; CALLSTACKADR = 8 ; (***************************************************) (* Reg 9 = Pascal FCB register *) (* normally available, but not during csp call *) (* Reg 8 = Call Stack Adr *) (* adr of next save area on stack, should be *) (* stable across calls (while in csp, reg 8 is *) (* used to access file cb) *) (***************************************************) MAXSTRL = 254 ; (******************************************************) (* MAXSTRL = maximal string length *) (* MXPLNGTH = maximal set length in chars (8 bits) *) (* MXSETINX = maximal set length (64 bit packets) *) (* MXSETIXI = maximal set length (32 bit packets) *) (******************************************************) MXPLNGTH = 256 ; MXSETINX = 32 ; MXSETIXI = 64 ; MXSETLEN = 256 ; HDRLNGTH = 40 ; // LENGTH OF PROGRAM HEADING EOFDPLMT = 33 ; (**************************************************) (*POSN OF EOF FLAG WITHIN FILE HEADER *) (**************************************************) EOLDPLMT = 34 ; (**************************************************) (*POSN OF EOL FLAG WITHIN HEADER FOR TEXT FILES *) (**************************************************) FILHDRSZ = 8 ; (**************************************************) (*OFFSET OF FILE COMPONENT WITHIN FILE VAR. *) (**************************************************) ADRSIZE = 4 ; CHARSIZE = 1 ; BOOLSIZE = 1 ; INTSIZE = 4 ; HINTSIZE = 2 ; REALSIZE = 8 ; (****************************************************) (* LAYOUT OF THE 'GLOBAL' STACK FRAME: *) (****************************************************) NEWPTR = 72 ; (****************************************************) (* NEWPTR , OFFSET FROM BOTTOM OF RUNTIME STACK *) (****************************************************) HEAPLMT = 76 ; (****************************************************) (* HEAP LIMIT PTR, OFFSET FROM BOTTOM OF STACK *) (****************************************************) DYNRUNC = 0 ; (****************************************************) (* # OF COUNTERS , FIELD OFFSET FROM HEAPLMT *) (****************************************************) DYN2LEN = 8 ; (****************************************************) (* LENGTH OF THE DYN. INFO. AREA AT THE END OF HEAP *) (****************************************************) FNCRSLT = 72 ; (****************************************************) (* FUNCTION RESULT LOCATION, OFFSET FROM MP *) (****************************************************) DISPLAY = 80 ; (****************************************************) (* DISPLAY REGS, OFFSET FROM BOTTOM OF RUNTIME STK *) (****************************************************) DISPAREA = 40 ; (****************************************************) (* SIZE OF DISPLAY TABLE *) (****************************************************) LCAFTMST = 80 ; (****************************************************) (* SIZE OF THE PROCEDURE LINKAGE AREA *) (****************************************************) FPRSAREA = 80 ; (****************************************************) (* FLOATING PT. REGS SAVE AREA, (OPTIONAL SAVE) *) (****************************************************) FPSIZE = 32 ; (****************************************************) (* LENGTH OF FPR SAVE AREA *) (****************************************************) FL1 = 352 ; FL2 = 360 ; FL3 = 368 ; FL4 = 376 ; (****************************************************) (* GLOBAL LOCATIONS USED FOR FIX-FLOAT CONVERSIONS *) (****************************************************) STRFIRST = 384 ; // PTR TO BEGIN OF STR WORKAREA STRCURR = 388 ; // ACTUAL PTR TO STR WORKAREA STRSIZE = 392 ; // STR WORKAREA SIZE (****************************************************) (* addresses for string workarea management *) (****************************************************) INXCHK = 152 ; (****************************************************) (* ADDRESS OF RUNTIME CHECK ROUTINES *) (****************************************************) RNGCHK = 164 ; PRMCHK = 176 ; PTRCHK = 188 ; PTACHK = 200 ; SETCHK = 212 ; STKCHK = 224 ; TRACER = 236 ; (****************************************************) (* CONTROL FLOW TRACE ROUTINE *) (****************************************************) FILEBUFS = 248 ; (****************************************************) (* INPUT, OUTPUT, PRD,.... BUFFERS *) (****************************************************) CLEARBUF = 320 ; (****************************************************) (* PRESET BUFER TO ERASE MEMORY WITH ITS CONTENTS *) (****************************************************) PASDATE = 328 ; (****************************************************) (* PREDEFINED DATE VARIABLE *) (****************************************************) PASTIME = 338 ; (****************************************************) (* PREDEFINED TIME VARIABLE *) (****************************************************) OSPRM = 348 ; (****************************************************) (* POINTER TO O.S. PARMS RECORD *) (****************************************************) FRSTGVAR = 400 ; (****************************************************) (* FIRST GLOBAL VAR, SHOULD BE A MULTIPLE OF 8 *) (* VARIOUS TABLE SIZES AND MISC. CONSTATNTS *) (****************************************************) HTSIZE = 200 ; (****************************************************) (* HASH TABLE SIZE (MUST EXCEED # OPS + # CSP OPS) *) (****************************************************) DBLCNT = 200 ; (****************************************************) (* SIZE OF LITERAL POOL - IN DOUBLE-WORDS *) (****************************************************) DBLDANGER = 190 ; // SAFE LIMIT FOR nxtdbl INTCNT = 400 ; // = DBLCNT*2 HWCNT = 800 ; // = DBLCNT*4 CHCNT = 1600 ; // = DBLCNT*8 LITCNT = 400 ; // # OF NUMERIC LITERALS IN A PROC. LITDANGER = 395 ; // SAFE LIMIT FOR NXTLIT (****************************************************) (* PRCCNT = # OF PROC'S OR ENTRY PT.S IN ONE CSECT *) (* opp 02.2018: was 50, set to 200 *) (* LBLCNT = # OF LABELS IN A CSECT *) (****************************************************) PRCCNT = 200 ; LBLCNT = 500 ; MAX_CALL_DEPTH = 9 ; (****************************************************) (* MAX NESTING OF FUNCTION CALLS IN A STMT. *) (****************************************************) MXCODE = 4092 ; (****************************************************) (* MAX OBJECT CODE SIZE (APPROX. 8K BYTES) *) (****************************************************) MXCODE1 = 4093 ; MXLNP = 800 ; (****************************************************) (* SIZE OF LINE NUMBER TABLE IN BYTES *) (****************************************************) CODE_BYTES = 11199 ; CODE_HINTS = 5599 ; CODE_INTS = 2799 ; CODE_REALS = 1399 ; CODE_CHUNKS = 199 ; SIZE_TXTCHUNK = 56 ; //********************************************************** // definitions for code vector // code_bytes = size of code vector in bytes (minus 1) // code_hints = size of code vector in hints (minus 1) // code_ints = size of code vector in ints (minus 1) // code_reals = size of code vector in reals (minus 1) // code_chunks = size of code vector in txt chunks (minus 1) // size_txtchunk = size of a txt chunk // MAX. BYTES PER TXT CARD IN 360 OBJECT DECK //********************************************************** LESCND = 4 ; LEQCND = 13 ; (*****************************) (* CONDITION CODE SYMBOLS *) (*****************************) GRTCND = 2 ; GEQCND = 11 ; EQUCND = 8 ; NEQCND = 7 ; ANYCND = 15 ; NOCND = 0 ; TRUCND = 1 ; FLSCND = 8 ; (****************************************************) (* LIMIT VALUE FOR A PROC. TO BE CONSIDERED SMALL *) (****************************************************) SHRT_PROC = 550 ; /*******************************************************/ /* asmtag = tag for assembler instructions in list002 */ /* colasmi = position for assembler instr. in list002 */ /* spaceasmi = spaces after asm instr. in list002 */ /*******************************************************/ ASMTAG = '@@ ' ; COLASMI = 10 ; SPACEASMI = 2 ; SPACEASMX = 12 ; SPACEASML = 5 ; (****************************************************) (* OPCODE TABLES (P-OPCODES / P-STANDARD PROCS / *) (* 370-OPCODES ) *) (****************************************************) XBALR = 5 ; XBCTR = 6 ; XBCR = 7 ; XSVC = 10 ; XMVCL = 14 ; XCLCL = 15 ; XLPR = 16 ; XLTR = 18 ; XLCR = 19 ; XNR = 20 ; XCLR = 21 ; XORX = 22 ; XXR = 23 ; XLR = 24 ; XCR = 25 ; XAR = 26 ; XSR = 27 ; XMR = 28 ; XDR = 29 ; XLPDR = 32 ; XLTDR = 34 ; XLCDR = 35 ; XLDR = 40 ; XCDR = 41 ; XADR = 42 ; XSDR = 43 ; XMDR = 44 ; XDDR = 45 ; XSTH = 64 ; XLA = 65 ; XSTC = 66 ; XIC = 67 ; XEX = 68 ; XBAL = 69 ; XBCT = 70 ; XBC = 71 ; XLH = 72 ; XCH = 73 ; XAH = 74 ; XSH = 75 ; XMH = 76 ; XST = 80 ; XN = 84 ; XCL = 85 ; XO = 86 ; XX = 87 ; XL = 88 ; XC = 89 ; XA = 90 ; XS = 91 ; XM = 92 ; XD = 93 ; XSTD = 96 ; XLD = 104 ; XCD = 105 ; XAD = 106 ; XSD = 107 ; XMD = 108 ; XDD = 109 ; XAW = 110 ; XSRL = 136 ; XSLL = 137 ; XSRA = 138 ; XSLA = 139 ; XSRDL = 140 ; XSLDL = 141 ; XSRDA = 142 ; XSLDA = 143 ; XSTM = 144 ; XTM = 145 ; XMVI = 146 ; XCLI = 149 ; XOI = 150 ; XLM = 152 ; XMVC = 210 ; XNC = 212 ; XCLC = 213 ; XOC = 214 ; XXC = 215 ; type OPTYPE = ( PCTS , PCTI , PLOD , PSTR , PLDA , PLOC , PSTO , PLDC , PLAB , PIND , PINC , PPOP , PCUP , PENT , PRET , PCSP , PIXA , PEQU , PNEQ , PGEQ , PGRT , PLEQ , PLES , PUJP , PFJP , PXJP , PCHK , PNEW , PADI , PADR , PSBI , PSBR , PSCL , PFLT , PFLO , PNGI , PNGR , PSQI , PSQR , PABI , PABR , PNOT , PAND , PIOR , PDIF , PINT , PUNI , PINN , PMOD , PODD , PMPI , PMPR , PDVI , PDVR , PMOV , PLCA , PDEC , PSTP , PSAV , PRST , PCHR , PORD , PDEF , PCRD , PXPO , PBGN , PEND , PASE , PSLD , PSMV , PMST , PUXJ , PXLB , PCST , PDFC , PPAK , PADA , PSBA , PXOR , PMFI , PMCP , PMSE , PDBG , PMZE , PVC1 , PVC2 , PVCC , PVLD , PVST , PVMV , PVSM , PVLM , PVPU , PVPO , PVIX , PVRP , PMCC , PMCV , PASR , PXBG , PXEN , PMV1 , UNDEF_OP ) ; CSPTYPE = ( PCTR , PN01 , PN02 , PN03 , PN04 , PN05 , PN06 , PN07 , PN08 , PN09 , PPAG , PGET , PPUT , PRES , PREW , PRDC , PWRI , PWRE , PWRR , PWRC , PWRS , PWRX , PRDB , PWRB , PRDR , PRDH , PRDY , PEOL , PEOT , PRDD , PWRD , PCLK , PWLN , PRLN , PRDI , PEOF , PELN , PRDS , PTRP , PXIT , PFDF , PSIO , PEIO , PMSG , PSKP , PLIM , PTRA , PWRP , PCLS , PDAT , PTIM , PFLR , PTRC , PRND , PWRV , PRDV , PRFC , PRFS , PRFV , UNDEF_CSP ) ; BETA = array [ 1 .. 3 ] of CHAR ; HINTEGER = - 32768 .. 32767 ; STRNG = packed array [ 1 .. MAXSTRL ] of CHAR ; ALFA = packed array [ 1 .. 8 ] of CHAR ; CHAR80 = packed array [ 1 .. 80 ] of CHAR ; ADRRNG = 0 .. MXADR ; LVLRNG = - 2 .. MXLVL ; (********************************************) (* REGISTER NUMBER RANGE *) (********************************************) RGRNG = LVLRNG ; (********************************************) (* set type definitions *) (********************************************) SHORT_SET = set of 0 .. 63 ; LARGE_SET = record case INTEGER of 1 : ( S : array [ 1 .. MXSETINX ] of SHORT_SET ) ; 2 : ( C : array [ 1 .. MXSETLEN ] of CHAR ) ; end ; (********************************************) (* some subranges *) (********************************************) BYTE = 0 .. 255 ; BYTE_PLUS_ONE = 1 .. 256 ; STKPTR = 0 .. STKDPTH ; (********************************************) (* POINTER TO THE COMPILE_TIME STACK *) (********************************************) LVLDSP = record DSPLMT : INTEGER ; LVL : LVLRNG end ; (******************************) (* WHERE ABOUT OF THE OPERAND *) (******************************) ICRNG = 0 .. MXCODE1 ; ICRNG_EXT = - 100 .. MXCODE1 ; ADRRNG_EXT = - 100 .. MXADR ; (********************************************) (* PROGRAM COUNTER RANGE *) (* extended ranges, because negative *) (* values are stored in linkage fields *) (* (pointers to stack entries) *) (********************************************) LBLRNG = - 1 .. LBLCNT ; (********************************************) (* RANGE OF P_COMPILER GENERATED LABELS *) (********************************************) STRLRNG = 0 .. MAXSTRL ; PLNRNG = 0 .. MXPLNGTH ; POSINT = 0 .. 214748360 ; HEX4 = array [ 1 .. 4 ] of CHAR ; MNEM_TABLE = array [ 0 .. 255 ] of array [ 1 .. 4 ] of CHAR ; PLABEL = record NAM : ALFA ; LEN : 0 .. IDLNGTH ; CADDR : ADRRNG ; end ; //************************************************************ // datatype and datum are types to define // the structure of the stack (stk) // used by pascal2 during optimization // bank is where the stack object resides //************************************************************ // 08.2019: because of strange errors due to overlay of // rgadr and memadr - other logic of offset computing - // I decided not to overlay these fields for the moment; // logic below sometimes feeds interesting values into // rgadr and destroys it later by overwriting memadr :-(( //************************************************************ // coding was: // case VPA : BANK of // RGS : // ( RGADR : RGRNG ) ; // MEM : // ( MEMADR : LVLDSP ) //************************************************************ BANK = ( RGS , MEM , ONSTK , NEITHER ) ; DATATYPE = ( BOOL , CHRC , ADR , HINT , INT , PSET , REEL , PROC , CARR , VARC , INX , NON ) ; DATUM = record RCNST : REAL ; PCNST : -> LARGE_SET ; STKADR : ADRRNG ; PLEN : PLNRNG ; FPA : LVLDSP ; SCNSTNO : 0 .. LITCNT ; VRBL , DRCT : BOOLEAN ; PROCNAME : ALFA ; DTYPE : DATATYPE ; VPA : BANK ; RGADR : RGRNG ; // only relevant if VPA = RGS MEMADR : LVLDSP ; // only relevant if VPA = MEM end ; //**************************************************************** //* this new structure records the global state of processing //**************************************************************** GLOBAL_STATE = record IN_PROCBODY : BOOLEAN ; FILL_LINEPTR : BOOLEAN ; MOD1DEFSTEP : INTEGER ; MOD2DEFSTEP : INTEGER ; XBG_XEN_SUPPRESSED : INTEGER ; end ; //**************************************************************** // structure with literal pool control information // nxtdbl, nxtch = indices of next free element // hw_gap = index of halfword gap to be filled (or -1, if no gap) // int_gap = index of integer gap to be filled (or -1, if no gap) // ihconf = index of integer containing halfword gap // riconf = index of double containing integer gap // (if double match, gap must not be used !) // rhconf = index of double containing halfword gap // (if double match, gap must not be used !) //**************************************************************** // if a double entry is used by a new halfword, // two gaps are inserted: a halfword gap and an integer gap // later the halfword gap or the integer gap may be used; // the integer gap may be used by a halfword, leaving another // halfword gap, and so on. if an entry containing a gap // is used otherwise, the gaps have to be invalidated etc. // at a certain point in time, we have always at most one // halfword gap and one integer gap //**************************************************************** LITERAL_POOL_CONTROL = record NXTDBL : 0 .. DBLCNT ; // next double NXTCH : 0 .. CHCNT ; // next char HW_GAP : - 1 .. HWCNT ; INT_GAP : - 1 .. INTCNT ; IHCONF : - 1 .. INTCNT ; RICONF : - 1 .. DBLCNT ; RHCONF : - 1 .. DBLCNT ; end ; //**************************************************************** // chain of procedure definitions // built from pcode file in first pass // before actual pcode processing //**************************************************************** // PRE-PASS (PRD FILE) INFORMATION - now DBGINFO // opp - 2018.03: // pcode summary file contains informations for // procedures that are available at the end of the // parsing of the procedure, but they are needed at // the beginning of the code generation already. to // keep the one pass paradigm of PASCAL1 and PASCAL2, // this informtion is written to a separate file and // read when a new procedure begins (tagged with the // procedure name in the leading column) // - proc size = code size of the procedure // - data size = data size of the procedure // - call higher = other procedure calls, that is, // the display position at the static level has to // be saved and restored //**************************************************************** // later: this information is written into the normal // pcode file, via def constants, after every procedure. // because it is needed before code generation, but it // is located after the procedure (the compiler does not // know it before processing the procedure), the p-code // translator (this program) reads the input twice. // see the main program ... two processing loops //**************************************************************** PPI = -> PROCEDURE_INFO ; PROCEDURE_INFO = record CURPNAME : array [ 1 .. IDLNGTH ] of CHAR ; CURPNO : INTEGER ; OPNDTYPE : DATATYPE ; SEGSZE : PLABEL ; SAVERGS : BOOLEAN ; ASM : BOOLEAN ; ASMVERB : BOOLEAN ; GET_STAT : BOOLEAN ; DEBUG_LEV : 0 .. 9 ; STATNAME : ALFA ; SOURCENAME : ALFA ; FLOW_TRACE : BOOLEAN ; CALL_HIGHER : BOOLEAN ; LARGE_PROC : BOOLEAN ; CODE_SIZE : ADRRNG ; // was icrng DATA_SIZE : ADRRNG ; SCRATCHPOS : ADRRNG ; NEXT : PPI end ; //**************************************************************** // XBG/XEN control // a P-Code instruction XBG starts a conditional code section // which may be ignored, if the corresponding XEN instruction // has a second parameter of zero. The XBG/XEN pairs are read // in the first pass (READNXTINST with modus = 1). The result // is recorded in this chain. //**************************************************************** PXXI = -> XBG_XEN_INFO ; XBG_XEN_INFO = record XBG_NO : INTEGER ; VALID : BOOLEAN ; NEXT : PXXI end ; //************************************************************ // for tables of offsets and statement numbers //************************************************************ STAT_OFFS = record STMT : INTEGER ; OFFS : ICRNG ; end ; var GS : GLOBAL_STATE ; LINECNT : INTEGER ; //************************************************************** // anchor for procedure information chain // built during first p-code reading //************************************************************** PIANKER : PPI ; PIAKT : PPI ; //************************************************************** // anchor for procedure information chain // built during first p-code reading //************************************************************** XXIANKER : PXXI ; XXIAKT : PXXI ; XXILAUF : PXXI ; //************************************************************** // CURRENT/OLD INST. OPCODE // CURRENT STND. PROC. CODE // CURRENT (SYMBOLIC) PCODE /CSP NAME //************************************************************** OPCODE , OLDOPCODE : OPTYPE ; CSP , OLDCSP : CSPTYPE ; P_OPCODE , EMPTY : BETA ; PROCOFFSET : INTEGER ; OP_SP : BOOLEAN ; (*******************************************) (* P INSTR/SP SWITCH *) (*******************************************) INIT : BOOLEAN ; (*******************************************) (* INITIALIZATION PHASE FLAG *) (*******************************************) CH : CHAR ; (*******************************************) (* CURRENT INPUT CHARACTER *) (*******************************************) IVAL : INTEGER ; RVAL : REAL ; PSVAL : LARGE_SET ; PSLNGTH : 0 .. MXPLNGTH ; SVAL : STRNG ; SLNGTH : 0 .. MAXSTRL ; CURLVL : LVLRNG ; (*******************************************) (* CURRENT PROC. STATIC LEVEL *) (*******************************************) TOP : STKPTR ; (*******************************************) (* TOP OF EXPRESSION STACK *) (*******************************************) CALL_DEPTH : 0 .. MAX_CALL_DEPTH ; (*******************************************) (* PROC. CALL NESTING *) (*******************************************) LASTLN , NXTLNP , LASTPC : INTEGER ; LBL1 , LBL2 : PLABEL ; (*******************************************) (* LEFT AND RIGHT LABELS OF INSTRUCTIONS *) (*******************************************) XJPFLAG : CHAR ; EXTLANG : CHAR ; (*******************************************) (* TYPE OF OPERAND OF INSTRUCTION *) (*******************************************) P , Q : INTEGER ; COMPTYPE : CHAR ; OPNDTYPE : DATATYPE ; (*******************************************) (* P_Q FIELDS OF INSTRUCTION *) (* comptype = type of comparison *) (* opndtype = type of operand *) (*******************************************) (*******************************************) (* LOC. OF STRUCT. CONSTANT ITEM *) (*******************************************) (*******************************************) (* MEMORY STACK POINTER, NOT USED *) (*******************************************) LCAFTSAREA : ADRRNG ; (*******************************************) (* FIRST LOC. AFTER PROC. SAVE AREA *) (*******************************************) FILECNT : 0 .. 2 ; (*******************************************) (* COUNT OF ACTIVE FILE ADDRESSES *) (*******************************************) (*******************************************) (* PDEF_CNT = PDEF before branch_table *) (*******************************************) PDEF_CNT : INTEGER ; CASE_LOW : INTEGER ; CASE_HIGH : INTEGER ; CASE_LABEL : INTEGER ; CASE_DEFAULT : INTEGER ; CASE_OPNDTYPE : DATATYPE ; CASE_CHARTABLE : array [ CHAR ] of LBLRNG ; (*******************************************) (* variables for case implementation *) (*******************************************) NXTRG , TXRG : RGRNG ; (*******************************************) (* AQUIRED REGISTERS *) (*******************************************) DBLALN , OPT_FLG : BOOLEAN ; (*******************************************) (* DWRD ALIGNMENT NEEDED, OPT. IN EFFECT *) (*******************************************) CSTBLK , MUSIC : BOOLEAN ; (*******************************************) (* STRUCT. CONST. BLOCK?, MUSIC O.S.? *) (*******************************************) CLEAR_REG , NEG_CND : BOOLEAN ; (*******************************************) (* CLEAR BEFORE LOADING THE REG. *) (*******************************************) SAVEFPRS , DEBUG : BOOLEAN ; (*******************************************) (* indicates, if we are inside of *) (* case branch table / old or new style *) (*******************************************) CASE_FLAG : BOOLEAN ; CASE_FLAG_NEW : BOOLEAN ; (*******************************************) (* if asm output is to be printed *) (* first_list002 = first output to list002 *) (*******************************************) ASM : BOOLEAN ; FIRST_LIST002 : BOOLEAN ; (*******************************************) (* VARIOUS OPTIONS *) (*******************************************) TRACE : BOOLEAN ; CKMODE , FLOW_TRACE : BOOLEAN ; (*******************************************) (* OBJ LISTING, FLOW-TRACING FLAGS *) (* (flow trace will probably not work *) (* at the moment - 2016) *) (*******************************************) (*******************************************) (* CURRENTLY UNUSED *) (*******************************************) POOL_SIZE : ICRNG ; (*******************************************) (* LITERAL POOL SIZE FOR STATISTICS ONLY *) (*******************************************) NUMLITS : INTEGER ; (*******************************************) (* NUMBER OF LITERALS, FOR STATISTICS *) (*******************************************) PCAFTLIT : ICRNG ; (*******************************************) (* Pcounter AFTER LITERAL DUMP *) (*******************************************) MDTAG : OPTYPE ; (*******************************************) (* MULTIPLY/DIVIDE TAG *) (*******************************************) HEAPMARK : -> INTEGER ; TESTCNT : INTEGER ; ZEROBL : LVLDSP ; (*******************************************) (* TO CLEAR BASE ,DISPLACEMENT FIELDS *) (*******************************************) TOTALBYTES , ERRORCNT : INTEGER ; (*******************************************) (* TOTAL ERROR COUNT, ALSO RETURN CODE *) (* COUNT OF 370-ONLY INSTRUCTIONS GENERATED*) (*******************************************) S370CNT : INTEGER ; (*******************************************) (* SET <=> INTEGER <=> REAL, 370 IMPL.ONLY *) (*******************************************) I_S_R : record case INTEGER of 1 : ( I1 : INTEGER ; I2 : INTEGER ) ; 2 : ( R : REAL ) ; 3 : ( C1 , C2 , C3 , C4 : CHAR ) ; 4 : ( S : SHORT_SET ) ; end ; TYPCDE : array [ 'A' .. 'Z' ] of DATATYPE ; (**************************) (* ENCODING OF TYPE FIELD *) (**************************) STK : array [ STKPTR ] of DATUM ; (*********************************) (* EXPRESSION STACK *) (*********************************) PROCOFFSET_OLD : INTEGER ; (*****************************************) (* keep track of register usage *) (* r15 = csp entry *) (* r9 = filadr *) (* r8 = call stack adr *) (* r1 = proc offset = csp number *) (* AVAIL = AVAILABLE REGISTERS *) (* CSPACTIVE = REGS ARE ACTIVE FOR CSP *) (* filadr_loaded = special action *) (* needed because of new $PAS... *) (* runtime functions *) (*****************************************) AVAIL : array [ 0 .. RGCNT ] of BOOLEAN ; AVAILFP : array [ 0 .. FPCNT ] of BOOLEAN ; CSPACTIVE : array [ 0 .. 15 ] of BOOLEAN ; FILADR_LOADED : BOOLEAN ; (*********************************) (* AVAIL. F.P. REGS *) (*********************************) INVBRM : array [ PEQU .. PLES ] of PEQU .. PLES ; (****************************) (* INV. MAP OF REL. OPCODES *) (****************************) BRMSK : array [ PEQU .. PLES ] of 0 .. 15 ; (****************************) (* 370 CONDITION CODES *) (****************************) BRCND : - 1 .. 15 ; (****************************) (* ACTIVE BRANCH MASK *) (****************************) TIMER : POSINT ; HEXCHARS : array [ 0 .. 15 ] of CHAR ; (***************************) (* HASH TABLE, INST./PROCS *) (***************************) HTBL : array [ 0 .. HTSIZE ] of record NAME : BETA ; case BOOLEAN of FALSE : ( OPCDE : OPTYPE ) ; TRUE : ( SPCDE : CSPTYPE ) end ; (***************************************) (* REMEMBERS USEFUL COND-CODE MEANINGS *) (***************************************) LAST_CC : record LAST_PC : ICRNG ; LOP : BYTE ; LR : RGRNG end ; (********************************) (* REMEMBERS CONTENTS OF REG 14 *) (********************************) TXR_CONTENTS : record VALID : BOOLEAN ; LEVEL : LVLRNG ; OFFSET , DISP : ADRRNG ; BASE : RGRNG end ; (**************************************) (* REMEMBERS OPNDS OF LAST STR INSTR. *) (**************************************) LAST_STR : record STOPND : LVLDSP ; STRGX : RGRNG ; LAST_PC : ICRNG ; STDT : DATATYPE ; end ; //******************************************************* // REMEMBERS LAST FILE USED //******************************************************* // comments added 01.2020 - oppolzer // this is used to avoid reloading of register 9 // (filadr) in case of repeated i/O operations to // the same file; // works only, if the I/O operations immediately follow // each other, due to the comparison of LAST_PC being // equal. LAST_PC is set in GOTO_CSP and EIO processing //******************************************************* // There was a problem: the old file operand was not // recorded in the field LAST_FILEOPERAND properly // in all cases. It turned out that a sequence of // SIO and EIO did not invalidate the LAST_FILEOPERAND // recorded here, leading to wrong files accessed. // I added the procedure SAVE_FILEOPERAND to cure this. //******************************************************* LAST_FILE : record LAST_PC : ICRNG ; LAST_FILEOPERAND : LVLDSP ; LAST_FILE_IS_VAR : BOOLEAN end ; (**********************************) (* REMEMBERS LAST MVC INSTRUCTION *) (**********************************) LAST_MVC : record LAST_PC : ICRNG ; LLEN : BYTE ; end ; (******************************************************) (* POINTERS TO LAST ELEMENTS OF 'OBJECT' CODE TABLES *) (******************************************************) NXTPRC , NXTEP : 0 .. PRCCNT ; HEXPC : HEX4 ; (**************************************************) (* PROGRAM COUNTER DIV 2 *) (**************************************************) PCOUNTER : ICRNG ; (***************************************************) (* Pcounter FOR CONSTANT BLOCK *) (***************************************************) CPCOUNTER : HINTEGER ; (***************************************************) (* START FOR CPCOUNTER IN CURRENT SEGMENT *) (***************************************************) CSEGSTRT : HINTEGER ; (***************************************************) (* END FOR CPCOUNTER IN CURRENT SEGMENT *) (***************************************************) CSEGLIMIT : HINTEGER ; MINLBL : LBLRNG ; (**************************************************) (* STARTING LABEL VALUE FOR CURRENT PROC *) (* DECLARATIONS FOR LITERAL TABLES ...ETC. NEEDED *) (* TO GENERATE OBJECT MODULE *) (**************************************************) CST_CURPNAME : array [ 1 .. IDLNGTH ] of CHAR ; CST_CURPNO : INTEGER ; CST_ASMVERB : BOOLEAN ; CST_GET_STAT : BOOLEAN ; MATCH_CURPNO : INTEGER ; (**********************************) (*CURRENT PROC # *) (**********************************) NXTLIT : - 1 .. LITCNT ; //************************************************************** // this structure contains all the fields // which are used to control the literal pool // see type definition above //************************************************************** LX : LITERAL_POOL_CONTROL ; //************************************************************** // code array to hold generated code for procedure //************************************************************** CODE : record case INTEGER of 1 : ( C : array [ 0 .. CODE_BYTES ] of CHAR ) ; 2 : ( H : array [ 0 .. CODE_HINTS ] of HINTEGER ) ; 3 : ( I : array [ 0 .. CODE_INTS ] of INTEGER ) ; 4 : ( R : array [ 0 .. CODE_REALS ] of REAL ) ; 5 : ( TXTCARD : array [ 0 .. CODE_CHUNKS ] of array [ 1 .. SIZE_TXTCHUNK ] of CHAR ) ; end ; //************************************************************** // literal pool for procedure //************************************************************** IDP_POOL : record case INTEGER of 1 : ( C : array [ 0 .. CHCNT ] of CHAR ) ; 2 : ( H : array [ 0 .. HWCNT ] of HINTEGER ) ; 3 : ( I : array [ 0 .. INTCNT ] of INTEGER ) ; 4 : ( R : array [ 0 .. DBLCNT ] of REAL ) ; 5 : ( S : array [ 0 .. DBLCNT ] of SHORT_SET ) ; end ; //************************************************************** // literal vector for literals // ltype = type of literal // length = length // xidp = index into literal pool // lnk = link into code array or zero, if notused //************************************************************** LITTBL : array [ 1 .. LITCNT ] of record LTYPE : CHAR ; LENGTH : HINTEGER ; XIDP : INTEGER ; LNK : ICRNG_EXT ; XLINECNT : INTEGER ; OPTIMIZED : BOOLEAN ; end ; LBLTBL : array [ 0 .. LBLCNT ] of record DEFINED : BOOLEAN ; LNK : ICRNG_EXT end ; PRCTBL : array [ 0 .. PRCCNT ] of record NAME : ALFA ; LNK : ADRRNG_EXT ; VPOS : ICRNG end ; CALL_MST_STACK : array [ 1 .. MAX_CALL_DEPTH ] of record PFLEV : INTEGER ; DISPSAV : ADRRNG end ; (*******************************************************) (* PROGRAM HEADER/DATE/TIME *) (*******************************************************) PROGHDR : array [ 1 .. HDRLNGTH ] of CHAR ; (*******************************************************) (* PCODE = primary pcode input file *) (* PCODE1 = first pcode include file *) (* PCODE2 = second pcode include file *) (* PCODE3 = third pcode include file *) (* OBJCODE = 370 objcode output file *) (* LIST002 = Datei fuer ASSEMBLER-Ausgabe *) (* *) (* STATNAME = Name der Static Csect (falls vorhanden) *) (* posofproclen = Position des ProcLen-Feldes *) (*******************************************************) PCODEP : -> TEXT ; PCODE_FILENO : 0 .. 3 ; EOF_PCODE : BOOLEAN ; PCODE : TEXT ; PCODE1 : TEXT ; PCODE2 : TEXT ; PCODE3 : TEXT ; OBJCODE : TEXT ; LIST002 : TEXT ; TRACEF : TEXT ; POSOFPROCLEN : ICRNG ; //************************************************************** // table of offsets and statement numbers //************************************************************** TOS : array [ 1 .. 4096 ] of STAT_OFFS ; TOS_COUNT : INTEGER ; (*******************************************************) (*____________________________________________________ *) (*******************************************************) const HEXTAB : array [ 0 .. 15 ] of CHAR = '0123456789abcdef' ; DATNULL : DATUM = ( 0.0 , NIL , 0 , 0 , ( 0 , 0 ) , 0 , FALSE , FALSE , ' ' , NON , NEITHER ) ; XTBLN : MNEM_TABLE = ( '(00)' , '(01)' , '(02)' , '(03)' , 'SPM ' , 'BALR' , 'BCTR' , 'BCR ' , 'SSK ' , 'ISK ' , 'SVC ' , '(0B)' , '(0C)' , '(0D)' , 'MVCL' , 'CLCL' , 'LPR ' , 'LNR ' , 'LTR ' , 'LCR ' , 'NR ' , 'CLR ' , 'OR ' , 'XR ' , 'LR ' , 'CR ' , 'AR ' , 'SR ' , 'MR ' , 'DR ' , 'ALR ' , 'SLR ' , 'LPDR' , 'LNDR' , 'LTDR' , 'LCDR' , 'HDR ' , 'LRDR' , 'MXR ' , 'MXDR' , 'LDR ' , 'CDR ' , 'ADR ' , 'SDR ' , 'MDR ' , 'DDR ' , 'AWR ' , 'SWR ' , 'LPER' , 'LNER' , 'LTER' , 'LCER' , 'HER ' , 'LRER' , 'AXR ' , 'SXR ' , 'LER ' , 'CER ' , 'AER ' , 'SER ' , 'MER ' , 'DER ' , 'AUR ' , 'SUR ' , 'STH ' , 'LA ' , 'STC ' , 'IC ' , 'EX ' , 'BAL ' , 'BCT ' , 'BC ' , 'LH ' , 'CH ' , 'AH ' , 'SH ' , 'MH ' , '(4D)' , 'CVD ' , 'CVB ' , 'ST ' , '(51)' , '(52)' , '(53)' , 'N ' , 'CL ' , 'O ' , 'X ' , 'L ' , 'C ' , 'A ' , 'S ' , 'M ' , 'D ' , 'AL ' , 'SL ' , 'STD ' , '(61)' , '(62)' , '(63)' , '(64)' , '(65)' , '(66)' , 'MXD ' , 'LD ' , 'CD ' , 'AD ' , 'SD ' , 'MD ' , 'DD ' , 'AW ' , 'SW ' , 'STE ' , '(71)' , '(72)' , '(73)' , '(74)' , '(75)' , '(76)' , '(77)' , 'LE ' , 'CE ' , 'AE ' , 'SE ' , 'ME ' , 'DE ' , 'AU ' , 'SU ' , 'SSM ' , '(81)' , 'LPSW' , 'DIAG' , 'WRD ' , 'RDD ' , 'BXH ' , 'BXLE' , 'SRL ' , 'SLL ' , 'SRA ' , 'SLA ' , 'SRDL' , 'SLDL' , 'SRDA' , 'SLDA' , 'STM ' , 'TM ' , 'MVI ' , 'TS ' , 'NI ' , 'CLI ' , 'OI ' , 'XI ' , 'LM ' , '(99)' , '(9A)' , '(9B)' , 'SIO ' , 'TIO ' , 'HIO ' , 'TCH ' , '(A0)' , '(A1)' , '(A2)' , '(A3)' , '(A4)' , '(A5)' , '(A6)' , '(A7)' , '(A8)' , '(A9)' , '(AA)' , '(AB)' , '(AC)' , '(AD)' , '(AE)' , '(AF)' , '(B0)' , 'LRA ' , 'STCK' , '(B3)' , '(B4)' , '(B5)' , 'STCT' , 'LCTL' , '(B8)' , '(B9)' , '(BA)' , '(BB)' , '(BC)' , 'CLM ' , 'STCM' , 'ICM ' , '(C0)' , '(C1)' , '(C2)' , '(C3)' , '(C4)' , '(C5)' , '(C6)' , '(C7)' , '(C8)' , '(C9)' , '(CA)' , '(CB)' , '(CC)' , '(CD)' , '(CE)' , '(CF)' , '(D0)' , 'MVN ' , 'MVC ' , 'MVZ ' , 'NC ' , 'CLC ' , 'OC ' , 'XC ' , '(D8)' , '(D9)' , '(DA)' , '(DB)' , 'TR ' , 'TRT ' , 'ED ' , 'EDMK' , '(E0)' , '(E1)' , '(E2)' , '(E3)' , '(E4)' , '(E5)' , '(E6)' , '(E7)' , '(E8)' , '(E9)' , '(EA)' , '(EB)' , '(EC)' , '(ED)' , '(EE)' , '(EF)' , 'SRP ' , 'MVO ' , 'PACK' , 'UNPK' , '(F4)' , '(F5)' , '(F6)' , '(F7)' , 'ZAP ' , 'CP ' , 'AP ' , 'SP ' , 'MP ' , 'DP ' , '(FE)' , '(FF)' ) ; PTBL : array [ OPTYPE ] of BETA = ( 'CTS' , 'CTI' , 'LOD' , 'STR' , 'LDA' , 'LOC' , 'STO' , 'LDC' , 'LAB' , 'IND' , 'INC' , 'POP' , 'CUP' , 'ENT' , 'RET' , 'CSP' , 'IXA' , 'EQU' , 'NEQ' , 'GEQ' , 'GRT' , 'LEQ' , 'LES' , 'UJP' , 'FJP' , 'XJP' , 'CHK' , 'NEW' , 'ADI' , 'ADR' , 'SBI' , 'SBR' , 'SCL' , 'FLT' , 'FLO' , 'NGI' , 'NGR' , 'SQI' , 'SQR' , 'ABI' , 'ABR' , 'NOT' , 'AND' , 'IOR' , 'DIF' , 'INT' , 'UNI' , 'INN' , 'MOD' , 'ODD' , 'MPI' , 'MPR' , 'DVI' , 'DVR' , 'MOV' , 'LCA' , 'DEC' , 'STP' , 'SAV' , 'RST' , 'CHR' , 'ORD' , 'DEF' , 'CRD' , 'XPO' , 'BGN' , 'END' , 'ASE' , 'SLD' , 'SMV' , 'MST' , 'UXJ' , 'XLB' , 'CST' , 'DFC' , 'PAK' , 'ADA' , 'SBA' , 'XOR' , 'MFI' , 'MCP' , 'MSE' , 'DBG' , 'MZE' , 'VC1' , 'VC2' , 'VCC' , 'VLD' , 'VST' , 'VMV' , 'VSM' , 'VLM' , 'VPU' , 'VPO' , 'VIX' , 'VRP' , 'MCC' , 'MCV' , 'ASR' , 'XBG' , 'XEN' , 'MV1' , '-?-' ) ; CSPTBL : array [ CSPTYPE ] of BETA = ( 'N00' , 'N01' , 'N02' , 'N03' , 'N04' , 'N05' , 'N06' , 'N07' , 'N08' , 'N09' , 'PAG' , 'GET' , 'PUT' , 'RES' , 'REW' , 'RDC' , 'WRI' , 'WRE' , 'WRR' , 'WRC' , 'WRS' , 'WRX' , 'RDB' , 'WRB' , 'RDR' , 'RDH' , 'RDY' , 'EOL' , 'EOT' , 'RDD' , 'WRD' , 'CLK' , 'WLN' , 'RLN' , 'RDI' , 'EOF' , 'ELN' , 'RDS' , 'TRP' , 'XIT' , 'FDF' , 'SIO' , 'EIO' , 'MSG' , 'SKP' , 'LIM' , 'TRA' , 'WRP' , 'CLS' , 'DAT' , 'TIM' , 'FLR' , 'TRC' , 'RND' , 'WRV' , 'RDV' , 'RFC' , 'RFS' , 'RFV' , '-?-' ) ; function MEMCMPX ( X : ANYPTR ; Y : ANYPTR ; L : INTEGER ) : INTEGER ; var PLINKS : -> CHAR ; PRECHTS : -> CHAR ; PLIMIT : -> CHAR ; RESULT : INTEGER ; begin (* MEMCMPX *) PLINKS := X ; PRECHTS := Y ; PLIMIT := PTRADD ( PLINKS , L ) ; RESULT := 0 ; while PTRDIFF ( PLIMIT , PLINKS ) > 0 do begin if PLINKS -> < PRECHTS -> then begin RESULT := - 1 ; break end (* then *) else if PLINKS -> > PRECHTS -> then begin RESULT := 1 ; break end (* then *) else begin PLINKS := PTRADD ( PLINKS , 1 ) ; PRECHTS := PTRADD ( PRECHTS , 1 ) ; end (* else *) end (* while *) ; MEMCMPX := RESULT end (* MEMCMPX *) ; function LIST002_HEADLINE ( MODUS : CHAR ; PFNAME_INT : CHAR ( 8 ) ; PFNAME : CHAR ( 20 ) ; PFTYP : CHAR ) : INTEGER ; //*************************************************************** // modus = S: zeilzahl setzen und drucken // modus = V: nur zeilzahl setzen // modus = R: zeilzahl abfragen // sonst = checken, ob zeilzahl gesetzt ist, nur dann drucken // in diesem Fall ein WRITELN weniger, weil ja "von aussen" // noch eines kommt //*************************************************************** static ZEILZAHL : INTEGER ; SEITENZAHL : INTEGER ; SPFNAME_INT : CHAR ( 8 ) ; SPFNAME : CHAR ( 20 ) ; SPFTYP : CHAR ; var HEADLINE : CHAR ( 100 ) ; CTEMP : CHAR ( 16 ) ; begin (* LIST002_HEADLINE *) LIST002_HEADLINE := 0 ; if MODUS = 'R' then begin LIST002_HEADLINE := ZEILZAHL ; return ; end (* then *) ; if MODUS in [ 'S' , 'V' ] then begin ZEILZAHL := 0 ; if PFTYP <> ' ' then begin SPFNAME_INT := PFNAME_INT ; SPFNAME := PFNAME ; SPFTYP := PFTYP ; end (* then *) end (* then *) ; if MODUS = 'V' then return ; ZEILZAHL := ZEILZAHL - 1 ; if ZEILZAHL <= 0 then begin if SEITENZAHL > 0 then begin WRITELN ( LIST002 ) ; WRITELN ( LIST002 ) ; WRITELN ( LIST002 ) ; end (* then *) ; SEITENZAHL := SEITENZAHL + 1 ; HEADLINE := '1Stanford Pascal P-Code to 370 Translator ' 'Oppolzer Version of MM.YYYY ' 'hh:mm:ss DD/MM/YYYY' ; CTEMP := VERSION ; MEMCPY ( ADDR ( HEADLINE [ 66 ] ) , ADDR ( CTEMP ) , 7 ) ; MEMCPY ( ADDR ( HEADLINE [ 78 ] ) , ADDR ( TIME ) , 8 ) ; MEMCPY ( ADDR ( HEADLINE [ 88 ] ) , ADDR ( DATE ) , 10 ) ; WRITELN ( LIST002 , HEADLINE , 'Page ' : 12 , SEITENZAHL : 4 ) ; WRITELN ( LIST002 ) ; if SPFTYP = '#' then WRITELN ( LIST002 , ' Constant and Static Section for ' , SPFNAME , ' (' , SPFNAME_INT , ')' ) else if SPFTYP = 'P' then WRITELN ( LIST002 , ' Proc ' , SPFNAME , ' (' , SPFNAME_INT , ')' ) else WRITELN ( LIST002 , ' Func ' , SPFNAME , ' (' , SPFNAME_INT , ') Result-Type ' , SPFTYP ) ; WRITELN ( LIST002 ) ; if MODUS = 'S' then WRITELN ( LIST002 ) ; ZEILZAHL := 58 ; end (* then *) ; end (* LIST002_HEADLINE *) ; procedure LIST002_NEWLINE ; var DUMMYINT : INTEGER ; begin (* LIST002_NEWLINE *) DUMMYINT := LIST002_HEADLINE ( ' ' , ' ' , ' ' , ' ' ) ; WRITELN ( LIST002 ) end (* LIST002_NEWLINE *) ; procedure LIST002_PRINTLOC ( Q : INTEGER ) ; var REST_ZEILZAHL : INTEGER ; DUMMYINT : INTEGER ; begin (* LIST002_PRINTLOC *) REST_ZEILZAHL := LIST002_HEADLINE ( 'R' , ' ' , ' ' , ' ' ) ; if REST_ZEILZAHL <= 5 then begin DUMMYINT := LIST002_HEADLINE ( 'S' , ' ' , ' ' , ' ' ) ; end (* then *) ; WRITE ( LIST002 , ' ' , '-------------------- LOC ' , Q : 1 , ' --------------------------------' ) ; LIST002_NEWLINE ; end (* LIST002_PRINTLOC *) ; procedure WRITEHEXBYTE ( var F : TEXT ; I : INTEGER ) ; begin (* WRITEHEXBYTE *) WRITE ( F , HEXTAB [ I DIV 16 ] , HEXTAB [ I MOD 16 ] ) ; end (* WRITEHEXBYTE *) ; procedure WRITEBINBYTE ( var F : TEXT ; I : INTEGER ) ; var X : INTEGER ; Y : INTEGER ; begin (* WRITEBINBYTE *) X := 128 ; for Y := 1 to 8 do begin if I >= X then begin WRITE ( F , '1' ) ; I := I - X ; end (* then *) else WRITE ( F , '0' ) ; X := X DIV 2 ; end (* for *) end (* WRITEBINBYTE *) ; procedure ERROR_SYMB ( ERRCDE : INTEGER ; ERR_SYMBOL : BETA ) ; begin (* ERROR_SYMB *) ERRORCNT := ERRORCNT + 1 ; WRITELN ( OUTPUT , ' ++++ Error ' , ERRCDE : 5 , ' (near line ' , LASTLN : 6 , ' of procedure ' , RTRIM ( PIAKT -> . CURPNAME ) , ')' ) ; WRITELN ( TRACEF , ' ++++ Error ' , ERRCDE : 5 , ' (near line ' , LASTLN : 6 , ' of procedure ' , RTRIM ( PIAKT -> . CURPNAME ) , ')' ) ; if ERR_SYMBOL <> ' ' then WRITELN ( OUTPUT , ' ' : 8 , 'Symbol in error = ' , ERR_SYMBOL ) ; if ERRCDE = 253 then WRITELN ( OUTPUT , ' ' : 8 , 'PROCEDURE TOO LARGE.' ) ; if ERRCDE = 254 then WRITELN ( OUTPUT , ' ' : 8 , 'PROCEDURE TOO LARGE.' ) ; if ERRCDE = 255 then WRITELN ( OUTPUT , ' ' : 8 , 'PROCEDURE TOO LARGE.' ) ; if ERRCDE = 256 then WRITELN ( OUTPUT , ' ' : 8 , 'TOO MANY PROC/FUNC CALLS IN THIS PROC.' ) ; if ERRCDE = 259 then WRITELN ( OUTPUT , ' ' : 8 , 'EXPRESSION TOO COMPLICATED.' ) ; if ERRCDE = 263 then WRITELN ( OUTPUT , ' ' : 8 , 'TOO MANY CONTROL JUMPS IN THIS PROC.' ) ; if ERRCDE = 300 then WRITELN ( OUTPUT , ' ' : 8 , 'IMPLIED DIVISION BY ZERO.' ) ; if ERRCDE = 301 then WRITELN ( OUTPUT , ' ' : 8 , 'RANGE ERROR IN STRUCTURED CONST.' ) ; if ERRCDE = 302 then WRITELN ( OUTPUT , ' ' : 8 , 'IMPLIED SUBSCRIPTRANGE ERROR.' ) ; if ERRCDE = 303 then WRITELN ( OUTPUT , ' ' : 8 , 'ILLEGAL CONSTANT SET ASSMT.' ) ; if ERRCDE = 504 then WRITELN ( OUTPUT , ' ' : 8 , 'ARRAY COMPONENT TOO LARGE (>32K).' ) ; if ERRCDE = 618 then WRITELN ( OUTPUT , ' ' : 8 , 'UNEXPECTED EOL IN P-CODE INPUT' ) ; end (* ERROR_SYMB *) ; procedure ERROR ( ERRCDE : INTEGER ) ; begin (* ERROR *) ERROR_SYMB ( ERRCDE , ' ' ) ; end (* ERROR *) ; procedure CHECKFREEREGS ; (***********************************************************) (* TO BE INVOKED WHEN COMPILATION STACK IS EMPTY, *) (* CHECKS THAT ALL REGS HAVE BEEN MARKED AS AVAILABLE *) (***********************************************************) var LIST : array [ 1 .. 12 ] of record RGNO : RGRNG ; KIND : CHAR end ; LP : 0 .. 12 ; I : RGRNG ; begin (* CHECKFREEREGS *) if TOP <> 1 then begin WRITELN ( OUTPUT , '****' : 7 , ' WARNING: STACK HEIGHT =' , TOP : 3 ) ; TOP := 1 end (* then *) ; I := 1 ; LP := 0 ; repeat I := I + 1 ; if not AVAIL [ I ] then if I <> CALLSTACKADR then begin LP := LP + 1 ; LIST [ LP ] . RGNO := I ; LIST [ LP ] . KIND := 'G' ; AVAIL [ I ] := TRUE ; end (* then *) ; until I >= RGCNT ; I := 0 ; repeat I := I + 2 ; if not AVAILFP [ I ] then begin LP := LP + 1 ; LIST [ LP ] . RGNO := I ; LIST [ LP ] . KIND := 'F' ; AVAILFP [ I ] := TRUE ; end (* then *) ; until I >= FPCNT ; if LP > 0 then begin WRITELN ( OUTPUT , '****' : 7 , ' WARNING: REGISTERS NOT FREED ' ) ; for I := 1 to LP do WRITE ( OUTPUT , LIST [ I ] . KIND : 8 , 'PR' , LIST [ I ] . RGNO : 3 ) ; WRITELN ( OUTPUT ) ; WRITELN ( OUTPUT , '(NEAR LINE' : 34 , LASTLN : 6 , 'OF PROCEDURE:' : 15 , PIAKT -> . CURPNAME , ')' ) ; end (* then *) ; end (* CHECKFREEREGS *) ; function TO_HINT ( X : INTEGER ) : INTEGER ; begin (* TO_HINT *) X := X & 0xffff ; if X > 0x8000 then X := X - 0x10000 ; TO_HINT := X ; end (* TO_HINT *) ; procedure ENTERLOOKUP ; const STEP = 17 ; // MUST BE COPRIME TO HTSIZE var H : INTEGER ; // was 0 .. HTSIZE, changed due to rangeerr begin (* ENTERLOOKUP *) H := ( ORD ( P_OPCODE [ 1 ] ) * 64 + // hashcode part 1 ORD ( P_OPCODE [ 2 ] ) * 4096 + // hashcode part 2 ORD ( P_OPCODE [ 3 ] ) ) MOD HTSIZE ; // hashcode part 3 repeat with HTBL [ H ] do if NAME <> P_OPCODE then if NAME <> EMPTY then begin H := H + STEP ; if H >= HTSIZE then H := H - HTSIZE ; continue ; (************************) (* NO CHECK FOR CYCLES! *) (************************) end (* then *) else if INIT then begin (******************) (* ENTER THE ITEM *) (******************) NAME := P_OPCODE ; if OP_SP then OPCDE := OPCODE else SPCDE := CSP end (* then *) else if OP_SP then OPCODE := UNDEF_OP else CSP := UNDEF_CSP else if OP_SP then OPCODE := OPCDE else CSP := SPCDE ; break ; until FALSE ; end (* ENTERLOOKUP *) ; function FLDW ( NUM : INTEGER ) : INTEGER ; var FW : INTEGER ; begin (* FLDW *) FW := 0 ; if NUM < 0 then begin FW := 1 ; NUM := ABS ( NUM ) ; end (* then *) ; repeat NUM := NUM DIV 10 ; FW := FW + 1 ; until NUM = 0 ; FLDW := FW end (* FLDW *) ; procedure DUMPAVAIL ; var I : INTEGER ; begin (* DUMPAVAIL *) WRITE ( TRACEF , 'Available Regs: ' ) ; for I := 1 to 9 do if AVAIL [ I ] then WRITE ( TRACEF , I : 3 ) ; WRITELN ( TRACEF ) ; end (* DUMPAVAIL *) ; procedure DUMPSTKELEM ( TAG : CHAR ( 8 ) ; STK : DATUM ) ; const TYPNAME : array [ BOOL .. VARC ] of array [ 1 .. 4 ] of CHAR = ( 'BOOL' , 'CHRC' , 'ADR ' , 'HINT' , 'INT ' , 'PSET' , 'REEL' , 'PROC' , 'CARR' , 'VARC' ) ; begin (* DUMPSTKELEM *) with STK do begin WRITELN ( TRACEF , TAG , ' VRBL=' , VRBL : 1 , ' STKADR=' , STKADR : 5 , ' PLEN=' , PLEN : 3 , ' SCNSTNO=' , SCNSTNO : 3 ) ; WRITE ( TRACEF , ' ' : 8 , ' FPA=' , FPA . LVL : 3 , FPA . DSPLMT : 6 , ' VPA=' , VPA ) ; if VRBL then begin WRITE ( TRACEF , ' ' ) ; if VPA = RGS then WRITE ( TRACEF , ' VPA-REG =' , RGADR : 3 ) else WRITE ( TRACEF , ' VPA-MEM =' , MEMADR . LVL : 3 , MEMADR . DSPLMT : 6 ) ; if DRCT then WRITE ( TRACEF , ' DIRECT' ) else WRITE ( TRACEF , ' INDIR.' ) ; end (* then *) ; if DTYPE <= VARC then WRITE ( TRACEF , '(' : 2 , TYPNAME [ DTYPE ] , ')' ) else WRITE ( TRACEF , '(ETC.)' : 8 ) ; WRITE ( TRACEF , ' ' , PROCNAME ) ; WRITELN ( TRACEF ) ; end (* with *) ; end (* DUMPSTKELEM *) ; procedure DUMPSTK ( STP1 , STP2 : STKPTR ) ; var I : STKPTR ; begin (* DUMPSTK *) DUMPAVAIL ; for I := STP1 to STP2 do begin WRITELN ( TRACEF , ' +++ DEPTH=' , I : 2 ) ; DUMPSTKELEM ( 'StkElem ' , STK [ I ] ) ; end (* for *) end (* DUMPSTK *) ; procedure HEXHW ( HW : HINTEGER ; var HEX : HEX4 ) ; (*************************************************) (* CONVERTS HALFWORD TO 4 HEXADECIMAL CHARACTERS *) (*************************************************) var C : INTEGER ; N : 1 .. 4 ; begin (* HEXHW *) C := 65536 + HW ; (************************) (* ELIMINATES HW<0 CASE *) (************************) for N := 4 DOWNTO 1 do begin HEX [ N ] := HEXCHARS [ C MOD 16 ] ; C := C DIV 16 end (* for *) ; end (* HEXHW *) ; function READNXTINST ( var PCODEF : TEXT ; MODUS : INTEGER ) : BOOLEAN ; //***************************************************** // TO READ AND DECODE NEXT P_INSTRUCTION // ------------------------------------- // 03.2021: allow comments which are added to p-code // instructions by the compiler following a semicolon // (variable names) //***************************************************** const SL16 = 65536 ; var I , J , K : INTEGER ; CH1 : CHAR ; HEX_PCOUNTER : HEX4 ; LEN : INTEGER ; BUFFER : CHAR80 ; OUTPOS : INTEGER ; BUF20 : CHAR80 ; LSTART : INTEGER ; X1 : INTEGER ; DUMMYNAME : array [ 1 .. IDLNGTH ] of CHAR ; DUMMYINT : INTEGER ; DUMMYBOOL : BOOLEAN ; DUMMYLABEL : PLABEL ; P_IS_CHAR : BOOLEAN ; Q_IS_CHAR : BOOLEAN ; OPERANDS : STRING ( 80 ) ; procedure READLBL ( var LBL : PLABEL ) ; (*******************************************************) (* SKIPS LEADING BLANKS AND READS THE NEXT *) (* CHARACTER SEQUENCE AS A LABEL *) (* --------------------------------------------------- *) (*******************************************************) var I : INTEGER ; CH : CHAR ; begin (* READLBL *) with LBL do begin CADDR := 0 ; NAM := ' ' ; LEN := 0 ; if EOL ( PCODEF ) then ERROR ( 618 ) ; repeat READ ( PCODEF , CH ) ; LEN := LEN + 1 ; NAM [ LEN ] := CH ; until ( PCODEF -> = ' ' ) or ( LEN = 8 ) ; if NAM [ 1 ] in [ '0' .. '9' ] then begin I := 1 ; CH := NAM [ 1 ] ; repeat CADDR := CADDR * 10 + ORD ( CH ) - ORD ( '0' ) ; I := I + 1 ; CH := NAM [ I ] ; until not ( CH in [ '0' .. '9' ] ) ; end (* then *) ; end (* with *) ; end (* READLBL *) ; function HEXVALUE ( C : CHAR ) : INTEGER ; begin (* HEXVALUE *) if C in [ '0' .. '9' ] then HEXVALUE := ORD ( C ) - ORD ( '0' ) else if C in [ 'A' .. 'F' ] then HEXVALUE := ORD ( C ) - ORD ( 'A' ) + 10 else if C in [ 'a' .. 'f' ] then HEXVALUE := ORD ( C ) - ORD ( 'a' ) + 10 end (* HEXVALUE *) ; procedure READSET ; var CH1 : CHAR ; CH2 : CHAR ; I : INTEGER ; X : set of CHAR ; Z : INTEGER ; begin (* READSET *) READ ( PCODEF , CH , CH ) ; (****************************) (* typ = e - d.h. empty set *) (****************************) if CH = 'E' then begin PSLNGTH := 0 ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , ' E()' ) ; LIST002_NEWLINE end (* then *) ; if FALSE then WRITELN ( TRACEF , ' E()' ) ; return end (* then *) ; (******************************************) (* typ = x - d.h. hexadezimaler bitstring *) (******************************************) if CH = 'X' then begin READ ( PCODEF , PSLNGTH ) ; Z := 30 ; READ ( PCODEF , CH ) ; if ASM then WRITE ( LIST002 , ' S,X' , PSLNGTH : 1 , '''' ) ; if FALSE then WRITE ( TRACEF , ' S,X' , PSLNGTH : 1 , '''' ) ; I := 0 ; while TRUE do begin READ ( PCODEF , CH1 ) ; if CH1 = '''' then begin if PCODEF -> <> ',' then begin if FALSE then WRITELN ( TRACEF , '''' ) ; break ; end (* then *) ; READLN ( PCODEF ) ; repeat READ ( PCODEF , CH ) ; until CH = '''' ; continue ; end (* then *) ; READ ( PCODEF , CH2 ) ; if FALSE then WRITE ( TRACEF , CH1 , CH2 ) ; I := I + 1 ; PSVAL . C [ I ] := CHR ( HEXVALUE ( CH1 ) * 16 + HEXVALUE ( CH2 ) ) ; if Z >= 70 then begin if ASM then begin WRITE ( LIST002 , ''',' ) ; LIST002_NEWLINE ; WRITE ( LIST002 , '''' : 27 ) ; end (* then *) ; Z := 27 ; end (* then *) ; if ASM then WRITE ( LIST002 , CH1 , CH2 ) ; if FALSE then WRITE ( TRACEF , CH1 , CH2 ) ; Z := Z + 2 ; end (* while *) ; PSLNGTH := I ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , '''' ) ; LIST002_NEWLINE end (* then *) ; return end (* then *) ; (******************************************) (* typ = c - d.h. char-string *) (******************************************) if CH = 'C' then begin READ ( PCODEF , PSLNGTH ) ; Z := 30 ; READ ( PCODEF , CH ) ; if ASM then WRITE ( LIST002 , ' S,C' , PSLNGTH : 1 , '''' ) ; if FALSE then WRITE ( TRACEF , ' S,C' , PSLNGTH : 1 , '''' ) ; X := [ ] ; while TRUE do begin READ ( PCODEF , CH ) ; if CH = '''' then begin CH := PCODEF -> ; if CH = '''' then READ ( PCODEF , CH ) else if CH = ',' then begin READLN ( PCODEF ) ; repeat READ ( PCODEF , CH ) ; until CH = '''' ; continue ; end (* then *) else break ; end (* then *) ; X := X + [ CH ] ; if Z >= 70 then begin if ASM then begin WRITE ( LIST002 , ''',' ) ; LIST002_NEWLINE ; WRITE ( LIST002 , '''' : 27 ) ; end (* then *) ; Z := 27 ; end (* then *) ; if ASM then begin WRITE ( LIST002 , CH ) ; Z := Z + 1 ; if CH = '''' then begin WRITE ( LIST002 , CH ) ; Z := Z + 1 ; end (* then *) end (* then *) ; if FALSE then begin WRITE ( TRACEF , CH ) ; if CH = '''' then WRITE ( TRACEF , CH ) ; end (* then *) ; end (* while *) ; MEMCPY ( ADDR ( PSVAL ) , ADDR ( X ) , PSLNGTH ) ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , '''' ) ; LIST002_NEWLINE end (* then *) ; return end (* then *) ; end (* READSET *) ; procedure SKIPBLANKS ; begin (* SKIPBLANKS *) GET ( PCODEF ) ; if EOL ( PCODEF ) then ERROR ( 618 ) ; end (* SKIPBLANKS *) ; procedure READLOADINSTRUCTIONS ; var TYPETAG : CHAR ; INEU : INTEGER ; X2 : INTEGER ; LLIMIT : INTEGER ; begin (* READLOADINSTRUCTIONS *) SKIPBLANKS ; (*******************************************************) (* TYPE-CODE, CONSTANT OPERANDS *) (* with type-code = m: *) (* length (optional) and string constant *) (* the string constant may be split over multiple *) (* lines and may be prefixed by B or X for binary *) (* or hex content *) (*******************************************************) if ( OPCODE = PDFC ) and ( PCODEF -> = '0' ) then begin OPNDTYPE := NON ; READ ( PCODEF , CH1 ) ; READLN ( PCODEF , CH , IVAL ) ; SLNGTH := IVAL ; if ASM then begin WRITE ( LIST002 , CH1 : 3 , ',' , IVAL : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* then *) else begin OPNDTYPE := TYPCDE [ PCODEF -> ] ; READ ( PCODEF , CH1 ) ; case OPNDTYPE of HINT , BOOL , INT : begin READLN ( PCODEF , CH , IVAL ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 , ',' , IVAL : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; CHRC : begin READLN ( PCODEF , CH , CH , CH ) ; IVAL := ORD ( CH ) ; if ASM then begin WRITE ( LIST002 , 'C,''' : 5 , CH , '''' ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; REEL : begin READLN ( PCODEF , CH , RVAL ) ; if ASM then begin WRITE ( LIST002 , 'R,' : 4 , RVAL : 20 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; ADR : begin READLN ( PCODEF ) ; IVAL := - 1 ; if ASM then begin WRITE ( LIST002 , 'NIL' : 4 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PSET : begin READSET ; end (* tag/ca *) ; PROC : begin READ ( PCODEF , CH ) ; READLBL ( LBL2 ) ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , 'P,' : 4 , LBL2 . NAM : LBL2 . LEN ) ; LIST002_NEWLINE ; end (* then *) ; end (* tag/ca *) ; CARR : begin LEN := - 1 ; READ ( PCODEF , CH ) ; /************************************/ /* read optional length information */ /************************************/ if not ( PCODEF -> in [ '''' , 'B' , 'X' ] ) then begin READ ( PCODEF , LEN ) ; READ ( PCODEF , CH ) ; end (* then *) ; /**************************/ /* read optional type tag */ /**************************/ READ ( PCODEF , CH ) ; TYPETAG := ' ' ; if CH in [ 'X' , 'B' ] then begin TYPETAG := CH ; READ ( PCODEF , CH ) ; end (* then *) ; SVAL := ' ' ; J := 0 ; CH := '''' ; repeat /*********************************/ /* read rest of line into buffer */ /*********************************/ READLN ( PCODEF , BUFFER ) ; I := 80 ; while BUFFER [ I ] = ' ' do I := I - 1 ; CH := BUFFER [ I ] ; /***********************************/ /* if comma after string constant, */ /* another part follows */ /***********************************/ if CH = ',' then begin I := I - 2 ; SKIPBLANKS ; READ ( PCODEF , CH ) ; CH := ',' ; end (* then *) else I := I - 1 ; /************************************/ /* now move part of string constant */ /* to result buffer (sval), */ /* depending on type tag */ /************************************/ K := 1 ; while K <= I do begin J := J + 1 ; case TYPETAG of ' ' : begin SVAL [ J ] := BUFFER [ K ] ; if SVAL [ J ] = '''' then K := K + 2 else K := K + 1 ; end (* tag/ca *) ; 'X' : begin INEU := 0 ; for X2 := K to K + 1 do begin INEU := INEU * 16 ; if BUFFER [ X2 ] in [ '1' .. '9' ] then INEU := INEU + ORD ( BUFFER [ X2 ] ) - ORD ( '0' ) else if BUFFER [ X2 ] in [ 'A' .. 'F' ] then INEU := INEU + ORD ( BUFFER [ X2 ] ) - ORD ( 'A' ) + 10 else if BUFFER [ X2 ] in [ 'a' .. 'f' ] then INEU := INEU + ORD ( BUFFER [ X2 ] ) - ORD ( 'a' ) + 10 ; end (* for *) ; SVAL [ J ] := CHR ( INEU ) ; K := K + 2 ; end (* tag/ca *) ; 'B' : begin INEU := 0 ; for X2 := K to K + 7 do begin INEU := INEU * 2 ; if BUFFER [ X2 ] = '1' then INEU := INEU + 1 ; end (* for *) ; SVAL [ J ] := CHR ( INEU ) ; K := K + 8 ; end (* tag/ca *) ; end (* case *) ; end (* while *) ; until CH = '''' ; if LEN < 0 then SLNGTH := J else SLNGTH := LEN ; /************************************/ /* show what has been read */ /* on list002 ... */ /************************************/ if ASM then begin WRITE ( LIST002 , ' M,' , SLNGTH : 1 , ',' ) ; case TYPETAG of 'X' : LLIMIT := SLNGTH * 2 ; 'B' : LLIMIT := SLNGTH * 8 ; otherwise LLIMIT := SLNGTH ; end (* case *) ; if LLIMIT < 40 then begin if TYPETAG <> ' ' then WRITE ( LIST002 , TYPETAG ) ; WRITE ( LIST002 , '''' ) end (* then *) else begin LIST002_NEWLINE ; WRITE ( LIST002 , ' ' , ' ' ) ; if TYPETAG <> ' ' then WRITE ( LIST002 , TYPETAG ) ; WRITE ( LIST002 , '''' ) end (* else *) ; OUTPOS := 0 ; for I := 1 to SLNGTH do begin if OUTPOS > 60 then begin WRITE ( LIST002 , ''',' ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' ' , ' ''' ) ; OUTPOS := 0 ; end (* then *) ; case TYPETAG of 'X' : begin CH := SVAL [ I ] ; WRITEHEXBYTE ( LIST002 , ORD ( CH ) ) ; OUTPOS := OUTPOS + 2 ; end (* tag/ca *) ; 'B' : begin CH := SVAL [ I ] ; WRITEBINBYTE ( LIST002 , ORD ( CH ) ) ; OUTPOS := OUTPOS + 8 ; end (* tag/ca *) ; otherwise begin CH := SVAL [ I ] ; WRITE ( LIST002 , CH ) ; OUTPOS := OUTPOS + 1 ; if CH = '''' then begin WRITE ( LIST002 , CH ) ; OUTPOS := OUTPOS + 1 end (* then *) ; end (* otherw *) end (* case *) ; end (* for *) ; WRITE ( LIST002 , '''' ) ; LIST002_NEWLINE ; end (* then *) ; end (* tag/ca *) ; end (* case *) end (* else *) end (* READLOADINSTRUCTIONS *) ; procedure LIST_PROCEDURE_ENTRY ; begin (* LIST_PROCEDURE_ENTRY *) LIST002_PRINTLOC ( LINECNT ) ; HEXHW ( 2 * PCOUNTER , HEX_PCOUNTER ) ; WRITE ( LIST002 , ' ' , HEX_PCOUNTER : 9 , ': ' ) ; WRITE ( LIST002 , LBL1 . NAM ) ; WRITE ( LIST002 , P_OPCODE : 4 ) ; WRITE ( LIST002 , CH1 : 3 , ',' ) ; WRITE ( LIST002 , P : 1 , ',' ) ; WRITE ( LIST002 , PIAKT -> . SEGSZE . NAM : 4 ) ; WRITE ( LIST002 , PIAKT -> . CURPNAME : IDLNGTH + 2 , ',' ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' ' , HEX_PCOUNTER : 9 , ': ' ) ; WRITE ( LIST002 , ' ' : 14 ) ; WRITE ( LIST002 , PIAKT -> . SAVERGS : 1 , ',' ) ; WRITE ( LIST002 , PIAKT -> . ASM : 1 , ',' ) ; WRITE ( LIST002 , PIAKT -> . GET_STAT : 1 , ',' ) ; WRITE ( LIST002 , PIAKT -> . ASMVERB : 1 , ',' ) ; WRITE ( LIST002 , PIAKT -> . DEBUG_LEV : 1 , ',' ) ; WRITE ( LIST002 , PIAKT -> . CURPNO : 1 , ',' ) ; if PIAKT -> . STATNAME <> ' ' then WRITE ( LIST002 , PIAKT -> . STATNAME ) ; WRITE ( LIST002 , ',' ) ; if PIAKT -> . SOURCENAME <> ' ' then WRITE ( LIST002 , PIAKT -> . SOURCENAME ) ; LIST002_NEWLINE ; end (* LIST_PROCEDURE_ENTRY *) ; procedure READ_XBG ; begin (* READ_XBG *) READLN ( PCODEF , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; if MODUS = 1 then begin if XXIANKER = NIL then begin NEW ( XXIANKER ) ; XXIAKT := XXIANKER end (* then *) else begin NEW ( XXIAKT -> . NEXT ) ; XXIAKT := XXIAKT -> . NEXT end (* else *) ; XXIAKT -> . NEXT := NIL ; XXIAKT -> . XBG_NO := Q ; XXIAKT -> . VALID := TRUE ; end (* then *) else begin XXILAUF := XXIANKER ; while XXILAUF <> NIL do begin if XXILAUF -> . XBG_NO = Q then break ; XXILAUF := XXILAUF -> . NEXT ; end (* while *) ; if XXILAUF <> NIL then if not XXILAUF -> . VALID then GS . XBG_XEN_SUPPRESSED := Q ; end (* else *) end (* READ_XBG *) ; procedure READ_XEN ; begin (* READ_XEN *) READLN ( PCODEF , Q , CH , P ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , Q : 1 , ',' , P : 1 ) ; LIST002_NEWLINE end (* then *) ; if MODUS = 1 then begin XXILAUF := XXIANKER ; while XXILAUF <> NIL do begin if XXILAUF -> . XBG_NO = Q then break ; XXILAUF := XXILAUF -> . NEXT ; end (* while *) ; if XXILAUF <> NIL then XXILAUF -> . VALID := ( P <> 0 ) ; end (* then *) else begin XXILAUF := XXIANKER ; while XXILAUF <> NIL do begin if XXILAUF -> . XBG_NO = Q then break ; XXILAUF := XXILAUF -> . NEXT ; end (* while *) ; if XXILAUF <> NIL then GS . XBG_XEN_SUPPRESSED := - 1 ; end (* else *) end (* READ_XEN *) ; procedure READ_DEF ; begin (* READ_DEF *) if MODUS = 1 then begin SKIPBLANKS ; case GS . MOD1DEFSTEP of 0 : begin READLN ( PCODEF , CH , CH , Q ) ; PIAKT -> . DATA_SIZE := Q ; GS . MOD1DEFSTEP := 1 ; end (* tag/ca *) ; 1 : begin READLN ( PCODEF , CH , CH , Q ) ; PIAKT -> . CODE_SIZE := Q ; PIAKT -> . LARGE_PROC := ( PIAKT -> . CODE_SIZE > SHRT_PROC ) or DEBUG ; GS . MOD1DEFSTEP := 2 ; end (* tag/ca *) ; 2 : begin READLN ( PCODEF , CH , CH , Q ) ; PIAKT -> . CALL_HIGHER := ( Q <> 0 ) ; GS . MOD1DEFSTEP := - 1 ; end (* tag/ca *) ; otherwise READLN ( PCODEF ) end (* case *) ; return end (* then *) ; (*****************************************) (* Type-Code and Integer or Char Operand *) (*****************************************) SKIPBLANKS ; if PCODEF -> = 'C' then begin READLN ( PCODEF , CH , CH , CH , CH1 , CH ) ; if ASM then begin WRITE ( LIST002 , ' C,''' , CH1 : 1 , '''' ) ; LIST002_NEWLINE end (* then *) ; Q := ORD ( CH1 ) ; OPNDTYPE := TYPCDE [ 'C' ] ; end (* then *) else if PCODEF -> = 'I' then begin READLN ( PCODEF , CH , CH , Q ) ; if ASM then begin WRITE ( LIST002 , ' I,' , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; OPNDTYPE := TYPCDE [ 'I' ] ; end (* then *) else if PCODEF -> = 'B' then begin READLN ( PCODEF , CH , CH , Q ) ; if ASM then begin WRITE ( LIST002 , ' I,' , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; OPNDTYPE := TYPCDE [ 'I' ] ; end (* then *) else begin READLN ( PCODEF , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; OPNDTYPE := TYPCDE [ 'I' ] ; end (* else *) end (* READ_DEF *) ; procedure READ_ENT ; var X : INTEGER ; OPTV : CHAR ( 8 ) ; begin (* READ_ENT *) (*************************************************************) (* TYPE-CODE,LEXIC-LEVEL,LABEL,THREE FLAGS,INTEGER OPERANDS *) (*************************************************************) if MODUS = 1 then begin if PIANKER = NIL then begin NEW ( PIANKER ) ; PIAKT := PIANKER end (* then *) else begin NEW ( PIAKT -> . NEXT ) ; PIAKT := PIAKT -> . NEXT end (* else *) ; PIAKT -> . NEXT := NIL ; SKIPBLANKS ; PIAKT -> . OPNDTYPE := TYPCDE [ PCODEF -> ] ; READ ( PCODEF , CH1 , CH , P , CH ) ; READLBL ( PIAKT -> . SEGSZE ) ; if PCODEF -> = ' ' then SKIPBLANKS ; READ ( PCODEF , PIAKT -> . CURPNAME , CH ) ; //**************************************** // change input format here - 10.05.2021 // support old and new format //**************************************** READ ( PCODEF , PIAKT -> . SAVERGS , CH ) ; if CH = ',' then begin READ ( PCODEF , PIAKT -> . ASM , CH ) ; READ ( PCODEF , PIAKT -> . GET_STAT , CH ) ; READ ( PCODEF , PIAKT -> . ASMVERB , CH ) ; PIAKT -> . INIT_AUTO := FALSE ; end (* then *) else begin OPTV := ' ' ; OPTV [ 2 ] := CH ; X := 2 ; repeat X := X + 1 ; READ ( PCODEF , OPTV [ X ] ) until OPTV [ X ] = ',' ; PIAKT -> . ASM := OPTV [ 2 ] = 'T' ; PIAKT -> . GET_STAT := OPTV [ 3 ] = 'T' ; PIAKT -> . ASMVERB := OPTV [ 4 ] = 'T' ; PIAKT -> . INIT_AUTO := OPTV [ 5 ] = 'T' ; end (* else *) ; READ ( PCODEF , PIAKT -> . DEBUG_LEV , CH ) ; READ ( PCODEF , PIAKT -> . CURPNO , CH ) ; PIAKT -> . STATNAME := ' ' ; PIAKT -> . SOURCENAME := ' ' ; if PCODEF -> <> ',' then READ ( PCODEF , PIAKT -> . STATNAME , CH ) else READ ( PCODEF , CH ) ; READ ( PCODEF , PIAKT -> . SOURCENAME ) ; if PCODEF -> = ',' then READ ( PCODEF , CH ) ; if PCODEF -> <> ' ' then READ ( PCODEF , PIAKT -> . SCRATCHPOS ) ; READLN ( PCODEF ) ; DEBUG := PIAKT -> . DEBUG_LEV >= 2 ; PIAKT -> . FLOW_TRACE := PIAKT -> . DEBUG_LEV >= 3 ; return ; end (* then *) else begin SKIPBLANKS ; READ ( PCODEF , CH1 , CH , P , CH ) ; READLBL ( DUMMYLABEL ) ; if PCODEF -> = ' ' then SKIPBLANKS ; //**************************************** // change input format here - 10.05.2021 // support old and new format //**************************************** READ ( PCODEF , DUMMYNAME , CH , DUMMYBOOL , CH ) ; if CH = ',' then READ ( PCODEF , DUMMYBOOL , CH , DUMMYBOOL , CH , DUMMYBOOL , CH ) else repeat READ ( PCODEF , CH ) until CH = ',' ; READ ( PCODEF , DUMMYINT , CH , MATCH_CURPNO , CH ) ; READLN ( PCODEF ) ; PIAKT := PIANKER ; while PIAKT <> NIL do begin if PIAKT -> . CURPNO <> MATCH_CURPNO then PIAKT := PIAKT -> . NEXT else break ; end (* while *) ; OPNDTYPE := PIAKT -> . OPNDTYPE ; ASM := PIAKT -> . ASM ; FLOW_TRACE := PIAKT -> . FLOW_TRACE ; PCOUNTER := 0 ; //************************************************************ // init tables of offsets and statement numbers //************************************************************ TOS_COUNT := 1 ; TOS [ 1 ] . STMT := LINECNT ; TOS [ 1 ] . OFFS := PCOUNTER ; if FIRST_LIST002 then begin REWRITE ( LIST002 ) ; FIRST_LIST002 := FALSE end (* then *) ; DUMMYINT := LIST002_HEADLINE ( 'S' , LBL1 . NAM , PIAKT -> . CURPNAME , CH1 ) ; if ASM then LIST_PROCEDURE_ENTRY end (* else *) end (* READ_ENT *) ; begin (* READNXTINST *) P := 0 ; Q := 0 ; LBL1 . LEN := 0 ; if PCODEF -> <> ' ' then begin READLBL ( LBL1 ) ; end (* then *) ; GET ( PCODEF ) ; if PCODEF -> = ' ' then SKIPBLANKS ; //************************************************************ // P-Opcode einlesen //************************************************************ READ ( PCODEF , P_OPCODE ) ; //************************************************************ // when reading the first time, only certain P-Opcodes are // of interest //************************************************************ if MODUS = 1 then begin if ( P_OPCODE <> 'ENT' ) and ( P_OPCODE <> 'RET' ) and ( P_OPCODE <> 'DEF' ) and ( P_OPCODE <> 'STP' ) and ( P_OPCODE <> 'XBG' ) and ( P_OPCODE <> 'XEN' ) then begin READLN ( PCODEF ) ; READNXTINST := EOF ( PCODEF ) ; return ; end (* then *) ; end (* then *) //************************************************************ // when reading the second time, there may be // XBG/XEN suppressing in effect ... if so, only // XEN P-Codes need to be interpreted, because only XEN // may terminate the XBG/XEN suppressing //************************************************************ else begin if GS . XBG_XEN_SUPPRESSED > 0 then if P_OPCODE <> 'XEN' then begin READLN ( PCODEF ) ; READNXTINST := EOF ( PCODEF ) ; return ; end (* then *) ; if ASM and ( P_OPCODE <> 'LOC' ) and ( P_OPCODE <> 'ENT' ) and ( P_OPCODE <> 'CST' ) then begin if P_OPCODE = 'DFC' then HEXHW ( LBL1 . CADDR , HEX_PCOUNTER ) else HEXHW ( 2 * PCOUNTER , HEX_PCOUNTER ) ; WRITE ( LIST002 , ' ' , HEX_PCOUNTER : 9 , ': ' , LBL1 . NAM : LBL1 . LEN , ' ' : 6 - LBL1 . LEN , P_OPCODE : 6 ) ; end (* then *) end (* else *) ; //************************************************************ // achtung, nur uebergangsweise, bis V-Befehle // korrekt implementiert sind //************************************************************ ENTERLOOKUP ; //************************************************************ // achtung, nur uebergangsweise, bis V-Befehle // korrekt implementiert sind //************************************************************ if OPCODE = PENT then begin if TOP <> 1 then ERROR ( 701 ) ; if FALSE then begin WRITELN ( TRACEF ) ; WRITELN ( TRACEF ) ; WRITELN ( TRACEF , 'Neuer Entry ' , LBL1 . NAM ) ; WRITELN ( TRACEF , 'TOP = ' , TOP ) ; end (* then *) ; TOP := 1 ; end (* then *) ; //************************************************************ // achtung, nur uebergangsweise, bis V-Befehle // korrekt implementiert sind // achtung, nur uebergangsweise, bis V-Befehle // korrekt implementiert sind //************************************************************ case OPCODE of //************************************************************ // pcodes with no operands //************************************************************ PADI , PADR , PSBI , PSBR , PFLT , PFLO , PNGI , PNGR , PSQI , PSQR , PABI , PABR , PMOD , PODD , PMPI , PMPR , PDVI , PDVR , PUNI , PINT , PDIF , PINN , PCRD , PLAB , PSAV , PRST , PCHR , PORD , PXPO , PPOP , PXLB , PADA , PSBA , PMCP : begin READLN ( PCODEF ) ; if ASM then LIST002_NEWLINE ; end (* tag/ca *) ; PEND : begin READLN ( PCODEF ) ; if ASM then LIST002_NEWLINE ; ASM := FALSE ; end (* tag/ca *) ; //************************************************************ // XBG creates a linked list of its parameters and // the indicators on the corresponding XEN instructions // during pass 1 // When in pass 2, XBG suppresses the reading of // P-instructions until the corresponding XEN is found // (if the indicator - boolean VALID - is off) //************************************************************ PXBG : READ_XBG ; PXEN : READ_XEN ; PSTP : begin if MODUS = 1 then begin READLN ( PCODEF ) ; READNXTINST := EOF ( PCODEF ) ; return end (* then *) ; (***************) (* NO OPERANDS *) (***************) READLN ( PCODEF ) ; if ASM then LIST002_NEWLINE ; end (* tag/ca *) ; PDEF : READ_DEF ; PCTI , PIXA , PASE , PMOV , PMV1 , PMFI , PMZE , PMSE , PDBG : begin (*******************) (* INTEGER OPERAND *) (*******************) READLN ( PCODEF , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PLOC : begin (*******************) (* INTEGER OPERAND *) (*******************) READLN ( PCODEF , Q ) ; if ASM then LIST002_PRINTLOC ( Q ) ; LINECNT := Q end (* tag/ca *) ; PAND , PIOR , PXOR , PNOT : begin (******************************) (* TYPE-CODE; if blank then b *) (******************************) GET ( PCODEF ) ; CH1 := PCODEF -> ; if CH1 = ' ' then CH1 := 'B' ; OPNDTYPE := TYPCDE [ CH1 ] ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PINC , PDEC , PIND : begin //***************************************** // TYPE-CODE AND INTEGER OPERANDS // 03.2021: operands contains comments //***************************************** SKIPBLANKS ; READLN ( PCODEF , OPERANDS ) ; READSTR ( OPERANDS , CH1 , CH , Q ) ; OPNDTYPE := TYPCDE [ CH1 ] ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , OPERANDS ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PNEW , PLDA , PSMV , PSLD , PSCL , PMST , PASR : begin //***************************************** // TWO INTEGER OPERANDS // 03.2021: operands contains comments //***************************************** SKIPBLANKS ; READLN ( PCODEF , OPERANDS ) ; READSTR ( OPERANDS , P , CH , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , OPERANDS ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PLOD , PSTR : begin //************************************************************ // TYPE-CODE AND TWO INTEGER OPERANDS // TYPE-CODE may be zero with STR // then no store is required, only pop of stack element // 03.2021: operands contains comments //************************************************************ SKIPBLANKS ; READLN ( PCODEF , OPERANDS ) ; READSTR ( OPERANDS , CH1 , CH , P , CH , Q ) ; if CH1 = '0' then OPNDTYPE := NON else OPNDTYPE := TYPCDE [ CH1 ] ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , OPERANDS ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PPAK : begin (**************************) (* THREE INTEGER OPERANDS *) (**************************) SKIPBLANKS ; READLN ( PCODEF , OPERANDS ) ; READSTR ( OPERANDS , IVAL , CH , P , CH , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , OPERANDS ) ; LIST002_NEWLINE ; end (* then *) ; end (* tag/ca *) ; PCHK : begin //********************************************************** // TYPE-CODE AND TWO INTEGER OPERANDS // change 28.08.2020: // to enable portable chk instructions for char subranges // the two integers may be specified as char constants // (single chars surrounded by apostrophs) //********************************************************** P_IS_CHAR := FALSE ; Q_IS_CHAR := FALSE ; SKIPBLANKS ; OPNDTYPE := TYPCDE [ PCODEF -> ] ; READ ( PCODEF , CH1 , CH ) ; if PCODEF -> = '''' then begin READ ( PCODEF , CH ) ; READ ( PCODEF , CH ) ; P := ORD ( CH ) ; P_IS_CHAR := TRUE ; READ ( PCODEF , CH ) ; end (* then *) else READ ( PCODEF , P ) ; READ ( PCODEF , CH ) ; if PCODEF -> = '''' then begin READ ( PCODEF , CH ) ; READ ( PCODEF , CH ) ; Q := ORD ( CH ) ; Q_IS_CHAR := TRUE ; READ ( PCODEF , CH ) ; end (* then *) else READ ( PCODEF , Q ) ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 , ',' ) ; if P_IS_CHAR then WRITE ( LIST002 , '''' , CHR ( P ) , '''' ) else WRITE ( LIST002 , P : 1 ) ; WRITE ( LIST002 , ',' ) ; if Q_IS_CHAR then WRITE ( LIST002 , '''' , CHR ( Q ) , '''' ) else WRITE ( LIST002 , Q : 1 ) ; LIST002_NEWLINE ; end (* then *) ; end (* tag/ca *) ; PEQU , PNEQ , PLES , PGRT , PLEQ , PGEQ , PSTO : begin //************************************************************ // type code and possibly length operands // 12.2020: // type M: two length parameters for left and right side // new type 1: left is char 1, right is char array, 1 length // new type 2: right is char 1, left is char array, 1 length // 01.2021: // type M,1,2: two length parameters for left and right side //************************************************************ SKIPBLANKS ; COMPTYPE := PCODEF -> ; case COMPTYPE of 'M' , '1' , '2' : begin OPNDTYPE := TYPCDE [ 'M' ] ; READ ( PCODEF , CH1 , CH , Q ) ; if PCODEF -> = ',' then READ ( PCODEF , CH , P ) else P := Q ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 , ',' , Q : 1 , ',' , P : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; otherwise begin OPNDTYPE := TYPCDE [ COMPTYPE ] ; READLN ( PCODEF , CH1 ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 ) ; LIST002_NEWLINE end (* then *) ; end (* otherw *) end (* case *) ; end (* tag/ca *) ; PRET : begin if MODUS = 1 then begin GS . MOD1DEFSTEP := 0 ; READLN ( PCODEF ) ; READNXTINST := EOF ( PCODEF ) ; return end (* then *) ; (*********************************************) (* TYPE-CODE AND POSSIBLY AN INTEGER OPERAND *) (*********************************************) SKIPBLANKS ; OPNDTYPE := TYPCDE [ PCODEF -> ] ; if OPNDTYPE = CARR then begin READLN ( PCODEF , CH1 , CH , Q ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 , ',' , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* then *) else begin READLN ( PCODEF , CH1 ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 ) ; LIST002_NEWLINE end (* then *) ; end (* else *) ; end (* tag/ca *) ; PFJP , PUJP , PCTS , PUXJ : begin (**********************) (* LABEL-NAME OPERAND *) (**********************) READLBL ( LBL2 ) ; READLN ( PCODEF ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , LBL2 . NAM : LBL2 . LEN ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PXJP : begin (**********************) (* LABEL-NAME OPERAND *) (**********************) SKIPBLANKS ; READLN ( PCODEF , BUF20 ) ; if ( BUF20 [ 1 ] in [ 'N' , 'O' ] ) and ( BUF20 [ 2 ] = ',' ) then begin XJPFLAG := BUF20 [ 1 ] ; LSTART := 2 end (* then *) else begin LSTART := 0 ; XJPFLAG := ' ' ; end (* else *) ; for X1 := 1 to 8 do begin LBL2 . NAM [ X1 ] := BUF20 [ X1 + LSTART ] ; end (* for *) ; LBL2 . LEN := 8 ; while LBL2 . NAM [ LBL2 . LEN ] = ' ' do begin LBL2 . LEN := LBL2 . LEN - 1 ; if LBL2 . LEN = 0 then break ; end (* while *) ; if ASM then begin if XJPFLAG = ' ' then begin WRITE ( LIST002 , ' ' , LBL2 . NAM : LBL2 . LEN ) ; LIST002_NEWLINE ; end (* then *) else begin WRITE ( LIST002 , ' ' , XJPFLAG , ',' , LBL2 . NAM : LBL2 . LEN ) ; LIST002_NEWLINE ; end (* else *) end (* then *) end (* tag/ca *) ; PCST : begin (************************************) (* PROCEDURE NAME & NUMBER OPERANDS *) (************************************) READLN ( PCODEF , CH1 , CST_CURPNAME , CST_CURPNO , CH , ASM , CH , CST_GET_STAT , CH , CST_ASMVERB ) ; if ASM then begin if FIRST_LIST002 then begin REWRITE ( LIST002 ) ; FIRST_LIST002 := FALSE end (* then *) ; DUMMYINT := LIST002_HEADLINE ( 'S' , LBL1 . NAM , CST_CURPNAME , '#' ) ; WRITE ( LIST002 , ' ' , ' 0000: ' , LBL1 . NAM : LBL1 . LEN , ' ' : 6 - LBL1 . LEN , P_OPCODE : 4 ) ; WRITE ( LIST002 , CST_CURPNAME : IDLNGTH + 2 , CST_CURPNO : 4 , ',' , ASM : 1 , ',' , CST_GET_STAT : 1 , ',' , CST_ASMVERB : 1 ) ; LIST002_NEWLINE ; end (* then *) ; end (* tag/ca *) ; PCUP : begin (*****************************************************) (* TYPE-CODE,LEXIC-LEVEL,LABEL-NAME,INTEGER OPERANDS *) (*****************************************************) SKIPBLANKS ; OPNDTYPE := TYPCDE [ PCODEF -> ] ; READ ( PCODEF , CH1 ) ; EXTLANG := ' ' ; if PCODEF -> <> ',' then begin EXTLANG := PCODEF -> ; READ ( PCODEF , CH ) ; end (* then *) ; READ ( PCODEF , CH , P , CH ) ; READLBL ( LBL2 ) ; if PCODEF -> = ' ' then SKIPBLANKS ; READLN ( PCODEF , CH , Q ) ; if ASM then begin WRITE ( LIST002 , CH1 : 3 ) ; if EXTLANG <> ' ' then WRITE ( LIST002 , EXTLANG ) ; WRITE ( LIST002 , ',' , P : 1 ) ; WRITE ( LIST002 , ',' , LBL2 . NAM : LBL2 . LEN ) ; WRITE ( LIST002 , ',' , Q : 1 ) ; LIST002_NEWLINE ; end (* then *) end (* tag/ca *) ; PBGN : begin (******************) (* STRING OPERAND *) (******************) READLN ( PCODEF , CH , PROGHDR ) ; if ASM then begin WRITE ( LIST002 , ' ' , PROGHDR ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PENT : READ_ENT ; PLDC , PLCA , PDFC : READLOADINSTRUCTIONS ; PCSP : begin (*************************************) (* SUBMONITOR OPERATION NAME OPERAND *) (*************************************) SKIPBLANKS ; READ ( PCODEF , P_OPCODE ) ; if FALSE then WRITE ( TRACEF , 'read = ' , P_OPCODE ) ; if PCODEF -> = ',' then begin READLN ( PCODEF , CH , PROCOFFSET ) ; end (* then *) else begin READLN ( PCODEF ) ; PROCOFFSET := 0 ; end (* else *) ; OP_SP := FALSE ; ENTERLOOKUP ; OP_SP := TRUE ; if ASM then begin WRITE ( LIST002 , P_OPCODE : 5 , ',' , PROCOFFSET : 1 ) ; LIST002_NEWLINE ; end (* then *) ; if FALSE then WRITELN ( TRACEF , ' csp = ' , ORD ( CSP ) ) ; end (* tag/ca *) ; //************************************************************ // vstring instructions //************************************************************ PVPU , PVPO : begin //************************************************************ // TWO INTEGER OPERANDS //************************************************************ READLN ( PCODEF , P , CH , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , P : 1 , ',' , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PVLD , PVST : begin //************************************************************ // TWO INTEGER OPERANDS // the first one is a mode indicator //************************************************************ READLN ( PCODEF , P , CH , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , P : 1 , ',' , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PVC1 , PVCC , PVLM , PVIX , PVRP : begin //************************************************************ // no operands //************************************************************ READLN ( PCODEF ) ; if ASM then LIST002_NEWLINE ; end (* tag/ca *) ; PVC2 , PVMV , PVSM : begin //************************************************************ // one integer operand //************************************************************ READLN ( PCODEF , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PMCC : begin //************************************************************ // one integer operand //************************************************************ READLN ( PCODEF , Q ) ; if ASM then begin WRITE ( LIST002 , ' ' : 2 , Q : 1 ) ; LIST002_NEWLINE end (* then *) ; end (* tag/ca *) ; PMCV : begin //************************************************************ // no operands //************************************************************ READLN ( PCODEF ) ; if ASM then LIST002_NEWLINE ; end (* tag/ca *) ; otherwise begin (*****************************) (* OPCODE NOT FOUND IN TABLE *) (*****************************) if not ASM then WRITE ( OUTPUT , LBL1 . NAM : LBL1 . LEN , ' ' : 6 - LBL1 . LEN , ' "' , P_OPCODE , '" ' ) ; while not EOLN ( PCODEF ) do begin WRITE ( OUTPUT , PCODEF -> ) ; GET ( PCODEF ) end (* while *) ; WRITELN ( OUTPUT ) ; READLN ( PCODEF ) ; ERROR ( 606 ) ; end (* otherw *) ; end (* case *) ; READNXTINST := EOF ( PCODEF ) ; end (* READNXTINST *) ; procedure ASMNXTINST ; (*********************************************************************) (* TO TRANSLATE THE NEXT P_INSTRUCTION INTO 370 ASSEMBLY/OBJECT CODE *) (* ----------------------------------------------------------------- *) (*********************************************************************) const SL8 = 256 ; // SHIFT LEFT 8 BITS SL12 = 4096 ; // 12 SL16 = 65536 ; // 16 SL24 = 16777216 ; // 24 var P1 , P2 , B1 , B2 : LVLRNG ; Q1 , Q2 : ADRRNG ; I , J : INTEGER ; OPPTR : STKPTR ; RGADR1 : RGRNG ; RGADR2 : RGRNG ; LBLX : PLABEL ; C : CHAR ; LITOK : INTEGER ; TAG : array [ 1 .. 3 ] of CHAR ; NXTINT : 0 .. INTCNT ; XOFFS : INTEGER ; (***************************************************) (* THE FOLLOWING PROCEDURES ARE FOR OBJECT CODE *) (* GENERATION ONLY *) (* ----------------------------------------------- *) (***************************************************) function NEXTPC ( PCINCR : ICRNG ) : ICRNG ; begin (* NEXTPC *) if FALSE then WRITELN ( TRACEF , 'nextpc: pcounter = ' , PCOUNTER , ' pcincr = ' , PCINCR ) ; if PCOUNTER >= MXCODE then begin ERROR ( 253 ) ; EXIT ( 253 ) end (* then *) ; NEXTPC := PCOUNTER + PCINCR ; end (* NEXTPC *) ; function BASE_DSPLMT ( PCOUNTER : ICRNG ) : INTEGER ; (*****************************************************) (* CONVERTS PROGRAM COUNTER VALUES TO 370 *) (* BASE/DISPLACEMENT HALF WORDS *) (* ------------------------------------------------- *) (*****************************************************) var PC : INTEGER ; begin (* BASE_DSPLMT *) PC := 2 * PCOUNTER ; if PC < 4096 then begin BASE_DSPLMT := PBR1 * SL12 + PC ; return end (* then *) ; if PC <= 8188 then begin BASE_DSPLMT := PBR2 * SL12 + PC - 4092 ; return end (* then *) ; if FALSE then $ERROR ( 999 ) ; ERROR ( 254 ) end (* BASE_DSPLMT *) ; procedure UPD_DBLTBL ( PCOUNTER : ICRNG ; R : REAL ) ; var I : INTEGER ; S_R : record case INTEGER of 1 : ( R : REAL ) ; 2 : ( S : SHORT_SET ) ; end ; begin (* UPD_DBLTBL *) DBLALN := TRUE ; //****************************************************** // INDICATE ALIGNMENT FOR LITERAL POOL //****************************************************** IDP_POOL . R [ LX . NXTDBL ] := R ; I := 0 ; //****************************************************** // look for matching entry in idp_pool //****************************************************** S_R . R := R ; while IDP_POOL . S [ I ] <> S_R . S do I := I + 1 ; //****************************************************** // if the matching entry contains the integer gaps // don't use the integer gaps ! //****************************************************** if I = LX . RICONF then begin LX . RICONF := - 1 ; LX . INT_GAP := - 1 end (* then *) ; //****************************************************** // if the matching entry contains the halfword gaps // don't use the halfword gaps ! //****************************************************** if I = LX . RHCONF then begin LX . RHCONF := - 1 ; LX . HW_GAP := - 1 end (* then *) ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := PCOUNTER ; //****************************************************** // if index found = nxtdbl, then increase nxtdbl //****************************************************** if I = LX . NXTDBL then LX . NXTDBL := LX . NXTDBL + 1 ; I := I * 8 ; //****************************************************** // set nxtch to nxtdbl + 8 //****************************************************** if I >= LX . NXTCH then LX . NXTCH := I + 8 ; //****************************************************** // insert pointer to literal pool into code //****************************************************** CODE . H [ PCOUNTER ] := TO_HINT ( I ) ; LITTBL [ NXTLIT ] . LTYPE := 'D' ; LITTBL [ NXTLIT ] . LENGTH := 8 ; LITTBL [ NXTLIT ] . XIDP := I ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'upd_dbltbl: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'upd_dbltbl: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'upd_dbltbl: lnk/pc = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'upd_dbltbl: ltype = ' , 'D' ) ; WRITELN ( TRACEF , 'upd_dbltbl: length = ' , 8 ) ; WRITELN ( TRACEF , 'upd_dbltbl: xidp = ' , I ) ; WRITELN ( TRACEF , 'upd_dbltbl: opt = ' , FALSE ) ; end (* then *) ; end (* UPD_DBLTBL *) ; procedure UPD_HWTBL ( PCOUNTER : ICRNG ; H : HINTEGER ) ; var I , NXTHW : 0 .. HWCNT ; begin (* UPD_HWTBL *) if LX . HW_GAP >= 0 then //****************************************************** // if there is a halfword gap // PREVENT MATCH WITH EMPTY SLOT //****************************************************** if H = 0 then IDP_POOL . H [ LX . HW_GAP ] := - 1 else IDP_POOL . H [ LX . HW_GAP ] := 0 ; if LX . INT_GAP >= 0 then //****************************************************** // if there is an integer gap // PREVENT MATCH WITH EMPTY SLOT //****************************************************** if H = 0 then IDP_POOL . I [ LX . INT_GAP ] := - 1 else IDP_POOL . I [ LX . INT_GAP ] := 0 ; //****************************************************** // look for matching entry in idp_pool //****************************************************** NXTHW := LX . NXTDBL * 4 ; IDP_POOL . H [ NXTHW ] := H ; I := 0 ; while IDP_POOL . H [ I ] <> H do I := I + 1 ; if I = NXTHW then if LX . HW_GAP >= 0 then begin //****************************************************** // NOW USE EMPTY SLOT //****************************************************** I := LX . HW_GAP ; IDP_POOL . H [ I ] := H ; LX . HW_GAP := - 1 ; LX . IHCONF := - 1 ; LX . RHCONF := - 1 end (* then *) else if LX . INT_GAP >= 0 then begin //****************************************************** // SPLIT EMPTY INTEGER SLOT //****************************************************** LX . HW_GAP := 2 * LX . INT_GAP + 1 ; I := LX . HW_GAP - 1 ; IDP_POOL . H [ I ] := H ; LX . IHCONF := LX . INT_GAP ; LX . RHCONF := LX . IHCONF DIV 2 ; LX . RICONF := - 1 ; IDP_POOL . H [ LX . HW_GAP ] := 0 ; LX . INT_GAP := - 1 end (* then *) else begin //****************************************************** // use new double entry, // generate two gaps //****************************************************** LX . HW_GAP := NXTHW + 1 ; LX . INT_GAP := LX . NXTDBL * 2 + 1 ; LX . RICONF := LX . NXTDBL ; LX . RHCONF := LX . NXTDBL ; LX . IHCONF := LX . INT_GAP - 1 ; LX . NXTDBL := LX . NXTDBL + 1 ; IDP_POOL . I [ LX . INT_GAP ] := 0 ; IDP_POOL . H [ LX . HW_GAP ] := 0 ; end (* else *) ; I := I * 2 ; CODE . H [ PCOUNTER ] := TO_HINT ( I ) ; if I >= LX . NXTCH then LX . NXTCH := I + 2 ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := PCOUNTER ; LITTBL [ NXTLIT ] . LTYPE := 'H' ; LITTBL [ NXTLIT ] . LENGTH := 2 ; LITTBL [ NXTLIT ] . XIDP := I ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'upd_hwtbl: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'upd_hwtbl: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'upd_hwtbl: lnk/pc = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'upd_hwtbl: ltype = ' , 'H' ) ; WRITELN ( TRACEF , 'upd_hwtbl: length = ' , 2 ) ; WRITELN ( TRACEF , 'upd_hwtbl: xidp = ' , I ) ; WRITELN ( TRACEF , 'upd_hwtbl: opt = ' , FALSE ) ; end (* then *) ; end (* UPD_HWTBL *) ; procedure UPD_INTTBL ( PCOUNTER : ICRNG ; D : INTEGER ) ; var I , NXTINT : 0 .. INTCNT ; begin (* UPD_INTTBL *) if LX . INT_GAP >= 0 then //****************************************************** // if there is an integer gap // PREVENT MATCH WITH EMPTY SLOT //****************************************************** if D = 0 then IDP_POOL . I [ LX . INT_GAP ] := - 1 else IDP_POOL . I [ LX . INT_GAP ] := 0 ; NXTINT := LX . NXTDBL * 2 ; IDP_POOL . I [ NXTINT ] := D ; I := 0 ; while IDP_POOL . I [ I ] <> D do I := I + 1 ; //****************************************************** // if the matching entry contains the halfword gaps // don't use the halfword gaps ! //****************************************************** if I = LX . IHCONF then begin LX . HW_GAP := - 1 ; LX . IHCONF := - 1 ; LX . RHCONF := - 1 end (* then *) ; if I = NXTINT then if LX . INT_GAP >= 0 then begin //****************************************************** // NOW USE EMPTY SLOT //****************************************************** I := LX . INT_GAP ; LX . INT_GAP := - 1 ; LX . RICONF := - 1 ; IDP_POOL . I [ I ] := D ; end (* then *) else begin //****************************************************** // use new double entry, // generate integer gap //****************************************************** LX . INT_GAP := NXTINT + 1 ; LX . RICONF := LX . INT_GAP DIV 2 ; LX . NXTDBL := LX . NXTDBL + 1 ; IDP_POOL . I [ LX . INT_GAP ] := 0 ; end (* else *) ; I := I * 4 ; CODE . H [ PCOUNTER ] := TO_HINT ( I ) ; if I >= LX . NXTCH then LX . NXTCH := I + 4 ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := PCOUNTER ; LITTBL [ NXTLIT ] . LTYPE := 'I' ; LITTBL [ NXTLIT ] . LENGTH := 4 ; LITTBL [ NXTLIT ] . XIDP := I ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'upd_inttbl: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'upd_inttbl: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'upd_inttbl: lnk/pc = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'upd_inttbl: d = ' , D ) ; WRITELN ( TRACEF , 'upd_inttbl: ltype = ' , 'I' ) ; WRITELN ( TRACEF , 'upd_inttbl: length = ' , 4 ) ; WRITELN ( TRACEF , 'upd_inttbl: xidp = ' , I ) ; WRITELN ( TRACEF , 'upd_inttbl: opt = ' , FALSE ) ; end (* then *) ; end (* UPD_INTTBL *) ; procedure UPD_SETTBL ( PCOUNTER : ICRNG ; PS : LARGE_SET ; L : INTEGER ) ; type SET_S_I = record case INTEGER of 1 : ( S : LARGE_SET ) ; 2 : ( I : array [ 1 .. MXSETIXI ] of INTEGER ) ; 3 : ( C : array [ 1 .. MXSETLEN ] of CHAR ) ; 4 : ( R : array [ 1 .. MXSETINX ] of REAL ) end ; var S_I : SET_S_I ; I , J , LD4 : INTEGER ; begin (* UPD_SETTBL *) S_I . S := PS ; /*************************/ /* show error when l = 0 */ /*************************/ if L = 0 then begin ERROR ( 616 ) ; return end (* then *) ; /********************************************/ /* set literal of length 4 - use upd_inttbl */ /********************************************/ if L <= 4 then begin UPD_INTTBL ( PCOUNTER , S_I . I [ 1 ] ) ; return end (* then *) ; /********************************************/ /* set literal of length 8 - use upd_dbltbl */ /********************************************/ if L <= 8 then begin UPD_DBLTBL ( PCOUNTER , S_I . R [ 1 ] ) ; return ; end (* then *) ; /******************/ /* longer literal */ /******************/ while ( L MOD INTSIZE ) <> 0 do L := L + 1 ; LD4 := L DIV 4 ; I := 2 * LX . NXTDBL ; //****************************************************** // if int_gap preceeding free area, use int_gap, too //****************************************************** if LX . INT_GAP >= 0 then if LX . INT_GAP = I - 1 then begin I := I - 1 ; LX . INT_GAP := - 1 ; LX . RICONF := - 1 end (* then *) ; //****************************************************** // set literal starts at this position (I * 4) // integer bound //****************************************************** CODE . H [ PCOUNTER ] := TO_HINT ( I * 4 ) ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := PCOUNTER ; LITTBL [ NXTLIT ] . LTYPE := 'S' ; LITTBL [ NXTLIT ] . LENGTH := L ; LITTBL [ NXTLIT ] . XIDP := I * 4 ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'upd_settbl: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'upd_settbl: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'upd_settbl: lnk/pc = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'upd_settbl: ltype = ' , 'S' ) ; WRITELN ( TRACEF , 'upd_settbl: length = ' , L ) ; WRITELN ( TRACEF , 'upd_settbl: xidp = ' , I * 4 ) ; WRITELN ( TRACEF , 'upd_settbl: opt = ' , FALSE ) ; end (* then *) ; //****************************************************** // copy set literal to literal pool //****************************************************** for J := 1 to LD4 do begin IDP_POOL . I [ I ] := S_I . I [ J ] ; I := I + 1 ; end (* for *) ; //****************************************************** // adjust nxtch and nxtdbl // and set new integer gap, if needed //****************************************************** if I * 4 > LX . NXTCH then LX . NXTCH := I * 4 ; if I > LX . NXTDBL * 2 then begin LX . NXTDBL := I DIV 2 ; if ODD ( I ) then begin LX . RICONF := LX . NXTDBL ; LX . NXTDBL := LX . NXTDBL + 1 ; LX . INT_GAP := I ; IDP_POOL . I [ I ] := 0 ; end (* then *) ; end (* then *) end (* UPD_SETTBL *) ; procedure INS_PRCTBL ( PRC_NAME : ALFA ; VPOS : ICRNG ) ; (*******************************************************) (* Insert External Reference *) (* ------------------------- *) (* an der vorgegebenen Position (VPos) befindet sich *) (* eine externe Referenz mit dem angegeben Namen *) (* (V-Adresse); diese ist bislang noch nicht vor- *) (* handen und soll von nachfolgenden L-Befehlen *) (* wie ein Literal verwendet werden. *) (*******************************************************) begin (* INS_PRCTBL *) PRCTBL [ NXTPRC ] . NAME := PRC_NAME ; PRCTBL [ NXTPRC ] . LNK := 0 ; PRCTBL [ NXTPRC ] . VPOS := VPOS ; if NXTPRC >= NXTEP then ERROR ( 256 ) else begin NXTPRC := NXTPRC + 1 ; PRCTBL [ NXTPRC ] . LNK := 0 ; PRCTBL [ NXTPRC ] . VPOS := 0 ; end (* else *) end (* INS_PRCTBL *) ; procedure UPD_PRCTBL ( PCOUNTER : ICRNG ; PRC_NAME : ALFA ) ; (*******************************************************) (* TO UPDATE EXTERNAL REFERENCE TABLE *) (* ---------------------------------- *) (* PRC-Name = Name der (neuen) externen Referenz; *) (* dieser Name wird zunaechst an der Position *) (* NXTPRC in die Tabelle PRCTBL eingetragen. *) (* Dann Suche, ob es evtl. in der Tabelle schon *) (* vorhanden ist. Falls ja, CODE.H an der Position *) (* PCOUNTER verlinken mit dem entsprechenden *) (* Eintrag (beide Richtungen). Wenn I = NXTPRC, *) (* dann war es der neu eingefuegte hoechste Eintrag, *) (* dann Pruefung auf Einhaltung der Grenzen, *) (* ansonsten naechsten Eintrag vorbereiten. *) (* --------------------------------------------------- *) (* Nachtrag: die Positionen im Code, wo dieselben *) (* externen Namen benutzt werden, sind miteinander *) (* verkettet ueber den LNK-Pointer; damit koennen *) (* nach Festlegung der Adresse alle Offsets *) (* angeglichen werden. *) (*******************************************************) var I : 0 .. PRCCNT ; begin (* UPD_PRCTBL *) PRCTBL [ NXTPRC ] . NAME := PRC_NAME ; PRCTBL [ NXTPRC ] . VPOS := 0 ; I := 0 ; while PRCTBL [ I ] . NAME <> PRC_NAME do I := I + 1 ; CODE . H [ PCOUNTER ] := TO_HINT ( PRCTBL [ I ] . LNK ) ; PRCTBL [ I ] . LNK := PCOUNTER ; if I = NXTPRC then if NXTPRC >= NXTEP then ERROR ( 256 ) else begin NXTPRC := NXTPRC + 1 ; PRCTBL [ NXTPRC ] . LNK := 0 ; PRCTBL [ NXTPRC ] . VPOS := 0 ; end (* else *) end (* UPD_PRCTBL *) ; function LBLMAP ( ALFLBL : ALFA ) : LBLRNG ; var I : 2 .. 8 ; J : LBLRNG ; begin (* LBLMAP *) I := 2 ; J := 0 ; repeat J := J * 10 + ORD ( ALFLBL [ I ] ) - ORD ( '0' ) ; I := I + 1 until ALFLBL [ I ] = ' ' ; LBLMAP := J ; end (* LBLMAP *) ; procedure UPD_LBLTBL ( PCOUNTER : ICRNG ; INTLBL : LBLRNG ; NEWLBL : BOOLEAN ; CASE_FLOW : BOOLEAN ) ; (********************************************************) (* TO 'DEFINE' LABELS AND/OR RESOLVE FORWARD REFERENCES *) (* ---------------------------------------------------- *) (********************************************************) var TPC , QPC : INTEGER ; begin (* UPD_LBLTBL *) if FALSE then begin WRITELN ( TRACEF , 'upd_lbltbl: pcounter = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'upd_lbltbl: intlbl = ' , INTLBL ) ; WRITELN ( TRACEF , 'upd_lbltbl: newlbl = ' , NEWLBL ) ; WRITELN ( TRACEF , 'upd_lbltbl: case_flow = ' , CASE_FLOW ) ; end (* then *) ; if INTLBL > LBLCNT then begin WRITELN ( ' **** INTLBL ' : 17 , INTLBL ) ; ERROR ( 263 ) ; EXIT ( 263 ) end (* then *) else with LBLTBL [ INTLBL ] do begin if FALSE then begin WRITELN ( TRACEF , 'upd_lbltbl: defined = ' , DEFINED ) ; end (* then *) ; if DEFINED then (**********************) (* BACKWARD REFERENCE *) (**********************) if CASE_FLOW then CODE . H [ PCOUNTER ] := TO_HINT ( LNK * 2 ) (****************) (*HALFWORD ADDR.*) (****************) else CODE . H [ PCOUNTER ] := TO_HINT ( BASE_DSPLMT ( LNK ) ) (***************************) (* BASE/DSPLMT HALF WORD *) (***************************) else if NEWLBL then (********************) (* LABEL DEFINITION *) (********************) begin DEFINED := TRUE ; TPC := LNK ; LNK := PCOUNTER ; if FALSE then begin WRITELN ( TRACEF , 'upd_lbltbl: newlbl = ' , NEWLBL ) ; WRITELN ( TRACEF , 'upd_lbltbl: lnk = ' , LNK ) ; end (* then *) ; (*******************) (* SET LABEL VALUE *) (*******************) while TPC > 1 do begin QPC := TPC ; TPC := CODE . H [ QPC ] ; if TPC < 0 then begin CODE . H [ QPC ] := TO_HINT ( PCOUNTER * 2 ) ; TPC := ABS ( TPC ) end (* then *) else CODE . H [ QPC ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER ) ) ; end (* while *) end (* then *) else (***********************************************************) (* NOT NEWLBL I.E. FORWARD REFERENCE, TO BE RESOLVED LATER *) (***********************************************************) begin if CASE_FLOW then CODE . H [ PCOUNTER ] := TO_HINT ( - LNK ) else CODE . H [ PCOUNTER ] := TO_HINT ( LNK ) ; LNK := PCOUNTER end (* else *) end (* with *) end (* UPD_LBLTBL *) ; procedure PRINT_SET ( S : LARGE_SET ; LNGTH : BYTE ) ; var I : INTEGER ; DELIM : CHAR ; C , C1 , C2 : CHAR ; COL : INTEGER ; begin (* PRINT_SET *) PSVAL := S ; DELIM := '''' ; WRITE ( LIST002 , '=XL' , LNGTH : 1 , '''' ) ; if FALSE then WRITE ( TRACEF , '=XL' , LNGTH : 1 , '''' ) ; COL := 0 ; for I := 1 to LNGTH do begin C := PSVAL . C [ I ] ; C1 := HEXTAB [ ORD ( C ) DIV 16 ] ; C2 := HEXTAB [ ORD ( C ) MOD 16 ] ; if COL + 1 > 32 then begin WRITE ( LIST002 , 'X' ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' ' : 21 ) ; COL := 1 ; end (* then *) else COL := COL + 1 ; WRITE ( LIST002 , C1 ) ; if FALSE then WRITE ( TRACEF , C1 ) ; COL := COL + 1 ; WRITE ( LIST002 , C2 ) ; if FALSE then WRITE ( TRACEF , C2 ) ; end (* for *) ; WRITE ( LIST002 , '''' ) ; LIST002_NEWLINE ; if FALSE then WRITELN ( TRACEF , '''' ) ; end (* PRINT_SET *) ; procedure TRACE_SET ( S : LARGE_SET ; LNGTH : BYTE ) ; var I : INTEGER ; DELIM : CHAR ; C , C1 , C2 : CHAR ; COL : INTEGER ; begin (* TRACE_SET *) PSVAL := S ; DELIM := '''' ; WRITE ( TRACEF , '=XL' , LNGTH : 1 , '''' ) ; COL := 0 ; for I := 1 to LNGTH do begin C := PSVAL . C [ I ] ; C1 := HEXTAB [ ORD ( C ) DIV 16 ] ; C2 := HEXTAB [ ORD ( C ) MOD 16 ] ; if COL + 1 > 32 then begin WRITELN ( TRACEF , 'X' ) ; WRITE ( TRACEF , ' ' : 21 ) ; COL := 1 ; end (* then *) else COL := COL + 1 ; WRITE ( TRACEF , C1 ) ; COL := COL + 1 ; WRITE ( TRACEF , C2 ) ; end (* for *) ; WRITELN ( TRACEF , '''' ) ; end (* TRACE_SET *) ; (****************************************************) (* 370 FORMAT CODE GENERATOR (ASSEMBLY/OBJECT CODE) *) (* ------------------------------------------------ *) (****************************************************) procedure GENRR ( OP : BYTE ; R1 , R2 : RGRNG ) ; begin (* GENRR *) if R1 = TRG14 then TXR_CONTENTS . VALID := FALSE ; if OPT_FLG then if ( OP = XLTR ) or ( OP = XLTDR ) then with LAST_CC do if PCOUNTER = LAST_PC then (*******************************) (* NO INTERVENING INSTRUCTIONS *) (*******************************) if R1 = R2 then if LR = R1 then if OP = XLTDR then if LOP in [ XAD , XSD , XLCDR , XLPDR , XADR , XSDR , XAD , XSD ] then return else else (*************) (* OP = XLTR *) (*************) if LOP in [ XLPR , XLCR , XNR , XORX , XXR , XAR , XSR , XAH , XSH , XO , XX , XN , XSLA , XSRA , XA , XS ] then return ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R1 : 1 , ',' , R2 : 1 ) ; LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R1 * 16 + R2 ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 1 ) ; with LAST_CC do begin LAST_PC := PCOUNTER ; LR := R1 ; LOP := OP end (* with *) ; end (* GENRR *) ; procedure GENRXLIT_EXTENDED ( OP : BYTE ; R : RGRNG ; D : INTEGER ; TAG : INTEGER ; EX_OPCODE : INTEGER ) ; FORWARD ; procedure GENRXLIT ( OP : BYTE ; R : RGRNG ; D : INTEGER ; TAG : INTEGER ) ; begin (* GENRXLIT *) GENRXLIT_EXTENDED ( OP , R , D , TAG , 0 ) ; end (* GENRXLIT *) ; procedure GENRX_2 ( OP : BYTE ; R : RGRNG ; D : ADRRNG ; X , B : RGRNG ; OPTION : INTEGER ) ; begin (* GENRX_2 *) if R = TRG14 then TXR_CONTENTS . VALID := FALSE ; if FALSE then begin WRITELN ( TRACEF , '---------------------------------------' ) ; WRITELN ( TRACEF , 'genrx_2 at linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'op = ' , XTBLN [ OP ] ) ; WRITELN ( TRACEF , 'r = ' , R ) ; WRITELN ( TRACEF , 'd = ' , D ) ; WRITELN ( TRACEF , 'x = ' , X ) ; WRITELN ( TRACEF , 'b = ' , B ) ; WRITELN ( TRACEF , 'opt = ' , OPTION ) ; end (* then *) ; if ( D < 0 ) or ( D > SHRTINT ) then begin (*********************************) (*THIS SHOULD NOT BE THE CASE NOW*) (*********************************) ERROR ( 608 ) ; TXR_CONTENTS . VALID := FALSE ; if B = TXRG then GENRXLIT ( XA , TXRG , D , 0 ) else begin GENRXLIT ( XL , TXRG , D , 0 ) ; if B = 0 then B := TXRG else if X = 0 then X := TXRG else begin GENRR ( XAR , TXRG , B ) ; B := TXRG end (* else *) ; end (* else *) ; D := 0 end (* then *) ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R : 1 , ',' ) ; case OPTION of 99 : ; 3 : begin WRITE ( LIST002 , '<constant>' ) ; if ( X > 0 ) or ( B > 0 ) then begin WRITE ( LIST002 , '(' , X : 1 ) ; if B > 0 then WRITE ( LIST002 , ',' , B : 1 ) ; WRITE ( LIST002 , ')' ) ; end (* then *) ; end (* tag/ca *) ; 2 : WRITE ( LIST002 , '<constant>' ) ; 1 : begin WRITE ( LIST002 , D : 1 ) ; if ( X > 0 ) or ( B > 0 ) then begin WRITE ( LIST002 , '(' , X : 1 ) ; if B > 0 then WRITE ( LIST002 , ',' , B : 1 ) ; WRITE ( LIST002 , ')' ) ; end (* then *) ; end (* tag/ca *) end (* case *) ; if OPTION <> 99 then LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R * 16 + X ) ; CODE . H [ PCOUNTER + 1 ] := TO_HINT ( SL12 * B + D ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 2 ) ; with LAST_CC do begin LAST_PC := PCOUNTER ; LR := R ; LOP := OP end (* with *) ; end (* GENRX_2 *) ; procedure GENRX ( OP : BYTE ; R : RGRNG ; D : ADRRNG ; X , B : RGRNG ) ; begin (* GENRX *) GENRX_2 ( OP , R , D , X , B , 1 ) end (* GENRX *) ; procedure GENRXLIT_EXTENDED ; var DLEFT , DRIGHT : INTEGER ; OP1 , OP2 : INTEGER ; begin (* GENRXLIT_EXTENDED *) if R = TRG14 then TXR_CONTENTS . VALID := FALSE ; if TAG >= 0 then if ( OP >= XL ) and ( OP <= XS ) then if ( D >= - 32768 ) and ( D <= 32767 ) then begin OP := OP - 16 ; (***********************) (* USE HALFWORD INSTR. *) (***********************) TAG := - 1 ; end (* then *) ; if OP = XLH then if ( D >= 0 ) and ( D <= SHRTINT ) then begin GENRX ( XLA , R , D , 0 , 0 ) ; return end (* then *) ; if OP = XAH then if D = - 1 then begin GENRR ( XBCTR , R , 0 ) ; return end (* then *) ; if OP = XSH then if D = 1 then begin GENRR ( XBCTR , R , 0 ) ; return end (* then *) ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R : 1 ) ; if TAG < 0 then begin WRITE ( LIST002 , ',=H''' , D : 1 , '''' ) ; LIST002_NEWLINE ; end (* then *) else if TAG = 0 then begin WRITE ( LIST002 , ',=F''' , D : 1 , '''' ) ; if OP = XEX then begin if EX_OPCODE = XOI then WRITE ( LIST002 , ' OI 0(R1),X''00''' ) else begin OP1 := D and 0xffff ; OP2 := OP1 and 0xfff ; OP1 := OP1 DIV 4096 ; WRITE ( LIST002 , ' CLI ' , OP2 : 1 , '(R' , OP1 : 1 , '),X''00''' ) end (* else *) end (* then *) ; LIST002_NEWLINE ; end (* then *) else begin DLEFT := D and ( not 0xffff ) ; DRIGHT := D and 0xffff ; DLEFT := DLEFT DIV 65536 ; WRITE ( LIST002 , ',=H''' , DLEFT : 1 , ',' , DRIGHT : 1 , '''' ) ; LIST002_NEWLINE ; end (* else *) end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R * 16 ) ; if TAG < 0 then UPD_HWTBL ( PCOUNTER + 1 , D ) else UPD_INTTBL ( PCOUNTER + 1 , D ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 2 ) ; with LAST_CC do begin LAST_PC := PCOUNTER ; LR := R ; LOP := OP end (* with *) end (* GENRXLIT_EXTENDED *) ; procedure GENRXDLIT ( OP : BYTE ; R : RGRNG ; VAL : REAL ) ; begin (* GENRXDLIT *) if OP = XLD then if VAL = 0.0 then begin GENRR ( XSDR , R , R ) ; return end (* then *) ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R : 1 , ',=D''' , VAL : 20 , '''' ) ; LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R * 16 + 00 ) ; UPD_DBLTBL ( PCOUNTER + 1 , VAL ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 2 ) ; with LAST_CC do begin LAST_PC := PCOUNTER ; LR := R ; LOP := OP end (* with *) ; end (* GENRXDLIT *) ; procedure GENRS ( OP : BYTE ; R1 , R2 : RGRNG ; D : ADRRNG ; B : RGRNG ) ; begin (* GENRS *) if R1 = TRG14 then TXR_CONTENTS . VALID := FALSE ; if ( D < 0 ) or ( D > SHRTINT ) then begin if B <> TXRG then GENRR ( XLR , TXRG , B ) ; GENRXLIT ( XA , TXRG , D , 0 ) ; D := 0 ; B := TXRG ; end (* then *) ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; if ( OP <= XSLDA ) and ( OP >= XSRL ) then WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R1 : 1 , ',' , D : 1 ) else WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R1 : 1 , ',' , R2 : 1 , ',' , D : 1 ) ; if B <> 0 then WRITE ( LIST002 , '(' , B : 1 , ')' ) ; LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R1 * 16 + R2 ) ; CODE . H [ PCOUNTER + 1 ] := TO_HINT ( B * SL12 + D ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 2 ) ; end (* GENRS *) ; procedure GENRSLIT ( OP : BYTE ; R1 , R2 : RGRNG ; S : SHORT_SET ) ; var LS : LARGE_SET ; begin (* GENRSLIT *) I_S_R . S := S ; if R1 = TRG14 then TXR_CONTENTS . VALID := FALSE ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R1 : 1 , ',' , R2 : 1 , ',' ) ; (*************************************************) (* it is sufficient to assign the first part of *) (* ls, because print_set will only use this part *) (*************************************************) LS . S [ 1 ] := S ; PRINT_SET ( LS , 8 ) ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R1 * 16 + R2 ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 2 ) ; UPD_DBLTBL ( PCOUNTER - 1 , I_S_R . R ) ; end (* GENRSLIT *) ; procedure GENSS ( OP : BYTE ; LNGTH : BYTE_PLUS_ONE ; D1 : ADRRNG ; B1 : RGRNG ; D2 : ADRRNG ; B2 : RGRNG ) ; begin (* GENSS *) (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , D1 : 1 , '(' , LNGTH : 1 , ',' , B1 : 1 , '),' , D2 : 1 , '(' , B2 : 1 , ')' ) ; LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + ( LNGTH - 1 ) ) ; CODE . H [ PCOUNTER + 1 ] := TO_HINT ( B1 * SL12 + D1 ) ; CODE . H [ PCOUNTER + 2 ] := TO_HINT ( B2 * SL12 + D2 ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 3 ) ; end (* GENSS *) ; procedure GENSI ( OP : BYTE ; D : ADRRNG ; B : RGRNG ; I : BYTE ) ; begin (* GENSI *) (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , D : 1 , '(' , B : 1 , '),' , I : 1 ) ; LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + I ) ; CODE . H [ PCOUNTER + 1 ] := TO_HINT ( B * SL12 + D ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 2 ) ; end (* GENSI *) ; procedure GENSSLIT ( OP , LNGTH : BYTE ; D1 : ADRRNG ; B1 : RGRNG ; S : LARGE_SET ) ; begin (* GENSSLIT *) if LNGTH = 1 then (*********************************) (* SUBSTITUTE AN IMMEDIATE INST. *) (*********************************) begin I_S_R . S := S . S [ 1 ] ; GENSI ( OP - XMVC + XMVI , D1 , B1 , ORD ( I_S_R . C1 ) ) ; end (* then *) else if LNGTH > 1 then begin (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , D1 : 1 , '(' , LNGTH : 1 , ',' , B1 : 1 , '),' ) ; PRINT_SET ( S , LNGTH ) ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + ( LNGTH - 1 ) ) ; CODE . H [ PCOUNTER + 1 ] := TO_HINT ( B1 * SL12 + D1 ) ; UPD_SETTBL ( PCOUNTER + 2 , S , LNGTH ) ; (**********************************) (* increment instr counter *) (**********************************) PCOUNTER := NEXTPC ( 3 ) ; end (* then *) ; end (* GENSSLIT *) ; procedure GENAL2 ( PC : ICRNG ; LAB : PLABEL ) ; var INTLBL : INTEGER ; begin (* GENAL2 *) if ASM then begin HEXHW ( PC * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , ' DC AL2(' , LAB . NAM : LAB . LEN , '-' , PRCTBL [ 0 ] . NAME , ')' ) ; LIST002_NEWLINE ; end (* then *) ; INTLBL := LBLMAP ( LAB . NAM ) ; UPD_LBLTBL ( PC , INTLBL , FALSE , TRUE ) ; if FALSE then begin WRITELN ( TRACEF , 'genal2: pc = ' , PC ) ; WRITELN ( TRACEF , 'genal2: intlbl = ' , INTLBL ) ; end (* then *) ; end (* GENAL2 *) ; procedure GENRXLAB ( OP : BYTE ; R : RGRNG ; LAB : PLABEL ; TAG : INTEGER ) ; begin (* GENRXLAB *) if R = TRG14 then TXR_CONTENTS . VALID := FALSE ; (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; if CASE_FLAG then begin WRITE ( LIST002 , ' DC AL2(' , LAB . NAM : LAB . LEN , '-' , PRCTBL [ 0 ] . NAME , ')' ) ; LIST002_NEWLINE ; end (* then *) else begin WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R : 1 , ',' ) ; if TAG = 0 then WRITE ( LIST002 , LAB . NAM : LAB . LEN ) else if TAG > 0 then WRITE ( LIST002 , LAB . NAM : LAB . LEN , '(' , TAG : 1 , ')' ) else begin if TAG = - 3 then WRITE ( LIST002 , '=V(' ) else (************) (* TAG = -1 *) (************) WRITE ( LIST002 , '=A(' ) ; WRITE ( LIST002 , LAB . NAM : LAB . LEN ) ; WRITE ( LIST002 , ')' ) ; end (* else *) ; LIST002_NEWLINE ; end (* else *) ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) if CASE_FLAG then begin (*********) (*LAB REF*) (*********) UPD_LBLTBL ( PCOUNTER , LBLMAP ( LAB . NAM ) , FALSE , TRUE ) ; PCOUNTER := NEXTPC ( 1 ) ; end (* then *) else begin if TAG >= - 1 then (*****************) (*GENERATED LABEL*) (*****************) UPD_LBLTBL ( PCOUNTER + 1 , LBLMAP ( LAB . NAM ) , FALSE , FALSE ) (*****************) (*LABEL REFERENCE*) (*****************) else (***********) (*PROC. ID.*) (***********) UPD_PRCTBL ( PCOUNTER + 1 , LAB . NAM ) ; if TAG < 0 then TAG := 0 ; CODE . H [ PCOUNTER ] := TO_HINT ( OP * SL8 + R * 16 + TAG ) ; PCOUNTER := NEXTPC ( 2 ) end (* else *) end (* GENRXLAB *) ; procedure GENRELRX ( OP : BYTE ; R : RGRNG ; OFFSET : HINTEGER ) ; (****************************************) (* OPERAND OF RX INST. IS "*+2*OFFSET" *) (****************************************) var SAVEASM : BOOLEAN ; begin (* GENRELRX *) (***********************************) (* write symbolic instr to list002 *) (***********************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , XTBLN [ OP ] : COLASMI , ' ' : SPACEASMI , R : 1 , ',*+' , 2 * OFFSET : 1 ) ; LIST002_NEWLINE ; end (* then *) ; (**********************************) (* insert instr into code buffer *) (**********************************) SAVEASM := ASM ; ASM := FALSE ; GENRX ( OP , R , 0 , 0 , 0 ) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER + OFFSET - 2 ) ) ; ASM := SAVEASM ; end (* GENRELRX *) ; procedure CONS_REGS ( var BASEREG : LVLRNG ; var INDEXREG : LVLRNG ) ; begin (* CONS_REGS *) if INDEXREG = 0 then return ; if BASEREG = 0 then begin BASEREG := INDEXREG ; INDEXREG := 0 ; return end (* then *) ; GENRR ( XAR , BASEREG , INDEXREG ) ; INDEXREG := 0 ; end (* CONS_REGS *) ; procedure BRANCH_CHAIN ( LAST_PC : ICRNG ) ; label 10 ; const X47F0 = 18416 ; X4700 = 18176 ; X4000 = 16384 ; XC000 = 19152 ; MAXCNT = 5 ; var BC15 , TI , DI : record case INTEGER of 1 : ( I : INTEGER ) ; 2 : ( S : set of 0 .. 31 ) ; end ; TPC , DPC : ICRNG ; CNT : 0 .. MAXCNT ; TIOP : INTEGER ; begin (* BRANCH_CHAIN *) BC15 . I := X47F0 ; TPC := PCAFTLIT ; repeat TI . I := CODE . H [ TPC ] ; if TI . I > X4700 then if TI . S <= BC15 . S then (*******************************) (* MUST BE UNINDEXED BC INSTR. *) (*******************************) begin CNT := 0 ; repeat TIOP := CODE . H [ TPC + 1 ] ; if TIOP < 0 then TIOP := TIOP + 65536 ; DPC := ( TIOP MOD SL12 ) DIV 2 ; TIOP := TIOP DIV SL12 - PBR1 ; if TIOP < 0 then goto 10 ; if TIOP > 0 then if TIOP > 1 then goto 10 else DPC := DPC + 2046 ; if DPC >= LAST_PC then goto 10 ; DI . I := CODE . H [ DPC ] ; if DI . I <= X4700 then goto 10 ; if DI . I > X47F0 then goto 10 ; if not ( TI . S <= DI . S ) then goto 10 ; TIOP := CODE . H [ DPC + 1 ] ; CODE . H [ TPC + 1 ] := TO_HINT ( TIOP ) ; CNT := CNT + 1 ; until CNT > MAXCNT ; 10 : end (* then *) ; if TI . I < 0 then TI . I := TI . I + 65536 ; if TI . I < X4000 then TPC := TPC + 1 (********) (* RR *) (********) else if TI . I < XC000 then TPC := TPC + 2 (********) (* RX *) (********) else TPC := TPC + 3 ; (********) (* SS *) (********) until TPC >= LAST_PC ; end (* BRANCH_CHAIN *) ; procedure DUMP_LITERALS ; (***************************************************) (* PROCEDURE TO EMPTY LITERAL POOL INTO CODE ARRAY *) (***************************************************) var I : INTEGER ; QPC : ICRNG ; TPC : ICRNG_EXT ; L : INTEGER ; begin (* DUMP_LITERALS *) if OPT_FLG then if not DEBUG then BRANCH_CHAIN ( PCOUNTER ) ; if ODD ( PCOUNTER ) then GENRR ( XBCR , 0 , 0 ) ; if DBLALN then if ( PCOUNTER MOD 4 ) <> 0 then GENRX ( XBC , 0 , 0 , 0 , 0 ) ; if NXTLIT > 0 then if ( LX . NXTDBL * 4 + PCOUNTER ) <= 8187 then begin if FALSE then WRITELN ( TRACEF , 'DUMP LITERALS ' , ' - linecnt = ' , LINECNT : 1 ) ; for I := 1 to NXTLIT do begin if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'littbl.linecnt = ' , LITTBL [ I ] . XLINECNT ) ; WRITELN ( TRACEF , 'littbl.index = ' , I ) ; WRITELN ( TRACEF , 'littbl.lnk/pc = ' , LITTBL [ I ] . LNK ) ; WRITELN ( TRACEF , 'littbl.ltype = ' , LITTBL [ I ] . LTYPE ) ; WRITELN ( TRACEF , 'littbl.length = ' , LITTBL [ I ] . LENGTH ) ; WRITELN ( TRACEF , 'littbl.xidp = ' , LITTBL [ I ] . XIDP ) ; WRITELN ( TRACEF , 'littbl.opt = ' , LITTBL [ I ] . OPTIMIZED ) ; end (* then *) ; TPC := LITTBL [ I ] . LNK ; if TPC > 0 then //****************************************************** // USUAL CASE //****************************************************** begin QPC := CODE . H [ TPC ] ; if FALSE then WRITELN ( TRACEF , 'code old = ' , QPC ) ; CODE . H [ TPC ] := TO_HINT ( BASE_DSPLMT ( QPC DIV 2 + PCOUNTER ) ) ; if ODD ( QPC ) then CODE . H [ TPC ] := TO_HINT ( CODE . H [ TPC ] + 1 ) ; if FALSE then WRITELN ( TRACEF , 'code new = ' , CODE . H [ TPC ] ) ; end (* then *) else begin if not LITTBL [ I ] . OPTIMIZED then begin ERROR ( 257 ) ; WRITELN ( TRACEF , '*** error 257 *** literal not used ***' ) ; end (* then *) end (* else *) end (* for *) ; //****************************************************** // copy literal pool into code array //****************************************************** TPC := LX . NXTDBL * 2 - 1 ; if LX . INT_GAP = TPC then TPC := TPC - 1 ; POOL_SIZE := POOL_SIZE + TPC * 2 ; NUMLITS := NUMLITS + NXTLIT ; QPC := PCOUNTER DIV 2 ; L := TPC + 1 ; MEMCPY ( ADDR ( CODE . I [ QPC ] ) , ADDR ( IDP_POOL . I [ 0 ] ) , L * 4 ) ; QPC := QPC + L ; PCOUNTER := QPC * 2 ; end (* then *) else ERROR ( 255 ) ; NXTLIT := 0 ; LX . NXTDBL := 0 ; LX . IHCONF := - 1 ; LX . RICONF := - 1 ; LX . RHCONF := - 1 ; LX . INT_GAP := - 1 ; LX . HW_GAP := - 1 ; DBLALN := FALSE ; PCAFTLIT := PCOUNTER ; LX . NXTCH := 0 ; end (* DUMP_LITERALS *) ; procedure FINDRG ; (***********************) (*TO FIND A GP REGISTER*) (***********************) var I : RGRNG ; begin (* FINDRG *) I := 1 ; repeat I := I + 1 until ( AVAIL [ I ] or ( I = RGCNT ) ) ; if not AVAIL [ I ] then ERROR ( 750 ) ; AVAIL [ I ] := FALSE ; NXTRG := I ; end (* FINDRG *) ; procedure FINDRP ; (****************************************************************) (* FIND REGISTER PAIR *) (****************************************************************) var I : RGRNG ; begin (* FINDRP *) I := RGCNT + 1 ; repeat I := I - 2 until ( I < 4 ) or ( AVAIL [ I ] and AVAIL [ I + 1 ] ) ; if not ( AVAIL [ I ] and AVAIL [ I + 1 ] ) then begin //****************************************************** // trial - opp - 02.06.2019: // if filadr (r9) occupied, free it and // signal that filreg has to be // loaded again later // same for callstackadr (r8) //****************************************************** if CSPACTIVE [ FILADR ] and CSPACTIVE [ CALLSTACKADR ] then begin AVAIL [ FILADR ] := TRUE ; CSPACTIVE [ FILADR ] := FALSE ; FILADR_LOADED := FALSE ; AVAIL [ CALLSTACKADR ] := TRUE ; CSPACTIVE [ CALLSTACKADR ] := FALSE ; I := CALLSTACKADR ; end (* then *) else begin ERROR ( 751 ) ; end (* else *) end (* then *) ; AVAIL [ I ] := FALSE ; AVAIL [ I + 1 ] := FALSE ; NXTRG := I end (* FINDRP *) ; procedure FINDFP ; (********************************) (*FIND A FLOATING POINT REGISTER*) (********************************) var I : INTEGER ; begin (* FINDFP *) I := 0 ; repeat I := I + 2 until AVAILFP [ I ] or ( I = FPCNT ) ; if not AVAILFP [ I ] then ERROR ( 752 ) ; AVAILFP [ I ] := FALSE ; NXTRG := I end (* FINDFP *) ; procedure FREEREG ( var STE : DATUM ) ; begin (* FREEREG *) with STE do if VRBL and ( VPA = RGS ) then begin if DTYPE = REEL then AVAILFP [ RGADR ] := TRUE else (*****************) (* DTYPE <> REEL *) (*****************) AVAIL [ RGADR ] := TRUE ; if DRCT and ( DTYPE = PSET ) then if PLEN > 4 then (********************) (* REG. PAIR IN USE *) (********************) AVAIL [ RGADR + 1 ] := TRUE end (* then *) end (* FREEREG *) ; procedure FREEREG_COND ( var STE : DATUM ; RGADR_IN_USE : RGRNG ) ; begin (* FREEREG_COND *) with STE do if VPA = RGS then if RGADR <> RGADR_IN_USE then AVAIL [ RGADR ] := TRUE ; end (* FREEREG_COND *) ; function ALIGN ( Q , P : INTEGER ) : INTEGER ; var I : INTEGER ; begin (* ALIGN *) ALIGN := Q ; I := Q MOD P ; if I <> 0 then ALIGN := Q + ( P - I ) ; end (* ALIGN *) ; function POWER2 ( I : INTEGER ) : INTEGER ; (********************************************************) (* IF I > 0 IS A POWER OF TWO, RETURN 'THAT' POWER, *) (* ELSE RETURN NEGATIVE *) (* ---------------------------------------------------- *) (********************************************************) var K : INTEGER ; begin (* POWER2 *) POWER2 := - 999 ; if I > 0 then begin K := 0 ; while not ODD ( I ) do begin I := I DIV 2 ; K := K + 1 ; end (* while *) ; if I = 1 then POWER2 := K ; end (* then *) ; end (* POWER2 *) ; procedure BASE ( var Q : ADRRNG ; var P , B : LVLRNG ) ; (*******************************************************) (* TO TRANSLATE A 'LEVEL/OFFSET' P/Q ADDRESS *) (* TO 'BASE/INDEX/DISPLACEMENT' *) (* --------------------------------------------------- *) (*******************************************************) const MAXDISP = 4088 ; SHRTINT2 = 8183 ; (*********************) (* SHRTINT + MAXDISP *) (*********************) var T , TQ : ADRRNG ; TP : LVLRNG ; begin (* BASE *) B := 0 ; if P < 0 then return ; (*******************) (* STRING CONSTANT *) (*******************) TQ := Q ; TP := P ; if OPT_FLG then with TXR_CONTENTS do if TP = LEVEL then if VALID then if TXRG = TRG14 then begin T := TQ - OFFSET + DISP ; if ( T >= 0 ) and ( T <= MAXDISP ) then begin Q := T ; P := TRG14 ; B := BASE ; return end (* then *) ; end (* then *) ; if P > 0 then if P = CURLVL then begin B := LBR ; P := 0 end (* then *) else if P = 1 then begin B := GBR ; P := 0 end (* then *) else begin GENRX ( XL , TXRG , DISPLAY + 4 * P , GBR , 0 ) ; P := TXRG ; end (* else *) ; if ( Q < 0 ) or ( Q > SHRTINT2 ) then begin Q := Q - 2048 ; if P > 0 then GENRXLIT ( XA , P , Q , 0 ) else begin GENRXLIT ( XL , TXRG , Q , 0 ) ; P := TXRG end (* else *) ; Q := 2048 end (* then *) else if Q > SHRTINT then begin GENRX ( XLA , TXRG , MAXDISP , B , P ) ; Q := Q - MAXDISP ; P := TXRG ; B := 0 ; end (* then *) ; if P = TRG14 then with TXR_CONTENTS do begin VALID := TRUE ; LEVEL := TP ; OFFSET := TQ ; DISP := Q ; BASE := B ; end (* with *) ; end (* BASE *) ; procedure CHECKDISP ( var Q : ADRRNG ; var P , B : LVLRNG ) ; (*********************************************************) (* TO ELIMINATE THE RESULT Q=4092 *) (* THAT MAY BE GENERATED BY BASE *) (* AND WHICH CAUSES TROUBLE FOR OPERATIONS ON SETS *) (*********************************************************) begin (* CHECKDISP *) if Q > ( SHRTINT - 4 ) then begin GENRX ( XLA , TXRG , SHRTINT - 4 , B , P ) ; Q := Q - ( SHRTINT - 4 ) ; P := TXRG ; B := 0 end (* then *) end (* CHECKDISP *) ; procedure GENLA_LR ( R1 : RGRNG ; Q2 : ADRRNG ; R2 , X2 : RGRNG ) ; begin (* GENLA_LR *) if Q2 = 0 then if R2 = 0 then GENRR ( XLR , R1 , X2 ) else if X2 = 0 then GENRR ( XLR , R1 , R2 ) else GENRX ( XLA , R1 , 0 , R2 , X2 ) else GENRX ( XLA , R1 , Q2 , R2 , X2 ) end (* GENLA_LR *) ; procedure GETADR ( STE : DATUM ; var Q : ADRRNG ; var P , B : RGRNG ) ; FORWARD ; procedure LOAD ( var STE : DATUM ) ; (****************************************************************) (* LOADS AN STACK ELEMENT INTO A REGISTER, IF NOT ALREADY THERE *) (* ------------------------------------------------------------ *) (****************************************************************) var P : LVLRNG ; Q : ADRRNG_EXT ; B : RGRNG ; procedure FINDMDRG ; (************************************) (*TO FIND A MULTIPLY/DIVIDE REGISTER*) (************************************) begin (* FINDMDRG *) if MDTAG = PDVI then begin FINDRP ; AVAIL [ NXTRG + 1 ] := TRUE end (* then *) else if MDTAG = PMPI then begin FINDRP ; AVAIL [ NXTRG ] := TRUE ; NXTRG := NXTRG + 1 end (* then *) else FINDRG ; end (* FINDMDRG *) ; begin (* LOAD *) with STE do begin if VRBL then (**************************************) (* LOAD THE VARIABLE POINTED TO BY STP*) (**************************************) if DRCT then (******************************) (*DIRECTLY ACCESSIBLE VARIABLE*) (******************************) case DTYPE of ADR , HINT , INT , BOOL , CHRC : begin if VPA = MEM then begin FINDMDRG ; P := MEMADR . LVL ; Q := MEMADR . DSPLMT ; BASE ( Q , P , B ) ; case DTYPE of CHRC , BOOL : begin if CLEAR_REG then GENRR ( XSR , NXTRG , NXTRG ) ; GENRX ( XIC , NXTRG , Q , B , P ) ; end (* tag/ca *) ; INT , ADR : GENRX ( XL , NXTRG , Q , B , P ) ; HINT : begin GENRX ( XLH , NXTRG , Q , B , P ) ; DTYPE := INT end (* tag/ca *) ; end (* case *) ; VPA := RGS ; RGADR := NXTRG ; end (* then *) ; P := FPA . LVL ; Q := FPA . DSPLMT ; FPA := ZEROBL ; if Q <> 0 then if P > 0 then begin BASE ( Q , P , B ) ; if P <= 0 then P := B else if B > 0 then GENRR ( XAR , P , B ) ; if Q = 0 then GENRR ( XAR , RGADR , P ) else GENLA_LR ( RGADR , Q , P , RGADR ) ; end (* then *) else if Q = - 1 then GENRR ( XBCTR , RGADR , 0 ) else GENRXLIT ( XA , RGADR , Q , 0 ) ; end (* tag/ca *) ; REEL : if VPA = MEM then begin FINDFP ; P := MEMADR . LVL ; Q := MEMADR . DSPLMT ; BASE ( Q , P , B ) ; GENRX ( XLD , NXTRG , Q , B , P ) ; VPA := RGS ; RGADR := NXTRG ; end (* then *) ; PSET : if VPA <> RGS then begin if VPA = MEM then begin P := MEMADR . LVL ; Q := MEMADR . DSPLMT end (* then *) else begin P := CURLVL ; Q := STKADR end (* else *) ; BASE ( Q , P , B ) ; if PLEN <= 8 then if PLEN > 4 then begin FINDRP ; if B > 0 then if P > 0 then GENRR ( XAR , P , B ) else P := B ; GENRS ( XLM , NXTRG , NXTRG + 1 , Q , P ) ; end (* then *) else if PLEN > 0 then begin FINDRG ; GENRX ( XL , NXTRG , Q , P , B ) ; end (* then *) ; VPA := RGS ; RGADR := NXTRG ; end (* then *) ; end (* case *) else //****************************************************** // if not drct //****************************************************** begin GETADR ( STE , Q , P , B ) ; FPA := ZEROBL ; case DTYPE of ADR , HINT , INT : begin if VPA = RGS then AVAIL [ RGADR ] := TRUE ; FINDMDRG ; if DTYPE <> HINT then GENRX ( XL , NXTRG , Q , B , P ) else begin GENRX ( XLH , NXTRG , Q , B , P ) ; DTYPE := INT end (* else *) ; end (* tag/ca *) ; BOOL , CHRC : begin FINDMDRG ; if CLEAR_REG then GENRR ( XSR , NXTRG , NXTRG ) ; GENRX ( XIC , NXTRG , Q , B , P ) ; if VPA = RGS then AVAIL [ RGADR ] := TRUE ; end (* tag/ca *) ; REEL : begin FINDFP ; GENRX ( XLD , NXTRG , Q , B , P ) ; if VPA = RGS then AVAIL [ RGADR ] := TRUE ; end (* tag/ca *) ; PSET : begin if VPA = RGS then AVAIL [ RGADR ] := TRUE ; if PLEN <= 8 then if PLEN > 4 then begin FINDRP ; if B > 0 then if P > 0 then GENRR ( XAR , P , B ) else P := B ; GENRS ( XLM , NXTRG , NXTRG + 1 , Q , P ) ; end (* then *) else if PLEN > 0 then begin FINDRG ; GENRX ( XL , NXTRG , Q , P , B ) ; end (* then *) ; end (* tag/ca *) end (* case *) ; VPA := RGS ; RGADR := NXTRG ; DRCT := TRUE ; end (* else *) else //****************************************************** // IF NOT VRBL, I.E. LOAD CONSTANT //****************************************************** begin case DTYPE of ADR : begin P := FPA . LVL ; Q := FPA . DSPLMT ; FINDRG ; if P > 0 then begin BASE ( Q , P , B ) ; GENLA_LR ( NXTRG , Q , B , P ) end (* then *) else if P < 0 then begin GENRX_2 ( XLA , NXTRG , 0 , 0 , 0 , 2 ) ; if P = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 1 - index = ' , SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ SCNSTNO ] . LNK := PCOUNTER - 1 ; end (* then *) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q ) ; end (* then *) else GENRXLIT ( XL , NXTRG , FPA . DSPLMT , 0 ) ; (***********) (*NIL VALUE*) (***********) FPA := ZEROBL ; end (* tag/ca *) ; HINT , INT , BOOL , CHRC : begin FINDMDRG ; if FPA . DSPLMT = 0 then GENRR ( XSR , NXTRG , NXTRG ) else GENRXLIT ( XL , NXTRG , FPA . DSPLMT , 0 ) ; FPA := ZEROBL ; end (* tag/ca *) ; REEL : begin FINDFP ; GENRXDLIT ( XLD , NXTRG , RCNST ) end (* tag/ca *) ; PSET : if PLEN <= 8 then if PLEN > 4 then begin FINDRP ; GENRSLIT ( XLM , NXTRG , NXTRG + 1 , PCNST -> . S [ 1 ] ) ; end (* then *) else if PLEN > 0 then begin FINDRG ; I_S_R . S := PCNST -> . S [ 1 ] ; GENRXLIT ( XL , NXTRG , I_S_R . I1 , 0 ) ; end (* then *) else //****************************************************** // PLEN = 0 //****************************************************** begin FINDRG ; PLEN := 4 ; GENRR ( XSR , NXTRG , NXTRG ) ; end (* else *) ; end (* case *) ; VRBL := TRUE ; VPA := RGS ; RGADR := NXTRG ; DRCT := TRUE ; end (* else *) ; if MDTAG = PMPI then begin if not ODD ( RGADR ) or not AVAIL [ RGADR - 1 ] then begin AVAIL [ RGADR ] := TRUE ; FINDRP ; GENRR ( XLR , NXTRG + 1 , RGADR ) ; RGADR := NXTRG + 1 ; end (* then *) ; RGADR := RGADR - 1 ; AVAIL [ RGADR ] := FALSE end (* then *) else if MDTAG = PDVI then begin if ODD ( RGADR ) or not AVAIL [ RGADR + 1 ] then begin AVAIL [ RGADR ] := TRUE ; FINDRP ; GENRR ( XLR , NXTRG , RGADR ) ; RGADR := NXTRG ; end (* then *) ; AVAIL [ RGADR + 1 ] := FALSE ; GENRS ( XSRDA , RGADR , 0 , 32 , 0 ) ; end (* then *) end (* with *) ; end (* LOAD *) ; procedure GETADR ; (***************************************************) (* IF PASSED THE ADR. OF AN ITEM, *) (* THIS ROUTINE RETURNS A <Q,B,P> ADR. *) (* INDIRECTIONS ARE NOT DEREFERENCED HERE. *) (* ----------------------------------------------- *) (***************************************************) var R : RGRNG ; begin (* GETADR *) R := 0 ; with STE do begin if DRCT and not ( DTYPE in [ ADR ] ) then ERROR ( 602 ) ; if VRBL then if VPA = RGS then R := RGADR else (***************************) (*VPA = MEM OR VPA = ONSTK *) (***************************) begin if VPA = MEM then begin P := MEMADR . LVL ; Q := MEMADR . DSPLMT end (* then *) else ERROR ( 616 ) ; BASE ( Q , P , B ) ; GENRX ( XL , TXRG , Q , B , P ) ; R := TXRG end (* else *) ; (************************************************************) (* NOW THE VARIABLE PORTION OF THE ADR., IF ANY, IS IN TXRG *) (************************************************************) Q := FPA . DSPLMT ; P := FPA . LVL ; if R > 0 then begin if ( Q < 0 ) or ( Q > SHRTINT ) then begin GENRXLIT ( XA , R , Q , 0 ) ; Q := 0 end (* then *) ; B := 0 ; if P = CURLVL then B := LBR else if P = 1 then B := GBR else if P > 0 then GENRX ( XA , R , DISPLAY + 4 * P , GBR , 0 ) ; P := R ; end (* then *) else (*******************) (* NO INDEX OR VPA *) (*******************) BASE ( Q , P , B ) ; end (* with *) end (* GETADR *) ; function CHECK_ZERO_REG ( var STE : DATUM ; Q : ADRRNG ; P , B : RGRNG ) : BOOLEAN ; var R : RGRNG ; begin (* CHECK_ZERO_REG *) CHECK_ZERO_REG := FALSE ; return ; //****************************************************** // ist wahrscheinlich falsch ... //****************************************************** if ( P <> 0 ) and ( B <> 0 ) then begin CHECK_ZERO_REG := FALSE ; return end (* then *) ; if P <> 0 then R := B else R := P ; STE . VPA := MEM ; STE . MEMADR . LVL := R ; STE . MEMADR . DSPLMT := Q ; STE . RGADR := 0 ; STE . VRBL := TRUE ; CHECK_ZERO_REG := TRUE ; end (* CHECK_ZERO_REG *) ; procedure GETADR2 ( STE : DATUM ; var Q : ADRRNG ; var P , B : RGRNG ) ; (***************************************************) (* IF PASSED THE ADR. OF AN ITEM, *) (* THIS ROUTINE RETURNS A <Q,B,P> ADR. *) (* INDIRECTIONS ARE NOT DEREFERENCED HERE. *) (* ----------------------------------------------- *) (***************************************************) var R : RGRNG ; begin (* GETADR2 *) R := 0 ; with STE do begin if DRCT and not ( DTYPE in [ ADR , CHRC , CARR , VARC ] ) then begin ERROR ( 602 ) ; if FALSE then WRITELN ( TRACEF , 'error 602 inside getadr2: dtype = ' , DTYPE ) ; end (* then *) ; if VRBL then if VPA = RGS then R := RGADR else (****************************) (* VPA = MEM OR VPA = ONSTK *) (****************************) begin if VPA = MEM then begin P := MEMADR . LVL ; Q := MEMADR . DSPLMT end (* then *) else ERROR ( 616 ) ; BASE ( Q , P , B ) ; if FALSE then begin WRITELN ( TRACEF , 'GETADR2 - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'base/vrbl: q = ' , Q ) ; WRITELN ( TRACEF , 'base/vrbl: p = ' , P ) ; WRITELN ( TRACEF , 'base/vrbl: b = ' , B ) ; WRITELN ( TRACEF , 'now calling GENRX for L' ) ; end (* then *) ; GENRX ( XL , TXRG , Q , B , P ) ; R := TXRG end (* else *) ; (************************************************************) (* NOW THE VARIABLE PORTION OF THE ADR., IF ANY, IS IN TXRG *) (************************************************************) Q := FPA . DSPLMT ; P := FPA . LVL ; if R > 0 then begin if ( Q < 0 ) or ( Q > SHRTINT ) then begin GENRXLIT ( XA , R , Q , 0 ) ; Q := 0 end (* then *) ; B := 0 ; if P = CURLVL then B := LBR else if P = 1 then B := GBR else if P > 0 then begin if FALSE then WRITELN ( TRACEF , 'now calling GENRX for A' ) ; GENRX ( XA , R , DISPLAY + 4 * P , GBR , 0 ) ; end (* then *) ; P := R ; end (* then *) else (*******************) (* NO INDEX OR VPA *) (*******************) BASE ( Q , P , B ) ; end (* with *) ; if FALSE then begin WRITELN ( TRACEF , 'base inside getadr2: q = ' , Q ) ; WRITELN ( TRACEF , 'base inside getadr2: p = ' , P ) ; WRITELN ( TRACEF , 'base inside getadr2: b = ' , B ) end (* then *) ; end (* GETADR2 *) ; procedure GETOP_SIMPLE ( var STE : DATUM ; var Q1 : ADRRNG ; var P1 , B1 : RGRNG ; TXRG : RGRNG ; INIT_ON_CHAR : BOOLEAN ) ; //**************************************************************** // get operands when target register is already fixed // target register is txrg // for example for code generation of new p-codes mcp, mse etc.; // see procedures mcpoperation, mseoperation // init_on_char: if false, then there is no need to clear the // register before IC, because the garbage bits are shifted // out later anyway. //**************************************************************** begin (* GETOP_SIMPLE *) with STE do begin //****************************************************** // if reg, simple copy register // if mem, load register from storage // if mem and char type, use XR and IC // if mem and indirect, load address before // if neither, source was constant, use LA //****************************************************** case VPA of RGS : GENRR ( XLR , TXRG , RGADR ) ; MEM : begin if not DRCT then begin P1 := MEMADR . LVL ; Q1 := MEMADR . DSPLMT ; BASE ( Q1 , P1 , B1 ) ; GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; P1 := TXRG ; Q1 := 0 ; B1 := 0 ; end (* then *) else begin P1 := MEMADR . LVL ; Q1 := MEMADR . DSPLMT ; BASE ( Q1 , P1 , B1 ) end (* else *) ; case DTYPE of CHRC : begin if DRCT then begin if INIT_ON_CHAR then GENRR ( XXR , TXRG , TXRG ) ; GENRX ( XIC , TXRG , Q1 , B1 , P1 ) end (* then *) else begin GENRX ( XIC , TXRG , Q1 , B1 , P1 ) ; if INIT_ON_CHAR then begin GENRS ( XSLL , TXRG , 0 , 24 , 0 ) ; GENRS ( XSRL , TXRG , 0 , 24 , 0 ) ; end (* then *) end (* else *) end (* tag/ca *) ; HINT : GENRX ( XLH , TXRG , Q1 , B1 , P1 ) ; otherwise GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; end (* case *) ; end (* tag/ca *) ; NEITHER : if FPA . DSPLMT <> 0 then GENLA_LR ( TXRG , FPA . DSPLMT , 0 , 0 ) else GENRR ( XXR , TXRG , TXRG ) ; otherwise end (* case *) ; end (* with *) ; end (* GETOP_SIMPLE *) ; procedure GEN_MOVECHAR ( var Q1 : ADRRNG ; var B1 : RGRNG ; var STE : DATUM ) ; var P2 , B2 : LVLRNG ; Q2 : ADRRNG ; begin (* GEN_MOVECHAR *) with STE do begin case VPA of RGS : begin if not DRCT then begin GENRX ( XIC , RGADR , 0 , RGADR , 0 ) ; DRCT := TRUE end (* then *) ; GENRX ( XSTC , RGADR , Q1 , 0 , B1 ) ; end (* tag/ca *) ; MEM : begin P2 := MEMADR . LVL ; Q2 := MEMADR . DSPLMT ; BASE ( Q2 , P2 , B2 ) ; CONS_REGS ( B2 , P2 ) ; GENSS ( XMVC , 1 , Q1 , B1 , Q2 , B2 ) ; end (* tag/ca *) ; NEITHER : GENSI ( XMVI , Q1 , B1 , FPA . DSPLMT ) ; otherwise end (* case *) ; end (* with *) ; end (* GEN_MOVECHAR *) ; procedure GETOPERAND ( var STE : DATUM ; var Q1 : ADRRNG ; var P1 , B1 : RGRNG ) ; (***************************************************************) (* IF PASSED AN ITEM, THIS ROUTINE RETURNS *) (* ITS <Q,B,P> ADDRESS *) (* WARNING ON USAGE OF THIS PROCEDURE!!! *) (* *) (* IT IS UNSAFE TO CALL FINDRG (AND THEREFORE ALSO *) (* FINDRP, LOAD, ...) AFTER GETOPERAND AND BEFORE *) (* THE P1 REGISTER HAS BEEN USED *) (***************************************************************) begin (* GETOPERAND *) with STE do if VRBL then if DRCT then if FPA . DSPLMT <> 0 then LOAD ( STE ) else begin if VPA = MEM then begin Q1 := MEMADR . DSPLMT ; P1 := MEMADR . LVL ; BASE ( Q1 , P1 , B1 ) ; end (* then *) else if VPA = ONSTK then begin P1 := CURLVL ; Q1 := STKADR ; BASE ( Q1 , P1 , B1 ) ; end (* then *) (*************************************) (* THE VPA=REG CASE NOT HANDLED HERE *) (*************************************) end (* else *) else (***********) (*NOT DIRCT*) (***********) begin GETADR ( STE , Q1 , P1 , B1 ) ; if VPA = RGS then AVAIL [ RGADR ] := TRUE ; end (* else *) else (*************************************) (* VRBL MAY NOT HAVE ANY FUNCTION *) (* ANY MORE *) (*************************************) begin if DTYPE <> ADR then ERROR ( 602 ) ; Q1 := FPA . DSPLMT ; P1 := FPA . LVL ; BASE ( Q1 , P1 , B1 ) ; end (* else *) ; end (* GETOPERAND *) ; procedure GETQB ( var STE : DATUM ; var Q : ADRRNG ; var P : RGRNG ; L : INTEGER ) ; (*****************************************************) (* GETS BASE-DISPLACEMENT ADDRESS SUCH THAT THE *) (* DISPLACEMENT < 4096-L *) (*****************************************************) var B : RGRNG ; begin (* GETQB *) if L < 0 then L := 0 ; GETOPERAND ( STE , Q , P , B ) ; if B > 0 then if P > 0 then if Q >= ( 4096 - L ) then begin GENLA_LR ( TXRG , Q , P , B ) ; Q := 0 ; P := TXRG ; B := 0 ; end (* then *) else GENRR ( XAR , P , B ) else P := B ; if Q >= ( 4096 - L ) then begin GENLA_LR ( TXRG , Q , P , 0 ) ; P := TXRG ; Q := 0 ; end (* then *) ; end (* GETQB *) ; procedure STORE ( STP : STKPTR ; INDRCT : BOOLEAN ) ; (********************************************************) (* STORE THE STACK ELEMENT IN THE LOCATION DENOTED BY : *) (* IF INDRCT THEN 2_ND TOP STACK ELEMENT *) (* ELSE P_Q FIELDS OF THE CURRENT INSTRUCTION *) (* ---------------------------------------------------- *) (********************************************************) var B : RGRNG ; P1 : RGRNG ; begin (* STORE *) (*************************************) (* LOADS THE ELEMENT INTO A REGISTER *) (*************************************) CLEAR_REG := STK [ STP ] . DTYPE <> OPNDTYPE ; if ( OPNDTYPE > CHRC ) or STK [ STP ] . VRBL then LOAD ( STK [ STP ] ) ; CLEAR_REG := TRUE ; P1 := P ; if INDRCT then begin if not STK [ STP - 1 ] . DRCT then LOAD ( STK [ STP - 1 ] ) ; GETADR ( STK [ STP - 1 ] , Q , P1 , B ) ; FREEREG ( STK [ STP - 1 ] ) ; end (* then *) else BASE ( Q , P1 , B ) ; with STK [ STP ] do begin if VRBL then if ( not DRCT ) or ( VPA = MEM ) then if DTYPE <> OPNDTYPE then if ( DTYPE <> INT ) or ( OPNDTYPE <> HINT ) then ERROR ( 601 ) ; case OPNDTYPE of ADR , INT : begin GENRX ( XST , RGADR , Q , B , P1 ) ; AVAIL [ RGADR ] := TRUE end (* tag/ca *) ; HINT : begin GENRX ( XSTH , RGADR , Q , B , P1 ) ; AVAIL [ RGADR ] := TRUE end (* tag/ca *) ; BOOL , CHRC : if VRBL then begin AVAIL [ RGADR ] := TRUE ; GENRX ( XSTC , RGADR , Q , B , P1 ) ; end (* then *) else (**********************) (* STORING A CONSTANT *) (**********************) begin if ( FPA . DSPLMT < 0 ) or ( FPA . DSPLMT > 255 ) then begin ERROR ( 302 ) ; FPA . DSPLMT := 0 end (* then *) ; if B > 0 then if P1 > 0 then GENRR ( XAR , P1 , B ) else P1 := B ; GENSI ( XMVI , Q , P1 , FPA . DSPLMT ) ; end (* else *) ; REEL : begin GENRX ( XSTD , RGADR , Q , B , P1 ) ; AVAILFP [ RGADR ] := TRUE end (* tag/ca *) ; PSET : ERROR ( 616 ) ; end (* case *) end (* with *) end (* STORE *) ; procedure CALLSUB ; var K : INTEGER ; DSREG , P1 , B1 , FPR : RGRNG ; Q1 : ADRRNG ; PPCALL : BOOLEAN ; begin (* CALLSUB *) if ODD ( P ) then (**************************) (* SAVEFPRS FOR THIS CALL *) (**************************) begin P := P - 1 ; SAVEFPRS := TRUE ; FPR := 0 ; K := FPRSAREA ; repeat FPR := FPR + 2 ; K := K + REALSIZE ; if not AVAILFP [ FPR ] then GENRX ( XSTD , FPR , K , LBR , 0 ) ; until FPR >= FPCNT ; end (* then *) else SAVEFPRS := FALSE ; with CALL_MST_STACK [ CALL_DEPTH ] do if DISPSAV > 0 then (********************************) (* CALL ON PARAMETRIC PROCEDURE *) (********************************) begin FINDRG ; GENRR ( XLR , NXTRG , LBR ) ; DSREG := NXTRG ; if DISPSAV > 4095 then begin GENRXLIT ( XA , DSREG , DISPSAV , 0 ) ; DISPSAV := 0 end (* then *) ; GENSS ( XMVC , DISPAREA , DISPSAV , DSREG , DISPLAY , GBR ) ; PPCALL := TRUE ; Q1 := PFLEV DIV 10 ; P1 := PFLEV MOD 10 ; BASE ( Q1 , P1 , B1 ) ; if P1 <= 0 then P1 := B1 else if B1 > 0 then GENRR ( XAR , P1 , B1 ) ; GENSS ( XMVC , DISPAREA - 4 , DISPLAY + 4 , GBR , Q1 + 4 , P1 ) ; GENRX ( XL , TRG15 , Q1 , P1 , 0 ) ; (********************) (* LOAD PROC. ADDR. *) (********************) end (* then *) else PPCALL := FALSE ; if Q <= 4095 then GENLA_LR ( TRG1 , Q , LBR , 0 ) else begin GENRR ( XLR , TRG1 , LBR ) ; GENRXLIT ( XA , TRG1 , Q , 0 ) ; end (* else *) ; //****************************************************** // generate different call sequences depending on // external language; for fortran all parameters // are call by reference, so dummyint arguments are // created for every by-value parameter ... this has // been done elsewhere //****************************************************** case EXTLANG of 'F' : begin K := P * 2 ; //****************************************************** // K = LENGTH OF PARM LIST //****************************************************** if K > 0 then GENSI ( XMVI , K - 4 , TRG1 , 128 ) ; K := ALIGN ( K , REALSIZE ) ; GENRX ( XST , TRG13 , K + 4 , TRG1 , 0 ) ; //****************************************************** // S/A CHAINING // provide r13 as usable sa base addr //****************************************************** GENRR ( XLR , TRG14 , TRG13 ) ; GENLA_LR ( TRG13 , K , TRG1 , 0 ) ; GENRX ( XST , TRG13 , 8 , TRG14 , 0 ) ; end (* tag/ca *) ; 'A' : begin //****************************************************** // S/A CHAINING // provide r13 as usable sa base addr //****************************************************** GENRX ( XST , TRG1 , 8 , TRG13 , 0 ) ; GENRX ( XST , TRG13 , 4 , TRG1 , 0 ) ; GENRR ( XLR , TRG13 , TRG1 ) ; GENLA_LR ( TRG1 , 112 , TRG1 , 0 ) ; end (* tag/ca *) ; otherwise end (* case *) ; if not FLOW_TRACE then begin if not PPCALL then GENRXLAB ( XL , TRG15 , LBL2 , - 3 ) ; GENRR ( XBALR , TRG14 , TRG15 ) ; end (* then *) else (******************************) (* GENERATE SPECIAL CALL CODE *) (******************************) begin if PPCALL then begin if ODD ( PCOUNTER ) then GENRR ( XBCR , NOCND , 0 ) ; (*****************) (* ALIGN TO WORD *) (*****************) GENRELRX ( XST , TRG15 , 4 ) ; (**************) (* ST 15,*+8 *) (**************) GENRELRX ( XBC , ANYCND , 4 ) ; (**************) (* B *+8 *) (**************) CODE . I [ PCOUNTER DIV 2 ] := 0 ; PCOUNTER := NEXTPC ( 2 ) ; GENRX ( XBAL , TRG14 , TRACER , GBR , 0 ) ; CODE . H [ PCOUNTER ] := TO_HINT ( 2 * PCOUNTER - 8 ) ; (******************) (* DC AL2( *-8 ) *) (******************) end (* then *) else begin GENRX ( XBAL , TRG14 , TRACER , GBR , 0 ) ; UPD_PRCTBL ( PCOUNTER , LBL2 . NAM ) ; end (* else *) ; PCOUNTER := NEXTPC ( 1 ) ; end (* else *) ; if PPCALL then (*******************) (* RESTORE DISPLAY *) (*******************) begin GENSS ( XMVC , DISPAREA , DISPLAY , GBR , CALL_MST_STACK [ CALL_DEPTH ] . DISPSAV , DSREG ) ; AVAIL [ DSREG ] := TRUE ; end (* then *) ; CALL_DEPTH := CALL_DEPTH - 1 ; if FALSE then WRITELN ( TRACEF , 'call_depth -- ' , CALL_DEPTH , ' linecnt = ' , LINECNT : 1 ) ; //****************************************************** // on return: different call seq. depending on extlang //****************************************************** case EXTLANG of 'F' : begin GENRX ( XL , TRG13 , 4 , TRG13 , 0 ) ; end (* tag/ca *) ; 'A' : begin GENRR ( XLR , TRG1 , TRG13 ) ; GENRX ( XL , TRG13 , 4 , TRG13 , 0 ) ; end (* tag/ca *) ; otherwise end (* case *) ; if SAVEFPRS then begin FPR := 0 ; K := FPRSAREA ; repeat FPR := FPR + 2 ; K := K + REALSIZE ; if not AVAILFP [ FPR ] then GENRX ( XLD , FPR , K , LBR , 0 ) ; until FPR >= FPCNT ; end (* then *) ; CLEAR_REG := TRUE ; CSPACTIVE [ TRG15 ] := FALSE ; CSPACTIVE [ TRG1 ] := FALSE ; (***************) (* R1,R15 USED *) (***************) end (* CALLSUB *) ; procedure SAVE_FILEOPERAND ( STP : STKPTR ) ; //*************************************** // this procedure saves the fileoperand // in the structure LAST_FILE to avoid // register loads in some cases // (repeated I/O to the same file) //*************************************** var Q1 : ADRRNG ; P1 : RGRNG ; begin (* SAVE_FILEOPERAND *) with STK [ STP ] do begin if VRBL then begin Q1 := MEMADR . DSPLMT ; P1 := MEMADR . LVL end (* then *) else begin Q1 := FPA . DSPLMT ; P1 := FPA . LVL end (* else *) ; with LAST_FILE do begin LAST_FILEOPERAND . DSPLMT := Q1 ; LAST_FILEOPERAND . LVL := P1 ; LAST_FILE_IS_VAR := VRBL ; end (* with *) ; end (* with *) ; end (* SAVE_FILEOPERAND *) ; procedure LOADFCBADDRESS ( STP : STKPTR ) ; //***************************** // load FCB address if needed //***************************** var OPC : BYTE ; begin (* LOADFCBADDRESS *) //**************************************** // if the file register (register 9) // has not yet been loaded, then load it //**************************************** if not FILADR_LOADED then begin //********************************** // first save the file operand // then get displacement and level // from the saved structure //********************************** SAVE_FILEOPERAND ( STP ) ; if CSP in [ PRES , PREW , PGET , PPUT , PRLN , PWLN , PPAG , PSKP , PLIM , PRDB , PWRB , PRDH , PRDY , PEOL , PEOT , PEOF , PELN , PRDC , PWRC , PRDI , PWRI , PRDS , PRDV , PRFC , PRFS , PRFV , PWRS , PWRV , PRDR , PWRR , PWRP , PWRX , PFDF , PWRD , PWRE , PCLS ] then with STK [ STP ] do begin if VRBL then OPC := XL else OPC := XLA ; //***************************************** // get displacement and level // from the saved structure (saved above) //***************************************** Q1 := LAST_FILE . LAST_FILEOPERAND . DSPLMT ; P1 := LAST_FILE . LAST_FILEOPERAND . LVL ; BASE ( Q1 , P1 , B1 ) ; GENRX ( OPC , FILADR , Q1 , B1 , P1 ) ; FILADR_LOADED := TRUE ; AVAIL [ FILADR ] := FALSE ; CSPACTIVE [ FILADR ] := TRUE ; end (* with *) end (* then *) end (* LOADFCBADDRESS *) ; procedure GOTOCSP ; var LBL_WORK : PLABEL ; begin (* GOTOCSP *) /**********************************/ /* (RE)LOAD PROCADR, if necessary */ /**********************************/ if not CSPACTIVE [ TRG15 ] then begin LBL_WORK . NAM := '$PASCSP' ; LBL_WORK . LEN := 7 ; GENRXLAB ( XL , TRG15 , LBL_WORK , - 3 ) ; end (* then *) ; CSPACTIVE [ TRG15 ] := TRUE ; /*************************************************/ /* load new stackaddr, if necessary (if changed) */ /*************************************************/ if PROCOFFSET <> 0 then begin if ( PROCOFFSET_OLD <> PROCOFFSET ) or not CSPACTIVE [ CALLSTACKADR ] then begin if PROCOFFSET <= 4095 then begin GENLA_LR ( CALLSTACKADR , PROCOFFSET , 13 , 0 ) ; AVAIL [ CALLSTACKADR ] := FALSE ; CSPACTIVE [ CALLSTACKADR ] := TRUE ; end (* then *) else begin GENRR ( XLR , CALLSTACKADR , 13 ) ; GENRXLIT ( XA , CALLSTACKADR , PROCOFFSET , 0 ) ; AVAIL [ CALLSTACKADR ] := FALSE ; CSPACTIVE [ CALLSTACKADR ] := TRUE ; end (* else *) end (* then *) ; PROCOFFSET_OLD := PROCOFFSET ; end (* then *) ; /************************/ /* proc number in reg 1 */ /************************/ if not CSPACTIVE [ TRG1 ] then OLDCSP := PSIO ; if CSP <> OLDCSP then begin GENLA_LR ( TRG1 , ORD ( CSP ) * 4 , 0 , 0 ) ; OLDCSP := CSP ; CSPACTIVE [ TRG1 ] := TRUE ; end (* then *) ; /**************************************/ /* see if filaddress has to be loaded */ /**************************************/ LOADFCBADDRESS ( TOP - 1 ) ; /************************/ /* branch to subroutine */ /************************/ GENRR ( XBALR , TRG14 , TRG15 ) ; /**********************************/ /* save some values for next call */ /**********************************/ LAST_FILE . LAST_PC := PCOUNTER ; end (* GOTOCSP *) ; procedure CALLSTNDRD ; (********************************) (* TO CALL A STANDARD PROCEDURE *) (* ---------------------------- *) (********************************) var Q1 , LEN : ADRRNG ; P1 , B1 : RGRNG ; OPC : BYTE ; ITEST : INTEGER ; LBL_WORK : PLABEL ; FILEOK : BOOLEAN ; procedure FILESETUP ( PRMCNT : RGRNG ) ; //************************************************* // TO SET UP PARAMETERS FOR THE FILE I/O // AND CALL THE I/O ROUTINE // ------------------------------------------------ // registers must be freed so that the parameters // are passed in the registers 2, 3 and 4 //************************************************* // register 4 is only needed by a small number // of runtime functions like WRR, WRX etc. //************************************************* label 10 ; var I : RGRNG ; STP : STKPTR ; STP1 : STKPTR ; STP2 : STKPTR ; STP3 : STKPTR ; CPARM3 : INTEGER ; CPARM3_SET : BOOLEAN ; TOPSTART : STKPTR ; begin (* FILESETUP *) TOPSTART := TOP ; if FALSE then begin WRITELN ( TRACEF , 'filesetup - csp: ' , CSPTBL [ CSP ] ) ; DUMPSTK ( 1 , TOPSTART ) ; end (* then *) ; (********************************************) (* POINTING TO NEXT AVAILABLE STACK ELEMENT *) (********************************************) STP := TOP - PRMCNT + 1 ; STP1 := STP ; STP2 := STP + 1 ; STP3 := STP + 2 ; TOP := STP ; (*******************************) (* POTENTIAL REGISTER CONFLICT *) (*******************************) if PRMCNT >= 2 then begin with STK [ STP2 ] do if VRBL and ( VPA = RGS ) and ( RGADR = 2 ) then begin FINDRG ; GENRR ( XLR , NXTRG , 2 ) ; AVAIL [ NXTRG ] := FALSE ; AVAIL [ 2 ] := TRUE ; RGADR := NXTRG ; end (* then *) end (* then *) ; (*******************************) (* POTENTIAL REGISTER CONFLICT *) (*******************************) if PRMCNT = 3 then begin with STK [ STP3 ] do if ( PROCNAME [ 1 ] <> ' ' ) and ( RGADR in [ 2 , 3 ] ) then begin FINDRG ; if NXTRG = 3 then begin FINDRG ; AVAIL [ 3 ] := TRUE ; end (* then *) ; GENRR ( XLR , NXTRG , RGADR ) ; AVAIL [ NXTRG ] := FALSE ; AVAIL [ RGADR ] := TRUE ; RGADR := NXTRG ; end (* then *) end (* then *) ; if FALSE then begin WRITELN ( TRACEF , 'nach korrektur: ' , CSPTBL [ CSP ] ) ; DUMPSTK ( 1 , TOPSTART ) ; end (* then *) ; //************************************************ // stack abarbeiten //************************************************ CPARM3_SET := FALSE ; for I := 2 to PRMCNT + 1 do with STK [ STP ] do begin //************************************************ // trace stack content //************************************************ if FALSE then begin WRITELN ( TRACEF , 'dumpstk vor load bei csp ' , 'bei zeile ' , LINECNT ) ; DUMPSTK ( STP , STP ) ; end (* then *) ; //************************************************ // trace stack content //************************************************ if not VRBL then case I of 3 : begin CPARM3 := FPA . DSPLMT ; CPARM3_SET := TRUE ; end (* tag/ca *) ; 4 : begin if CPARM3_SET then if CPARM3 = FPA . DSPLMT then begin RGADR := 3 ; goto 10 end (* then *) ; end (* tag/ca *) ; otherwise begin end (* otherw *) end (* case *) ; LOAD ( STK [ STP ] ) ; 10 : if DTYPE <> REEL then begin (*******************) (* THE COMMON CASE *) (*******************) if RGADR <> I then if AVAIL [ I ] then begin GENRR ( XLR , I , RGADR ) ; if RGADR > I then AVAIL [ RGADR ] := TRUE ; AVAIL [ I ] := FALSE ; RGADR := I ; end (* then *) else begin ERROR ( 753 ) end (* else *) end (* then *) else (**************************) (* DTYPE = REEL, I.E. WRR *) (**************************) begin if RGADR <> I then if AVAILFP [ I ] then GENRR ( XLDR , I , RGADR ) else begin ERROR ( 754 ) end (* else *) ; AVAILFP [ RGADR ] := TRUE ; AVAIL [ I ] := FALSE ; RGADR := I ; (*****************************************) (* KLUDGE TO RELEASE THE FIX. REG. LATER *) (*****************************************) end (* else *) ; STP := STP + 1 ; end (* with *) ; GOTOCSP ; for I := 2 to PRMCNT + 1 do begin STP := STP - 1 ; AVAIL [ STK [ STP ] . RGADR ] := TRUE end (* for *) ; end (* FILESETUP *) ; begin (* CALLSTNDRD *) if FALSE then begin WRITELN ( 'start callstandard csp: ' , ORD ( CSP ) : 3 ) ; for ITEST := 2 to 4 do if not AVAIL [ ITEST ] then begin WRITELN ( 'register ' , ITEST : 3 , ' not available / line: ' , LASTLN : 6 ) ; end (* then *) end (* then *) ; TOP := TOP - 1 ; case CSP of PTRC : begin with STK [ TOP ] do begin LOAD ( STK [ TOP ] ) ; AVAILFP [ RGADR ] := TRUE ; if RGADR <> 2 then GENRR ( XLDR , 2 , RGADR ) end (* with *) ; GOTOCSP ; with STK [ TOP ] do begin VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := 2 ; AVAIL [ RGADR ] := FALSE ; FPA . LVL := - 1 ; DTYPE := INT end (* with *) ; TOP := TOP + 1 ; /***********************************/ /* r1 beim naechsten mal neu laden */ /***********************************/ CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; PRND : begin with STK [ TOP ] do begin LOAD ( STK [ TOP ] ) ; AVAILFP [ RGADR ] := TRUE ; if RGADR <> 2 then GENRR ( XLDR , 2 , RGADR ) end (* with *) ; GOTOCSP ; with STK [ TOP ] do begin VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := 2 ; AVAIL [ RGADR ] := FALSE ; FPA . LVL := - 1 ; DTYPE := INT end (* with *) ; TOP := TOP + 1 ; /***********************************/ /* r1 beim naechsten mal neu laden */ /***********************************/ CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; PFLR : begin with STK [ TOP ] do begin LOAD ( STK [ TOP ] ) ; AVAILFP [ RGADR ] := TRUE ; if RGADR <> 2 then GENRR ( XLDR , 2 , RGADR ) end (* with *) ; GOTOCSP ; with STK [ TOP ] do begin VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := 2 ; AVAILFP [ RGADR ] := FALSE ; FPA . LVL := - 1 ; DTYPE := REEL end (* with *) ; TOP := TOP + 1 ; /***********************************/ /* r1 beim naechsten mal neu laden */ /***********************************/ CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; PTIM : begin GOTOCSP ; TOP := TOP + 1 ; end (* tag/ca *) ; PDAT : begin GOTOCSP ; TOP := TOP + 1 ; end (* tag/ca *) ; PCLK : with STK [ TOP ] do begin LOAD ( STK [ TOP ] ) ; GENRR ( XLR , 0 , RGADR ) ; GOTOCSP ; GENRR ( XLR , RGADR , 0 ) ; TOP := TOP + 1 ; CSPACTIVE [ TRG1 ] := FALSE ; end (* with *) ; PMSG : begin LOAD ( STK [ TOP - 1 ] ) ; with STK [ TOP - 1 ] do begin if RGADR <> 2 then if AVAIL [ 2 ] then begin GENRR ( XLR , 2 , RGADR ) ; AVAIL [ RGADR ] := TRUE ; AVAIL [ 2 ] := FALSE ; RGADR := 2 ; end (* then *) else ERROR ( 755 ) ; (**************************************) (* ASSUMING THE CURRENT SIMPLE FORMAT *) (**************************************) end (* with *) ; LOAD ( STK [ TOP ] ) ; with STK [ TOP ] do begin if RGADR <> 3 then if AVAIL [ 3 ] then begin GENRR ( XLR , 3 , RGADR ) ; AVAIL [ RGADR ] := TRUE ; AVAIL [ 3 ] := FALSE ; RGADR := 3 ; end (* then *) else ERROR ( 756 ) ; end (* with *) ; GOTOCSP ; CSPACTIVE [ TRG1 ] := FALSE ; AVAIL [ 2 ] := TRUE ; AVAIL [ 3 ] := TRUE ; TOP := TOP - 1 ; end (* tag/ca *) ; PXIT , PTRA : with STK [ TOP ] do begin LOAD ( STK [ TOP ] ) ; AVAIL [ RGADR ] := TRUE ; if RGADR <> 2 then GENRR ( XLR , 2 , RGADR ) ; GOTOCSP ; end (* with *) ; PTRP : begin with STK [ TOP ] do if ( not DRCT ) or ( DTYPE <> ADR ) then ERROR ( 602 ) else begin GETOPERAND ( STK [ TOP ] , Q1 , P1 , B1 ) ; if VRBL then if VPA = MEM then GENRX ( XL , 1 , Q1 , B1 , P1 ) else begin GENRR ( XLR , 1 , RGADR ) ; AVAIL [ RGADR ] := TRUE end (* else *) else GENLA_LR ( 1 , Q1 , B1 , P1 ) ; end (* else *) ; TOP := TOP - 1 ; with STK [ TOP ] do if not DRCT then ERROR ( 602 ) else if not VRBL then GENRXLIT ( XL , 0 , FPA . DSPLMT , 0 ) else begin GETOPERAND ( STK [ TOP ] , Q1 , P1 , B1 ) ; if VPA = MEM then GENRX ( XL , 0 , Q1 , B1 , P1 ) else begin GENRR ( XLR , 0 , RGADR ) ; AVAIL [ RGADR ] := TRUE ; end (* else *) ; end (* else *) ; LBL_WORK . NAM := '$PASTRAP' ; LBL_WORK . LEN := 8 ; if not FLOW_TRACE then begin GENRXLAB ( XL , JREG , LBL_WORK , - 3 ) ; GENRR ( XBALR , RTREG , JREG ) ; end (* then *) else (*********************) (* SPECIAL CALL CODE *) (*********************) begin GENRX ( XBAL , TRG14 , TRACER , GBR , 0 ) ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'DC AL2(' , PRCTBL [ 0 ] . NAME , '-=V($PASTRAP))' ) ; LIST002_NEWLINE ; end (* then *) ; UPD_PRCTBL ( PCOUNTER , LBL_WORK . NAM ) ; PCOUNTER := NEXTPC ( 1 ) ; end (* else *) ; end (* tag/ca *) ; //*************************************** // start i/O and end i/O do nothing // but they are there to make sure that // the file registers are set properly // prior to the actual I/O //*************************************** PSIO : begin if not AVAIL [ FILADR ] then if FILECNT = 0 then ERROR ( 757 ) ; AVAIL [ FILADR ] := FALSE ; FILECNT := FILECNT + 1 ; if FALSE then begin WRITELN ( TRACEF , '---------------------------------------' ) ; WRITELN ( TRACEF , 'SIO at linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'last_file.last_pc = ' , LAST_FILE . LAST_PC ) ; WRITELN ( TRACEF , 'pcounter = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'last_fileoperand = ' , LAST_FILE . LAST_FILEOPERAND . LVL : 1 , '/' , LAST_FILE . LAST_FILEOPERAND . DSPLMT : 1 ) ; end (* then *) ; //*********************************************** // check if the file register from the last I/O // is still valid //*********************************************** with LAST_FILE do begin if LAST_PC = PCOUNTER then begin with STK [ TOP ] do if VRBL then FILEOK := LAST_FILE_IS_VAR and ( LAST_FILEOPERAND = MEMADR ) else FILEOK := ( not LAST_FILE_IS_VAR ) and ( LAST_FILEOPERAND = FPA ) end (* then *) else FILEOK := FALSE ; CSPACTIVE [ FILADR ] := FILEOK end (* with *) ; //*********************************************** // if file register does not match, // FILADR_LOADED is false, of course // otherwise FILADR_LOADED retains its old value // that is, it may already contain the correct // old value //*********************************************** if not CSPACTIVE [ FILADR ] then FILADR_LOADED := FALSE ; if FALSE then begin WRITELN ( TRACEF , 'cspactive [9] = ' , CSPACTIVE [ FILADR ] ) ; WRITELN ( TRACEF , 'fileadr_loaded = ' , FILADR_LOADED ) ; end (* then *) ; CSPACTIVE [ TRG1 ] := FALSE ; TOP := TOP + 1 ; (*********************************************) (* TO CANCEL OUT PREVIOUS SUBTRACT OPERATION *) (*********************************************) end (* tag/ca *) ; PEIO : begin (*****************************) (* RELEASE FILE ADR REG ETC. *) (*****************************) FILECNT := FILECNT - 1 ; if FILECNT = 0 then AVAIL [ FILADR ] := TRUE ; if FALSE then begin WRITELN ( TRACEF , '---------------------------------------' ) ; WRITELN ( TRACEF , 'EIO at linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'last_file.last_pc = ' , LAST_FILE . LAST_PC ) ; WRITELN ( TRACEF , 'pcounter = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'last_fileoperand = ' , LAST_FILE . LAST_FILEOPERAND . LVL : 1 , '/' , LAST_FILE . LAST_FILEOPERAND . DSPLMT : 1 ) ; end (* then *) ; //***************************************** // the file register is invalid after EIO //***************************************** CSPACTIVE [ FILADR ] := FALSE ; FILADR_LOADED := FALSE ; CSPACTIVE [ TRG1 ] := FALSE ; LAST_FILE . LAST_PC := PCOUNTER ; (************************************************) (* TOP := TOP-1 IS DONE AT ENTRY TO CALLSTNDRD *) (************************************************) if FALSE then begin WRITELN ( TRACEF , 'cspactive [9] = ' , CSPACTIVE [ FILADR ] ) ; WRITELN ( TRACEF , 'fileadr_loaded = ' , FILADR_LOADED ) ; end (* then *) ; end (* tag/ca *) ; PELN , PEOF : begin LOADFCBADDRESS ( TOP ) ; FINDRG ; GENRX ( XL , NXTRG , 0 , FILADR , 0 ) ; with STK [ TOP ] do begin VRBL := TRUE ; DRCT := FALSE ; VPA := RGS ; RGADR := NXTRG ; FPA . LVL := - 1 ; if CSP = PEOF then FPA . DSPLMT := EOFDPLMT else FPA . DSPLMT := EOLDPLMT ; DTYPE := BOOL end (* with *) ; TOP := TOP + 2 ; (********************************) (*TO BE CORRECTED BY PENDING EIO*) (********************************) end (* tag/ca *) ; PEOL , PEOT : begin FILESETUP ( 0 ) ; FINDRG ; GENRX ( XL , NXTRG , 0 , FILADR , 0 ) ; with STK [ TOP - 1 ] do begin VRBL := TRUE ; DRCT := FALSE ; VPA := RGS ; RGADR := NXTRG ; FPA . LVL := - 1 ; if CSP = PEOL then FPA . DSPLMT := EOLDPLMT else FPA . DSPLMT := EOFDPLMT ; DTYPE := BOOL ; end (* with *) ; TOP := TOP + 1 ; end (* tag/ca *) ; PRDD : begin TOP := TOP - 2 ; CSP := PGET ; FILESETUP ( 0 ) ; GETADR ( STK [ TOP ] , Q1 , P1 , B1 ) ; if not STK [ TOP ] . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG end (* then *) ; FREEREG ( STK [ TOP ] ) ; LEN := STK [ TOP + 1 ] . FPA . DSPLMT ; if LEN <= 256 then begin if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; GENSS ( XMVC , LEN , Q1 , P1 , FILHDRSZ , FILADR ) ; end (* then *) else begin FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; GENRXLIT ( XL , NXTRG + 1 , LEN , 0 ) ; P1 := NXTRG ; FINDRP ; GENLA_LR ( NXTRG , FILHDRSZ , FILADR , 0 ) ; GENRR ( XLR , NXTRG + 1 , P1 + 1 ) ; GENRR ( XMVCL , P1 , NXTRG ) ; S370CNT := S370CNT + 1 ; AVAIL [ P1 ] := TRUE ; AVAIL [ NXTRG ] := TRUE ; AVAIL [ P1 + 1 ] := TRUE ; AVAIL [ NXTRG + 1 ] := TRUE ; end (* else *) end (* tag/ca *) ; PWRD , PWRE : begin LEN := STK [ TOP ] . FPA . DSPLMT ; LOADFCBADDRESS ( TOP - 2 ) ; with STK [ TOP - 1 ] do if CSP = PWRE then begin LOAD ( STK [ TOP - 1 ] ) ; if DTYPE = REEL then begin OPC := XSTD ; AVAILFP [ RGADR ] := TRUE end (* then *) else begin AVAIL [ RGADR ] := TRUE ; if LEN = 2 then OPC := XSTH else if LEN = 1 then OPC := XSTC else OPC := XST ; end (* else *) ; GENRX ( OPC , RGADR , FILHDRSZ , FILADR , 0 ) ; end (* then *) else begin (**************) (* CSP = PWRD *) (**************) GETADR ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; if not DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG end (* then *) ; FREEREG ( STK [ TOP - 1 ] ) ; if LEN <= 256 then begin if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; GENSS ( XMVC , LEN , FILHDRSZ , FILADR , Q1 , P1 ) ; end (* then *) else begin FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; GENRXLIT ( XL , NXTRG + 1 , LEN , 0 ) ; P1 := NXTRG ; FINDRP ; GENLA_LR ( NXTRG , FILHDRSZ , FILADR , 0 ) ; GENRR ( XLR , NXTRG + 1 , P1 + 1 ) ; GENRR ( XMVCL , NXTRG , P1 ) ; S370CNT := S370CNT + 1 ; AVAIL [ P1 ] := TRUE ; AVAIL [ P1 + 1 ] := TRUE ; AVAIL [ NXTRG ] := TRUE ; AVAIL [ NXTRG + 1 ] := TRUE ; end (* else *) ; end (* else *) ; TOP := TOP - 2 ; CSP := PPUT ; FILESETUP ( 0 ) ; end (* tag/ca *) ; PGET , PPUT , PRLN , PWLN , PRES , PREW , PPAG , PCLS : FILESETUP ( 0 ) ; PRDI , PRDR , PSKP , PLIM , PRDB , PRDH , PRDY : FILESETUP ( 1 ) ; PRDS , PWRC , PWRI , PWRB , PWRP , PFDF : FILESETUP ( 2 ) ; PWRS , PWRR , PWRX : begin FILESETUP ( 3 ) ; end (* tag/ca *) ; PWRV : FILESETUP ( 2 ) ; PRDV : FILESETUP ( 2 ) ; PRDC : FILESETUP ( 2 ) ; //************************************************** // RFC returns result at the place of the length // argument, so that the two elements of the stack // must not pe popped by the CSP RFC. // Compiler generates a STO C instruction after // the CSP RFC call. This is done to allow for // a CHK instruction after the READ of a char //************************************************** PRFC : begin FILESETUP ( 2 ) ; TOP := TOP + 2 ; end (* tag/ca *) ; PRFS , PRFV : FILESETUP ( 3 ) ; otherwise ERROR_SYMB ( 607 , P_OPCODE ) end (* case *) ; if FALSE then begin WRITELN ( 'ende callstandard csp: ' , ORD ( CSP ) : 3 ) ; for ITEST := 2 to 4 do if not AVAIL [ ITEST ] then begin WRITELN ( 'register ' , ITEST : 3 , ' not available / line: ' , LASTLN : 6 ) ; end (* then *) end (* then *) ; end (* CALLSTNDRD *) ; procedure CHKOPERATION ; var RTA : ADRRNG ; BPC : ICRNG ; begin (* CHKOPERATION *) case OPNDTYPE of //************************************************************ // check addresses - if they are nil //************************************************************ ADR : begin with STK [ TOP - 1 ] do if VRBL then begin if not AVAIL [ 2 ] then if not ( ( VPA = RGS ) and ( RGADR = 2 ) ) then begin J := 0 ; (***************) (* CLEAR GPR 2 *) (***************) for I := TOP - 2 DOWNTO 1 do with STK [ I ] do if VRBL then if ( not DRCT ) or ( DTYPE <> REEL ) then if ( VPA = RGS ) and ( RGADR = 2 ) then J := I ; if J = 0 then ERROR ( 758 ) else with STK [ J ] do begin FINDRG ; (******************************) (* TRADE GPR2 FOR ANOTHER ONE *) (******************************) GENRR ( XLR , NXTRG , 2 ) ; (********************) (* THIS FREES REG 2 *) (********************) RGADR := NXTRG ; end (* with *) ; end (* then *) ; AVAIL [ 2 ] := TRUE ; (***********) (* IN CASE *) (***********) LOAD ( STK [ TOP - 1 ] ) ; AVAIL [ 2 ] := FALSE ; if RGADR <> 2 then (**************************) (* VALUE IS IN WRONG REG. *) (**************************) begin AVAIL [ RGADR ] := TRUE ; GENRR ( XLR , 2 , RGADR ) ; RGADR := 2 end (* then *) ; RTA := PTRCHK ; if P < 0 then RTA := PTACHK ; GENRX ( XBAL , RTREG , RTA , GBR , 0 ) ; CSPACTIVE [ TRG15 ] := FALSE ; CSPACTIVE [ TRG1 ] := FALSE ; (********************) (* R1,R15 DESTROYED *) (********************) end (* then *) else (********************************************) (* ^ VAR, I.E. CHECK A CONSTANT EXPRESSION *) (********************************************) if ( FPA . DSPLMT < P ) or ( FPA . DSPLMT > Q ) then begin ERROR ( 302 ) ; WRITELN ( OUTPUT , '****' : 7 , FPA . DSPLMT : 9 , ' IS NOT IN THE RANGE:' , P : 9 , Q : 10 ) ; end (* then *) ; end (* tag/ca *) ; //************************************************************ // check integers or indexes for ranges //************************************************************ INT , INX : begin with STK [ TOP - 1 ] do if VRBL then begin if not DRCT then LOAD ( STK [ TOP - 1 ] ) ; FPA . DSPLMT := FPA . DSPLMT - P ; LOAD ( STK [ TOP - 1 ] ) ; (*******************************) (* later literal will be built *) (* with two margin values *) (*******************************) I_S_R . I1 := Q - P ; I_S_R . I2 := P ; (*********************************************) (* address of CL = first part of literal *) (*********************************************) GENRX_2 ( XCL , RGADR , 0 , 0 , 0 , 99 ) ; if ASM then begin WRITE ( LIST002 , '=A(' , Q - P : 1 , ',' , P : 1 , ')' ) ; LIST002_NEWLINE ; end (* then *) ; UPD_DBLTBL ( PCOUNTER - 1 , I_S_R . R ) ; (*********************************************) (* address of branch will be filled in later *) (*********************************************) GENRX ( XBC , LEQCND , 0 , 0 , 0 ) ; BPC := PCOUNTER ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'BNH @OK' ) ; LIST002_NEWLINE ; end (* then *) ; if RGADR <> 2 then GENRR ( XLR , 2 , RGADR ) ; if OPNDTYPE = PROC then RTA := PRMCHK else if OPNDTYPE = INX then RTA := INXCHK else RTA := RNGCHK ; GENRX ( XBAL , RTREG , RTA , GBR , 0 ) ; (*********************************************) (* subprogram needs both parts of literal *) (* for error message; put reg + displ *) (* after call *) (*********************************************) UPD_DBLTBL ( PCOUNTER , I_S_R . R ) ; if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , ' ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , '=A(' , Q - P : 1 , ',' , P : 1 , ')' ) ; LIST002_NEWLINE ; end (* then *) ; PCOUNTER := NEXTPC ( 1 ) ; FPA . DSPLMT := P ; CODE . H [ BPC - 1 ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER ) ) ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASML , '@OK DS 0H' ) ; LIST002_NEWLINE ; end (* then *) end (* then *) else (********************************************) (* ^ VAR, I.E. CHECK A CONSTANT EXPRESSION *) (********************************************) if ( FPA . DSPLMT < P ) or ( FPA . DSPLMT > Q ) then begin ERROR ( 302 ) ; WRITELN ( OUTPUT , '****' : 7 , FPA . DSPLMT : 9 , ' IS NOT IN THE RANGE:' , P : 9 , Q : 10 ) ; end (* then *) ; end (* tag/ca *) ; //************************************************************ // non means CHK E ... that is: generate runtime error //************************************************************ NON : begin LOAD ( STK [ TOP - 1 ] ) ; FREEREG ( STK [ TOP - 1 ] ) ; GENRR ( XLR , 1 , 2 ) ; GENRR ( 0 , 5 , 3 ) ; TOP := TOP - 1 ; end (* tag/ca *) ; otherwise ; end (* case *) ; end (* CHKOPERATION *) ; procedure FORCESTK ( var STE : DATUM ) ; (**************************************) (* FORCES A SET INTO RUN-STACK MEMORY *) (**************************************) var Q1 , Q2 : ADRRNG ; P1 , P2 , B1 , R : RGRNG ; begin (* FORCESTK *) with STE do if not ( DRCT and VRBL and ( VPA = ONSTK ) ) then if DRCT and VRBL and ( VPA = RGS ) then begin R := RGADR ; VPA := ONSTK ; if PLEN = 8 then begin GETQB ( STE , Q1 , P1 , 0 ) ; GENRS ( XSTM , R , R + 1 , Q1 , P1 ) ; AVAIL [ R + 1 ] := TRUE ; end (* then *) else (************) (* PLEN = 4 *) (************) begin GETOPERAND ( STE , Q1 , P1 , B1 ) ; GENRX ( XST , R , Q1 , P1 , B1 ) ; end (* else *) ; AVAIL [ R ] := TRUE ; end (* then *) else if DRCT and not VRBL then begin (*************************************) (* TRANSFER A CONSTANT ONTO RUNSTACK *) (*************************************) VPA := ONSTK ; VRBL := TRUE ; GETQB ( STE , Q1 , P1 , 0 ) ; GENSSLIT ( XMVC , PLEN , Q1 , P1 , PCNST -> ) ; end (* then *) else (******************************) (* SET IS SOMEWHERE IN MEMORY *) (******************************) begin GETQB ( STE , Q2 , P2 , 0 ) ; TXRG := TRG1 ; DRCT := TRUE ; VRBL := TRUE ; VPA := ONSTK ; GETQB ( STE , Q1 , P1 , 0 ) ; TXRG := TRG14 ; GENSS ( XMVC , PLEN , Q1 , P1 , Q2 , P2 ) ; end (* else *) ; CSPACTIVE [ TRG1 ] := FALSE ; (**************************) (* INDICATE LOSS OF REG 1 *) (**************************) end (* FORCESTK *) ; procedure BSETOPS ; (*************************) (* BINARY SET OPERATIONS *) (*************************) var L , R : DATUM ; Q1 , Q2 : ADRRNG ; P1 , P2 , B2 : RGRNG ; I , J , STKADRX : INTEGER ; MIN , LEN : PLNRNG ; LR : BOOLEAN ; RNG : array [ 1 .. 6 ] of ADRRNG ; procedure MINCONSTSET ; label 10 ; var I , J : INTEGER ; begin (* MINCONSTSET *) J := MXSETINX * 8 ; if L . PLEN > 0 then for I := MXSETINX DOWNTO 1 do begin I_S_R . S := L . PCNST -> . S [ I ] ; if I_S_R . I2 = 0 then J := J - 4 else goto 10 ; if I_S_R . I1 = 0 then J := J - 4 else goto 10 ; end (* for *) else J := 0 ; 10 : L . PLEN := J ; if J = 0 then L . PCNST := NIL ; end (* MINCONSTSET *) ; procedure COMPACT ( var S : LARGE_SET ; var LEN : PLNRNG ; var OFFSET : INTEGER ; TAG : CHAR ) ; var S_C : record case INTEGER of 1 : ( S : LARGE_SET ) ; 2 : ( C : array [ 1 .. MXPLNGTH ] of CHAR ) ; end ; I : PLNRNG ; begin (* COMPACT *) S_C . S := S ; while ( LEN > 0 ) and ( S_C . C [ LEN ] = TAG ) do LEN := LEN - 1 ; OFFSET := 0 ; while ( S_C . C [ OFFSET + 1 ] = TAG ) and ( OFFSET < LEN ) do OFFSET := OFFSET + 1 ; if OFFSET > 0 then begin LEN := LEN - OFFSET ; for I := 1 to LEN do S_C . C [ I ] := S_C . C [ I + OFFSET ] ; for I := LEN + 1 to MXPLNGTH do S_C . C [ I ] := TAG ; S := S_C . S ; end (* then *) ; end (* COMPACT *) ; procedure INN_OP ; label 10 ; var LN , TOO_MANY : BOOLEAN ; I , J , K : INTEGER ; L , R : DATUM ; begin (* INN_OP *) L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; if L . DTYPE <> INT then if L . DTYPE <> HINT then ERROR ( 601 ) ; if R . DTYPE <> PSET then ERROR ( 615 ) ; if not L . VRBL then if ( R . PLEN * 8 <= L . FPA . DSPLMT ) or ( L . FPA . DSPLMT < 0 ) then begin L . FPA . LVL := 0 ; L . FPA . DSPLMT := 0 ; end (* then *) else if not R . VRBL then begin (*******************************) (* BOTH OPERANDS ARE CONSTANTS *) (*******************************) I := L . FPA . DSPLMT MOD 64 ; J := L . FPA . DSPLMT DIV 64 ; L . FPA . DSPLMT := ORD ( I in R . PCNST -> . S [ J + 1 ] ) ; end (* then *) else if not ( R . DRCT and ( R . VPA = RGS ) ) then begin (********************************************) (* LEFT OPND IS CONST, RIGHT OPND IN MEMORY *) (********************************************) P1 := L . FPA . DSPLMT MOD 8 ; Q1 := L . FPA . DSPLMT DIV 8 ; GETQB ( R , Q2 , P2 , Q1 ) ; J := 1 ; for I := 6 DOWNTO P1 do J := J * 2 ; GENSI ( XTM , Q2 + Q1 , P2 , J ) ; BRCND := TRUCND ; L . VRBL := TRUE ; end (* then *) else begin (******************************************) (* LEFT OPND IS CONST, RIGHT OPND IN REGS *) (******************************************) if R . PLEN > 4 then GENRS ( XSLDL , R . RGADR , 0 , L . FPA . DSPLMT , 0 ) else GENRS ( XSLL , R . RGADR , 0 , L . FPA . DSPLMT , 0 ) ; GENRR ( XLTR , R . RGADR , R . RGADR ) ; BRCND := LESCND ; L . VRBL := TRUE ; end (* else *) else (**********) (* L.VRBL *) (**********) if R . PLEN <= 0 then begin FREEREG ( L ) ; L . VRBL := FALSE ; L . FPA . LVL := 0 ; L . FPA . DSPLMT := 0 ; end (* then *) else (**************) (* R.PLEN > 0 *) (**************) if not R . VRBL then begin (********************************) (* TRY FOR BETTER CODE SEQUENCE *) (********************************) if not L . DRCT then LOAD ( L ) ; K := R . PLEN * 8 ; J := 0 ; LN := TRUE ; TOO_MANY := FALSE ; for I := 0 to K do if ( ( I MOD 64 ) in R . PCNST -> . S [ I DIV 64 + 1 ] ) and ( I < K ) then if LN then begin J := J + 1 ; if J > 6 then begin J := 5 ; TOO_MANY := TRUE end (* then *) ; RNG [ J ] := I ; LN := FALSE ; end (* then *) else else if not LN then begin J := J + 1 ; RNG [ J ] := I - 1 ; LN := TRUE ; end (* then *) ; if J > 2 then if ( ( RNG [ J ] - RNG [ 1 ] ) <= 50 ) or TOO_MANY then begin COMPACT ( R . PCNST -> , R . PLEN , I , CHR ( 0 ) ) ; L . FPA . DSPLMT := L . FPA . DSPLMT - I * 8 ; goto 10 end (* then *) ; K := RNG [ 1 ] ; L . FPA . DSPLMT := L . FPA . DSPLMT - K ; LOAD ( L ) ; I := 1 ; while I < J do begin if RNG [ I ] > K then GENRXLIT ( XSH , L . RGADR , RNG [ I ] - K , - 1 ) ; GENRXLIT ( XCL , L . RGADR , RNG [ I + 1 ] - RNG [ I ] , 0 ) ; K := RNG [ I ] ; RNG [ I ] := PCOUNTER + 1 ; I := I + 2 ; if I < J then begin if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'BNH T' , TESTCNT + 1 : 1 ) ; LIST002_NEWLINE ; end (* then *) ; GENRX ( XBC , LEQCND , 0 , 0 , 0 ) end (* then *) ; end (* while *) ; if ASM then begin TESTCNT := TESTCNT + 1 ; WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASML , 'T' , TESTCNT : 1 , ' DS 0H' ) ; LIST002_NEWLINE ; end (* then *) ; begin K := BASE_DSPLMT ( PCOUNTER ) ; while I > 2 do begin I := I - 2 ; CODE . H [ RNG [ I ] ] := TO_HINT ( K ) ; end (* while *) ; end ; BRCND := LEQCND ; end (* then *) else 10 : begin (***************************************) (* R.VRBL OR UNOPTIMIZED CASE OF ABOVE *) (***************************************) LOAD ( L ) ; if R . PLEN <= 8 then begin (*********************************) (* OPERATE ON RIGHT OPND IN REGS *) (*********************************) LOAD ( R ) ; GENLA_LR ( 0 , R . PLEN * 8 , 0 , 0 ) ; GENRR ( XCLR , L . RGADR , 0 ) ; GENRELRX ( XBC , GEQCND , 5 ) ; (************) (* BNL *+10 *) (************) if R . PLEN > 4 then begin AVAIL [ R . RGADR + 1 ] := TRUE ; GENRS ( XSLDL , R . RGADR , 0 , 0 , L . RGADR ) ; end (* then *) else GENRS ( XSLL , R . RGADR , 0 , 0 , L . RGADR ) ; GENRR ( XLTR , R . RGADR , R . RGADR ) ; BRCND := LESCND ; end (* then *) else begin (***************************) (* RIGHT OPERAND IN MEMORY *) (***************************) if R . VRBL then GETQB ( R , Q2 , P2 , 0 ) else begin P2 := 0 ; Q2 := 0 end (* else *) ; GENRXLIT ( XCL , L . RGADR , R . PLEN * 8 - 1 , 0 ) ; if ASM then begin TESTCNT := TESTCNT + 1 ; WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'BH T' , TESTCNT : 1 ) ; LIST002_NEWLINE ; end (* then *) ; GENRELRX ( XBC , GRTCND , 12 ) ; (***********) (* BH *+24 *) (***********) GENLA_LR ( TRG1 , 7 , 0 , 0 ) ; GENRR ( XNR , TRG1 , L . RGADR ) ; GENRS ( XSRA , L . RGADR , 0 , 3 , 0 ) ; if R . VRBL then GENRX ( XIC , L . RGADR , Q2 , L . RGADR , P2 ) else begin if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , '<constant> ' ) ; PRINT_SET ( R . PCNST -> , R . PLEN ) ; end (* then *) ; GENRX_2 ( XIC , L . RGADR , Q2 , L . RGADR , P2 , 3 ) ; UPD_SETTBL ( PCOUNTER - 1 , R . PCNST -> , R . PLEN ) ; end (* else *) ; GENRS ( XSLL , L . RGADR , 0 , 24 , TRG1 ) ; GENRR ( XLTR , L . RGADR , L . RGADR ) ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASML , 'T' , TESTCNT : 1 , ' DS 0H' ) ; LIST002_NEWLINE ; end (* then *) ; BRCND := LESCND ; end (* else *) ; end ; (**********) (* L.VRBL *) (**********) FREEREG ( L ) ; FREEREG ( R ) ; L . DTYPE := BOOL ; STK [ TOP - 1 ] := L ; CSPACTIVE [ TRG1 ] := FALSE ; end (* INN_OP *) ; procedure ASE_OP ; var L , R : DATUM ; INSTR : INTEGER ; begin (* ASE_OP *) if FALSE then begin WRITE ( TRACEF , 'DUMPSTK vor ASE - ' ) ; WRITELN ( TRACEF , 'LINECNT = ' , LINECNT : 1 ) ; DUMPSTK ( TOP - 1 , TOP ) end (* then *) ; L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; if Q < 0 then (*********************************) (* OPERANDS ARE IN REVERSE ORDER *) (*********************************) begin L := STK [ TOP ] ; R := STK [ TOP - 1 ] ; Q := - Q end (* then *) ; if L . DTYPE <> PSET then ERROR ( 615 ) ; if R . DTYPE <> INT then if R . DTYPE <> HINT then ERROR ( 602 ) ; LOAD ( R ) ; if DEBUG then begin (**********************************) (* CHECK THAT ELEMENT IS IN RANGE *) (**********************************) GENRR ( XBALR , TRG14 , 0 ) ; GENLA_LR ( TRG1 , L . PLEN * 8 - 1 , 0 , 0 ) ; GENRR ( XCLR , R . RGADR , TRG1 ) ; GENRX ( XBC , GRTCND , SETCHK , GBR , 0 ) ; end (* then *) ; if L . PLEN <= 8 then begin (******************************) (* PRODUCE THE RESULT IN REGS *) (******************************) LOAD ( L ) ; GENLA_LR ( TRG1 , 1 , 0 , 0 ) ; GENRR ( XLCR , R . RGADR , R . RGADR ) ; if L . PLEN > 4 then begin GENRR ( XSR , TRG0 , TRG0 ) ; GENRS ( XSLDL , TRG0 , 0 , 63 , R . RGADR ) ; GENRR ( XORX , L . RGADR , TRG0 ) ; GENRR ( XORX , L . RGADR + 1 , TRG1 ) ; end (* then *) else begin GENRS ( XSLL , TRG1 , 0 , 31 , R . RGADR ) ; GENRR ( XORX , L . RGADR , TRG1 ) ; end (* else *) ; end (* then *) else begin (****************************) (* OPERATE ON SET IN MEMORY *) (****************************) FORCESTK ( L ) ; GETQB ( L , Q1 , P1 , 0 ) ; GENLA_LR ( TRG15 , 7 , 0 , 0 ) ; GENRR ( XNR , TRG15 , R . RGADR ) ; GENRS ( XSRL , R . RGADR , 0 , 3 , 0 ) ; GENLA_LR ( TRG1 , Q1 , P1 , R . RGADR ) ; GENLA_LR ( R . RGADR , 128 , 0 , 0 ) ; GENRS ( XSRL , R . RGADR , 0 , 0 , TRG15 ) ; INSTR := XOI * SL24 + TRG1 * SL12 ; GENRXLIT_EXTENDED ( XEX , R . RGADR , INSTR , 0 , XOI ) ; (*************) (* OI 0(1),0 *) (*************) CSPACTIVE [ TRG15 ] := FALSE ; (***************************) (* INDICATE LOSS OF REG 15 *) (***************************) end (* else *) ; AVAIL [ R . RGADR ] := TRUE ; STK [ TOP - 1 ] := L ; CSPACTIVE [ TRG1 ] := FALSE ; end (* ASE_OP *) ; procedure ASR_OP ; var S , R1 , R2 , RX : DATUM ; REVERSE : BOOLEAN ; INSTR : INTEGER ; begin (* ASR_OP *) if FALSE then begin WRITELN ( TRACEF , 'DUMPSTK vor ASR - p = ' , P : 1 , ' q = ' , Q : 1 ) ; WRITELN ( TRACEF , 'LINECNT = ' , LINECNT : 1 ) ; DUMPSTK ( TOP - 2 , TOP ) end (* then *) ; REVERSE := FALSE ; S := STK [ TOP - 2 ] ; R1 := STK [ TOP - 1 ] ; R2 := STK [ TOP ] ; if P < 0 then (*********************************) (* OPERANDS ARE IN REVERSE ORDER *) (*********************************) begin REVERSE := TRUE ; S := STK [ TOP ] ; R1 := STK [ TOP - 2 ] ; R2 := STK [ TOP - 1 ] ; P := - P end (* then *) ; if Q = 2 then begin RX := R1 ; R1 := R2 ; R2 := RX end (* then *) ; if S . DTYPE <> PSET then ERROR ( 615 ) ; if R1 . DTYPE <> INT then if R1 . DTYPE <> HINT then ERROR ( 602 ) ; if R2 . DTYPE <> INT then if R2 . DTYPE <> HINT then ERROR ( 602 ) ; LOAD ( R1 ) ; LOAD ( R2 ) ; if DEBUG then begin (**********************************) (* CHECK THAT ELEMENT IS IN RANGE *) (**********************************) GENRR ( XBALR , TRG14 , 0 ) ; GENLA_LR ( TRG1 , S . PLEN * 8 - 1 , 0 , 0 ) ; GENRR ( XCLR , R2 . RGADR , TRG1 ) ; GENRX ( XBC , GRTCND , SETCHK , GBR , 0 ) ; end (* then *) ; if S . PLEN <= 8 then begin (******************************) (* PRODUCE THE RESULT IN REGS *) (******************************) GENRR ( XCLR , R1 . RGADR , R2 . RGADR ) ; if S . PLEN > 4 then GENRELRX ( XBC , GRTCND , 17 ) else GENRELRX ( XBC , GRTCND , 16 ) ; LOAD ( S ) ; FINDRG ; GENRR ( XLR , NXTRG , R2 . RGADR ) ; GENRR ( XSR , NXTRG , R1 . RGADR ) ; GENLA_LR ( NXTRG , 1 , NXTRG , 0 ) ; GENRR ( XSR , TRG0 , TRG0 ) ; GENRR ( XBCTR , TRG0 , TRG0 ) ; GENRR ( XSR , TRG1 , TRG1 ) ; GENRR ( XBCTR , TRG1 , TRG0 ) ; GENRR ( XLCR , NXTRG , NXTRG ) ; GENRS ( XSLDL , TRG0 , 0 , 64 , NXTRG ) ; AVAIL [ NXTRG ] := TRUE ; GENRS ( XSRDL , TRG0 , 0 , 0 , R1 . RGADR ) ; if S . PLEN > 4 then begin GENRR ( XORX , S . RGADR , TRG0 ) ; GENRR ( XORX , S . RGADR + 1 , TRG1 ) ; end (* then *) else begin GENRR ( XORX , S . RGADR , TRG0 ) ; end (* else *) ; end (* then *) else begin (****************************) (* OPERATE ON SET IN MEMORY *) (****************************) FORCESTK ( S ) ; GETQB ( S , Q1 , P1 , 0 ) ; GENRR ( XCLR , R1 . RGADR , R2 . RGADR ) ; GENRELRX ( XBC , GRTCND , 39 ) ; GENLA_LR ( TRG15 , 7 , 0 , 0 ) ; GENRR ( XNR , TRG15 , R1 . RGADR ) ; GENRELRX ( XBC , NEQCND , 19 ) ; FINDRG ; GENRR ( XLR , NXTRG , R2 . RGADR ) ; GENRR ( XSR , NXTRG , R1 . RGADR ) ; GENRXLIT ( XCH , NXTRG , 8 , - 1 ) ; GENRELRX ( XBC , LESCND , 13 ) ; GENRR ( XLR , NXTRG , R1 . RGADR ) ; GENRS ( XSRL , NXTRG , 0 , 3 , 0 ) ; GENLA_LR ( TRG1 , Q1 , P1 , NXTRG ) ; GENSI ( XMVI , 0 , TRG1 , 0xff ) ; GENLA_LR ( R1 . RGADR , 8 , R1 . RGADR , 0 ) ; GENRELRX ( XBC , ANYCND , - 23 ) ; GENRR ( XLR , NXTRG , R1 . RGADR ) ; GENRS ( XSRL , NXTRG , 0 , 3 , 0 ) ; GENLA_LR ( TRG1 , Q1 , P1 , NXTRG ) ; GENLA_LR ( NXTRG , 128 , 0 , 0 ) ; GENRS ( XSRL , NXTRG , 0 , 0 , TRG15 ) ; INSTR := XOI * SL24 + TRG1 * SL12 ; // OI 0(1),X'00' GENRXLIT_EXTENDED ( XEX , NXTRG , INSTR , 0 , XOI ) ; GENLA_LR ( R1 . RGADR , 1 , R1 . RGADR , 0 ) ; GENRELRX ( XBC , ANYCND , - 38 ) ; AVAIL [ NXTRG ] := TRUE ; CSPACTIVE [ TRG15 ] := FALSE ; (***************************) (* INDICATE LOSS OF REG 15 *) (***************************) end (* else *) ; AVAIL [ R1 . RGADR ] := TRUE ; AVAIL [ R2 . RGADR ] := TRUE ; TOP := TOP - 1 ; STK [ TOP - 1 ] := S ; CSPACTIVE [ TRG1 ] := FALSE ; end (* ASR_OP *) ; begin (* BSETOPS *) case OPCODE of /************************************************************/ /* UNI implementieren */ /************************************************************/ PUNI : begin L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; if L . DTYPE <> PSET then ERROR ( 615 ) ; if R . DTYPE <> PSET then ERROR ( 615 ) ; STKADRX := L . STKADR ; (****************************************) (* len = maximum length of the operands *) (* ok on union *) (****************************************) LEN := L . PLEN ; if LEN < R . PLEN then LEN := R . PLEN ; (********************************************) (* ONE time loop - using break to terminate *) (********************************************) repeat (******************************************************) (* the right operand is null *) (* nothing to do *) (******************************************************) if R . PLEN <= 0 then break ; (******************************************************) (* the left operand is null *) (* replace the left operand with the right operand *) (******************************************************) if L . PLEN <= 0 then begin if ( R . STKADR <> STKADRX ) and R . VRBL and R . DRCT and ( R . VPA = ONSTK ) then begin L . VRBL := TRUE ; L . DRCT := TRUE ; L . VPA := ONSTK ; GETQB ( L , Q1 , P1 , 0 ) ; TXRG := TRG1 ; GETQB ( R , Q2 , P2 , 0 ) ; TXRG := TRG14 ; GENSS ( XMVC , LEN , Q1 , P1 , Q2 , P2 ) ; end (* then *) else L := R ; break end (* then *) ; (******************************) (* BOTH OPERANDS ARE NOT NULL *) (******************************) if not L . VRBL and not R . VRBL then (**********************************************************) (* both operands are constants, operation at compile time *) (**********************************************************) begin for I := 1 to MXSETINX do L . PCNST -> . S [ I ] := L . PCNST -> . S [ I ] + R . PCNST -> . S [ I ] ; MINCONSTSET ; break ; end (* then *) ; (*****************************************) (* one of the operands is not a constant *) (*****************************************) if LEN <= 8 then (*******************************************) (* len <= 8 - generate result in registers *) (*******************************************) begin LR := TRUE ; if L . PLEN < R . PLEN then begin LOAD ( R ) ; LR := FALSE end (* then *) else if L . PLEN > R . PLEN then LOAD ( L ) else (*************************) (* EQUAL LENGTH OPERANDS *) (*************************) if not ( L . VRBL and L . DRCT and ( L . VPA = RGS ) ) then if R . VRBL and R . DRCT and ( R . VPA = RGS ) then LR := FALSE else LOAD ( L ) ; if not LR then (************************) (* INTERCHANGE OPERANDS *) (************************) begin L := R ; R := STK [ TOP - 1 ] end (* then *) ; if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then begin (******************************) (* BOTH OPERANDS IN REGISTERS *) (******************************) GENRR ( XORX , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE ; if R . PLEN > 4 then begin GENRR ( XORX , L . RGADR + 1 , R . RGADR + 1 ) ; AVAIL [ R . RGADR + 1 ] := TRUE end (* then *) end (* then *) else (*******************************************) (* LEFT OPND IN REGS, RIGHT OPND IN MEMORY *) (*******************************************) begin GETOPERAND ( R , Q2 , P2 , B2 ) ; GENRX ( XO , L . RGADR , Q2 , P2 , B2 ) ; if R . PLEN > 4 then begin CHECKDISP ( Q2 , P2 , B2 ) ; GENRX ( XO , L . RGADR + 1 , Q2 + 4 , P2 , B2 ) ; end (* then *) end (* else *) else (******************************************) (* LEFT OPND IN REGS, RIGHT OPND IS CONST *) (******************************************) begin I_S_R . S := R . PCNST -> . S [ 1 ] ; if I_S_R . I1 <> 0 then GENRXLIT ( XO , L . RGADR , I_S_R . I1 , 0 ) ; if R . PLEN > 4 then if I_S_R . I2 <> 0 then GENRXLIT ( XO , L . RGADR + 1 , I_S_R . I2 , 0 ) end (* else *) ; break ; end (* then *) ; (*****************************************) (* len > 8 - most complicated situation *) (*****************************************) FORCESTK ( L ) ; if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then begin GETQB ( L , Q1 , P1 , 4 ) ; GENRX ( XO , R . RGADR , Q1 , P1 , 0 ) ; AVAIL [ R . RGADR ] := TRUE ; if R . PLEN > 4 then begin GENRX ( XO , R . RGADR + 1 , Q1 + 4 , P1 , 0 ) ; GENRS ( XSTM , R . RGADR , R . RGADR + 1 , Q1 , P1 ) ; AVAIL [ R . RGADR + 1 ] := TRUE end (* then *) else GENRX ( XST , R . RGADR , Q1 , P1 , 0 ) end (* then *) else (***************************) (* BOTH OPERANDS IN MEMORY *) (***************************) begin MIN := L . PLEN ; if MIN > R . PLEN then MIN := R . PLEN ; GETQB ( L , Q1 , P1 , MIN ) ; TXRG := TRG1 ; GETQB ( R , Q2 , P2 , MIN ) ; TXRG := TRG14 ; GENSS ( XOC , MIN , Q1 , P1 , Q2 , P2 ) ; if R . PLEN > L . PLEN then GENSS ( XMVC , R . PLEN - L . PLEN , Q1 + MIN , P1 , Q2 + MIN , P2 ) end (* else *) else (*****************************************) (* LEFT OPND IN MEM, RIGHT OPND IS CONST *) (*****************************************) begin PSVAL := R . PCNST -> ; MIN := L . PLEN ; if MIN > R . PLEN then MIN := R . PLEN ; COMPACT ( R . PCNST -> , MIN , J , CHR ( 0 ) ) ; GETQB ( L , Q1 , P1 , MIN ) ; if MIN >= 0 then GENSSLIT ( XOC , MIN , Q1 + J , P1 , R . PCNST -> ) ; if LEN > L . PLEN then begin for I := 1 to LEN - L . PLEN do PSVAL . C [ I ] := PSVAL . C [ I + L . PLEN ] ; GENSSLIT ( XMVC , LEN - L . PLEN , Q1 + R . PLEN , P1 , PSVAL ) ; end (* then *) end (* else *) ; until TRUE ; (*********************************************) (* this is done in any case before returning *) (*********************************************) L . STKADR := STKADRX ; L . PLEN := LEN ; STK [ TOP - 1 ] := L ; CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; /************************************************************/ /* INT implementieren */ /************************************************************/ PINT : begin L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; if L . DTYPE <> PSET then ERROR ( 615 ) ; if R . DTYPE <> PSET then ERROR ( 615 ) ; STKADRX := L . STKADR ; (****************************************) (* len = minimum length of the operands *) (* ok on intersection *) (****************************************) LEN := L . PLEN ; if LEN > R . PLEN then LEN := R . PLEN ; (********************************************) (* ONE time loop - using break to terminate *) (********************************************) repeat (*****************************) (* ONE OR BOTH OPERANDS NULL *) (*****************************) if LEN <= 0 then begin if R . PLEN <= 0 then begin FREEREG ( L ) ; L := R end (* then *) else FREEREG ( R ) ; break ; end (* then *) ; (******************************) (* BOTH OPERANDS ARE NOT NULL *) (******************************) if not L . VRBL and not R . VRBL then (**********************************************************) (* both operands are constants, operation at compile time *) (**********************************************************) begin for I := 1 to MXSETINX do L . PCNST -> . S [ I ] := L . PCNST -> . S [ I ] * R . PCNST -> . S [ I ] ; MINCONSTSET ; break ; end (* then *) ; (*****************************************) (* one of the operands is not a constant *) (*****************************************) if LEN <= 8 then (*******************************************) (* len <= 8 - generate result in registers *) (*******************************************) begin LR := TRUE ; if L . PLEN > R . PLEN then begin LOAD ( R ) ; LR := FALSE end (* then *) else if L . PLEN < R . PLEN then LOAD ( L ) else (*************************) (* EQUAL LENGTH OPERANDS *) (*************************) if not ( L . VRBL and L . DRCT and ( L . VPA = RGS ) ) then if R . VRBL and R . DRCT and ( R . VPA = RGS ) then LR := FALSE else LOAD ( L ) ; if not LR then (************************) (* INTERCHANGE OPERANDS *) (************************) begin L := R ; R := STK [ TOP - 1 ] end (* then *) ; if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then begin (******************************) (* BOTH OPERANDS IN REGISTERS *) (******************************) GENRR ( XNR , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE ; if L . PLEN > 4 then GENRR ( XNR , L . RGADR + 1 , R . RGADR + 1 ) ; if R . PLEN > 4 then AVAIL [ R . RGADR + 1 ] := TRUE ; end (* then *) else (*******************************************) (* LEFT OPND IN REGS, RIGHT OPND IN MEMORY *) (*******************************************) begin GETOPERAND ( R , Q2 , P2 , B2 ) ; GENRX ( XN , L . RGADR , Q2 , P2 , B2 ) ; if L . PLEN > 4 then begin CHECKDISP ( Q2 , P2 , B2 ) ; GENRX ( XN , L . RGADR + 1 , Q2 + 4 , P2 , B2 ) end (* then *) end (* else *) else (******************************************) (* LEFT OPND IN REGS, RIGHT OPND IS CONST *) (******************************************) begin I_S_R . S := R . PCNST -> . S [ 1 ] ; if I_S_R . I1 <> - 1 then if I_S_R . I1 <> 0 then GENRXLIT ( XN , L . RGADR , I_S_R . I1 , 0 ) else GENRR ( XSR , L . RGADR , L . RGADR ) ; if LEN > 4 then GENRXLIT ( XN , L . RGADR + 1 , I_S_R . I2 , 0 ) else if L . PLEN > 4 then AVAIL [ L . RGADR + 1 ] := TRUE ; end (* else *) ; break ; end (* then *) ; (*****************************************) (* len > 8 - most complicated situation *) (*****************************************) FORCESTK ( L ) ; if R . VRBL then begin (***************************) (* BOTH OPERANDS IN MEMORY *) (***************************) GETQB ( L , Q1 , P1 , 0 ) ; TXRG := TRG1 ; GETQB ( R , Q2 , P2 , 0 ) ; TXRG := TRG14 ; GENSS ( XNC , LEN , Q1 , P1 , Q2 , P2 ) ; end (* then *) else begin (*****************************************) (* LEFT OPND IN MEM, RIGHT OPND IS CONST *) (*****************************************) COMPACT ( R . PCNST -> , LEN , J , CHR ( 255 ) ) ; GETQB ( L , Q1 , P1 , J ) ; LEN := ALIGN ( LEN , INTSIZE ) ; if LEN >= J then GENSSLIT ( XNC , LEN - J , Q1 + J , P1 , R . PCNST -> ) ; end (* else *) ; until TRUE ; (*********************************************) (* this is done in any case before returning *) (*********************************************) L . STKADR := STKADRX ; L . PLEN := LEN ; STK [ TOP - 1 ] := L ; CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; /************************************************************/ /* DIF implementieren */ /************************************************************/ PDIF : begin L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; if L . DTYPE <> PSET then ERROR ( 615 ) ; if R . DTYPE <> PSET then ERROR ( 615 ) ; (****************************************) (* len = maximum length of the operands *) (* ok on set difference *) (****************************************) LEN := L . PLEN ; if LEN < R . PLEN then LEN := R . PLEN ; (********************************************) (* ONE time loop - using break to terminate *) (********************************************) repeat (******************************************************) (* the right operand is null *) (* nothing to do *) (******************************************************) if R . PLEN <= 0 then break ; (******************************************************) (* the left operand is null *) (******************************************************) if L . PLEN <= 0 then begin FREEREG ( R ) ; break ; end (* then *) ; (******************************) (* BOTH OPERANDS ARE NOT NULL *) (******************************) if not L . VRBL and not R . VRBL then (**********************************************************) (* both operands are constants, operation at compile time *) (**********************************************************) begin if LEN > R . PLEN then for I := R . PLEN + 1 to LEN do R . PCNST -> . C [ I ] := CHR ( 0 ) ; for I := 1 to MXSETINX do L . PCNST -> . S [ I ] := L . PCNST -> . S [ I ] - R . PCNST -> . S [ I ] ; MINCONSTSET ; break ; end (* then *) ; (*****************************************) (* one of the operands is not a constant *) (*****************************************) if L . PLEN <= 8 then (*******************************************) (* len <= 8 - generate result in registers *) (*******************************************) begin LOAD ( L ) ; if R . VRBL then begin if not ( R . DRCT and ( R . VPA = RGS ) ) then begin (**************************) (* FORCE R INTO REGISTERS *) (**************************) if R . PLEN > L . PLEN then R . PLEN := L . PLEN ; LOAD ( R ) ; end (* then *) ; GENRR ( XORX , L . RGADR , R . RGADR ) ; GENRR ( XXR , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE ; if R . PLEN > 4 then begin if L . PLEN > 4 then begin GENRR ( XORX , L . RGADR + 1 , R . RGADR + 1 ) ; GENRR ( XXR , L . RGADR + 1 , R . RGADR + 1 ) ; end (* then *) ; AVAIL [ R . RGADR + 1 ] := TRUE ; end (* then *) end (* then *) else begin (*****************************************) (* LEFT OPND IN REGS, RIGHT OPND IS CNST *) (*****************************************) I_S_R . S := [ 0 .. 63 ] - R . PCNST -> . S [ 1 ] ; if I_S_R . I1 <> - 1 then if I_S_R . I1 <> 0 then GENRXLIT ( XN , L . RGADR , I_S_R . I1 , 0 ) else GENRR ( XSR , L . RGADR , L . RGADR ) ; if ( L . PLEN > 4 ) and ( R . PLEN > 4 ) then if I_S_R . I2 <> 0 then GENRXLIT ( XN , L . RGADR + 1 , I_S_R . I2 , 0 ) else begin L . PLEN := 4 ; AVAIL [ L . RGADR + 1 ] := TRUE end (* else *) ; end (* else *) ; break ; end (* then *) ; (*****************************************) (* len > 8 - most complicated situation *) (*****************************************) FORCESTK ( L ) ; if R . VRBL then begin (*****************************************) (* fraglich, ob das hier richtig ist *) (*****************************************) if not ( R . VRBL and R . DRCT and ( R . VPA = MEM ) ) then FORCESTK ( R ) ; GETQB ( L , Q1 , P1 , 0 ) ; TXRG := TRG1 ; GETQB ( R , Q2 , P2 , 0 ) ; TXRG := TRG14 ; GENSS ( XOC , LEN , Q1 , P1 , Q2 , P2 ) ; GENSS ( XXC , LEN , Q1 , P1 , Q2 , P2 ) ; end (* then *) else begin (***********************) (* RIGHT OPND IS CONST *) (***********************) if LEN > R . PLEN then for I := R . PLEN + 1 to LEN do R . PCNST -> . C [ I ] := CHR ( 0 ) ; for I := 1 to MXSETINX do begin R . PCNST -> . S [ I ] := [ 0 .. 63 ] - R . PCNST -> . S [ I ] ; end (* for *) ; COMPACT ( R . PCNST -> , LEN , J , CHR ( 255 ) ) ; GETQB ( L , Q1 , P1 , J ) ; if LEN > 0 then GENSSLIT ( XNC , LEN , Q1 + J , P1 , R . PCNST -> ) ; end (* else *) until TRUE ; STK [ TOP - 1 ] := L ; CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; /************************************************************/ /* INN implementieren */ /************************************************************/ PINN : INN_OP ; /************************************************************/ /* ASE implementieren */ /************************************************************/ PASE : ASE_OP ; /************************************************************/ /* ASR implementieren */ /************************************************************/ PASR : ASR_OP ; end (* case *) ; end (* BSETOPS *) ; procedure CSETOPS ; (************************************************) (* CONTROL AND MISCELLANEOUS OPERATIONS ON SETS *) (************************************************) var Q1 , Q2 : ADRRNG ; P1 , P2 , B1 : RGRNG ; L , R : DATUM ; K : INTEGER ; procedure FORCESET ( var STE : DATUM ; LEN : INTEGER ) ; (*********************************************) (* CONVERTS A SET ADDR INTO SET ON RUN STACK *) (*********************************************) begin (* FORCESET *) with STE do if DTYPE = ADR then begin if VRBL then begin LOAD ( STE ) ; DRCT := FALSE ; end (* then *) else begin MEMADR := FPA ; FPA := ZEROBL ; DRCT := TRUE ; VRBL := TRUE ; VPA := MEM ; end (* else *) ; DTYPE := PSET ; PLEN := LEN ; STKADR := 0 ; (*******************) (* TO BE SET LATER *) (*******************) end (* then *) else if DTYPE <> PSET then begin WRITELN ( TRACEF , 'dtype falsch = ' , DTYPE ) ; ERROR ( 615 ) ; end (* then *) end (* FORCESET *) ; begin (* CSETOPS *) case OPCODE of PSLD : with STK [ TOP - 1 ] do begin FORCESET ( STK [ TOP - 1 ] , P ) ; STKADR := Q ; end (* with *) ; PSCL : with STK [ TOP ] do begin DTYPE := PSET ; PLEN := P ; STKADR := Q ; VRBL := TRUE ; DRCT := TRUE ; FPA := ZEROBL ; if PLEN = 0 then begin (**************************************) (* THIS CASE NEVER OCCURS IN PRACTICE *) (**************************************) VRBL := FALSE ; VPA := NEITHER ; end (* then *) else if P <= 8 then begin (****************) (* CLEAR REG(S) *) (****************) VPA := RGS ; if P = 4 then FINDRG else FINDRP ; RGADR := NXTRG ; GENRR ( XSR , RGADR , RGADR ) ; if P > 4 then GENRR ( XSR , RGADR + 1 , RGADR + 1 ) ; end (* then *) else begin (*****************************) (* CLEAR MEMORY ON RUN-STACK *) (*****************************) VPA := ONSTK ; GETQB ( STK [ TOP ] , Q1 , P1 , 0 ) ; GENSS ( XXC , PLEN , Q1 , P1 , Q1 , P1 ) ; end (* else *) ; TOP := TOP + 1 ; end (* with *) ; PCRD : with STK [ TOP - 1 ] do begin if PLEN <= 4 then LOAD ( STK [ TOP - 1 ] ) else if not VRBL or ( DRCT and ( VPA = RGS ) ) then FORCESTK ( STK [ TOP - 1 ] ) ; (******************************************) (* OPERAND = SINGLE REG. OR A MEMORY AREA *) (******************************************) FINDRG ; (***********************) (* REGISTER FOR RESULT *) (***********************) GENRR ( XSR , NXTRG , NXTRG ) ; if PLEN > 4 then begin (******************) (* MEMORY OPERAND *) (******************) GETOPERAND ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; if P1 <> TRG14 then (*************************) (* WE NEED AN INDEX REG. *) (*************************) begin GENLA_LR ( TRG14 , Q1 , P1 , B1 ) ; P1 := TRG14 ; Q1 := 0 ; B1 := 0 ; end (* then *) ; GENLA_LR ( TRG1 , PLEN DIV 4 , 0 , 0 ) ; GENRX ( XL , 0 , Q1 , P1 , B1 ) ; P2 := 0 ; end (* then *) else P2 := RGADR ; GENRR ( XLTR , 15 , P2 ) ; GENRELRX ( XBC , EQUCND , 6 ) ; (***********) (* BZ *+12 *) (***********) GENRR ( XBCTR , P2 , 0 ) ; GENRR ( XNR , P2 , 15 ) ; GENRELRX ( XBCT , NXTRG , - 5 ) ; (******************) (* BCT NXTRG,*-10 *) (******************) if PLEN > 4 then begin GENLA_LR ( P1 , 4 , P1 , 0 ) ; GENRELRX ( XBCT , TRG1 , - 11 ) ; (***************) (* BCT R1,*-22 *) (***************) end (* then *) else AVAIL [ RGADR ] := TRUE ; GENRR ( XLPR , NXTRG , NXTRG ) ; DTYPE := BOOL ; DRCT := TRUE ; VRBL := TRUE ; VPA := RGS ; RGADR := NXTRG ; CSPACTIVE [ TRG15 ] := FALSE ; (***************************) (* INDICATE LOSS OF REG 15 *) (***************************) end (* with *) ; PSMV : begin if FALSE then begin WRITELN ( TRACEF , 'DUMPSTK vor SMV' ) ; DUMPSTK ( TOP - 2 , TOP - 1 ) end (* then *) ; TOP := TOP - 2 ; if P < 0 then (*********************) (* REVERSED OPERANDS *) (*********************) begin if FALSE then WRITELN ( TRACEF , 'psmv, p negativ' ) ; L := STK [ TOP + 1 ] ; R := STK [ TOP ] ; P := - P end (* then *) else begin L := STK [ TOP ] ; R := STK [ TOP + 1 ] end (* else *) ; if FALSE then begin WRITELN ( TRACEF , 'psmv, forceset rechts' ) ; WRITELN ( TRACEF , 'r.dtype = ' , R . DTYPE ) ; end (* then *) ; FORCESET ( R , Q ) ; if FALSE then begin WRITELN ( TRACEF , 'psmv, forceset links' ) ; WRITELN ( TRACEF , 'l.dtype = ' , L . DTYPE ) ; end (* then *) ; FORCESET ( L , P ) ; if FALSE then WRITELN ( TRACEF , 'psmv, ende forceset' ) ; (***************************************) (* L = DESTINATION SET, R = SOURCE SET *) (***************************************) if R . VRBL then begin if ( R . PLEN <= 8 ) and ( P = 4 ) and DEBUG then LOAD ( R ) ; if R . DRCT and ( R . VPA = RGS ) then if P < R . PLEN then (*****************) (* R.PLEN=8, P=4 *) (*****************) begin if DEBUG then begin GENRR ( XBALR , TRG14 , 0 ) ; GENRR ( XLTR , R . RGADR + 1 , R . RGADR + 1 ) ; GENRX ( XBC , NEQCND , SETCHK , GBR , 0 ) ; end (* then *) ; AVAIL [ R . RGADR + 1 ] := TRUE ; R . PLEN := P ; end (* then *) else (***********) (* NOTHING *) (***********) else (******************) (* R IS IN MEMORY *) (******************) begin TXRG := TRG1 ; K := 0 ; if P < R . PLEN then if DEBUG then K := P ; GETQB ( R , Q2 , P2 , K ) ; TXRG := TRG14 ; if P < R . PLEN then begin if DEBUG then begin GENRR ( XBALR , TRG14 , 0 ) ; GENSS ( XNC , R . PLEN - P , Q2 + P , P2 , Q2 + P , P2 ) ; GENRX ( XBC , NEQCND , SETCHK , GBR , 0 ) ; end (* then *) ; R . PLEN := P ; end (* then *) end (* else *) end (* then *) else (*******************) (* R IS A CONSTANT *) (*******************) if R . PLEN > P then begin ERROR ( 303 ) ; R . PLEN := P ; end (* then *) ; if P > R . PLEN then begin (*************************************) (* CLEAR EXCESS BYTES IN DESTINATION *) (*************************************) GETQB ( L , Q1 , P1 , R . PLEN ) ; GENSS ( XXC , P - R . PLEN , Q1 + R . PLEN , P1 , Q1 + R . PLEN , P1 ) ; end (* then *) else GETQB ( L , Q1 , P1 , 0 ) ; if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then if R . PLEN > 4 then GENRS ( XSTM , R . RGADR , R . RGADR + 1 , Q1 , P1 ) else (**************) (* R.PLEN = 4 *) (**************) GENRX ( XST , R . RGADR , Q1 , P1 , 0 ) else (******************) (* R IS IN MEMORY *) (******************) GENSS ( XMVC , R . PLEN , Q1 , P1 , Q2 , P2 ) else (***********************) (* R IS A CONSTANT SET *) (***********************) if R . PLEN > 0 then begin if FALSE then begin WRITELN ( TRACEF , '---------------------' '---------------------' ) ; WRITELN ( 'tracef: SMV' ) ; TRACE_SET ( R . PCNST -> , R . PLEN ) ; end (* then *) ; GENSSLIT ( XMVC , R . PLEN , Q1 , P1 , R . PCNST -> ) ; end (* then *) ; FREEREG ( L ) ; FREEREG ( R ) ; end (* tag/ca *) ; end (* case *) ; CSPACTIVE [ TRG1 ] := FALSE ; (**************************) (* INDICATE LOSS OF REG 1 *) (**************************) end (* CSETOPS *) ; procedure GEN_STRING_ADRESSE ( var SDAT : DATUM ; LOAD_REG : BOOLEAN ; var OFFSET : ADRRNG ; var RGWORK : RGRNG ) ; var B : RGRNG ; P2 : RGRNG ; Q2 : ADRRNG ; begin (* GEN_STRING_ADRESSE *) OFFSET := 0 ; with SDAT do if VPA = RGS then begin RGWORK := RGADR ; //****************************************************** // offset muss ggf. drauf // bei statischen variablen //****************************************************** P2 := FPA . LVL ; Q2 := FPA . DSPLMT ; if Q2 <> 0 then if P2 > 0 then begin BASE ( Q2 , P2 , B ) ; if P2 <= 0 then P2 := B else if B > 0 then GENRR ( XAR , P2 , B ) ; if Q2 = 0 then GENRR ( XAR , RGWORK , P2 ) else GENLA_LR ( RGWORK , Q2 , P2 , RGWORK ) ; end (* then *) else if LOAD_REG then begin if Q2 = - 1 then GENRR ( XBCTR , RGWORK , 0 ) else GENRXLIT ( XA , RGWORK , Q2 , 0 ) ; end (* then *) else begin OFFSET := Q2 end (* else *) end (* then *) else begin P2 := FPA . LVL ; Q2 := FPA . DSPLMT ; BASE ( Q2 , P2 , B2 ) ; if P2 < 0 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 2 - index = ' , SCNSTNO : 1 , ' pc = ' , PCOUNTER + 1 : 1 ) ; LITTBL [ SCNSTNO ] . LNK := PCOUNTER + 1 ; P2 := 0 ; end (* then *) ; GENLA_LR ( 14 , Q2 , B2 , P2 ) ; RGWORK := 14 ; end (* else *) end (* GEN_STRING_ADRESSE *) ; procedure STRINGCOMPARE ( var LEFT , RIGHT : DATUM ) ; //**************************************************************** // implement string (varchar) comparisons // by calling the routine $PASSCMP // which is part of PASMONN (runtime) //**************************************************************** var LBL : PLABEL ; RGWORK : RGRNG ; LITVALUE : INTEGER ; DUMMY_OFFS : ADRRNG ; begin (* STRINGCOMPARE *) //****************************************************** // show stack elements before compare //****************************************************** if FALSE then begin WRITELN ( TRACEF , 'start stringcompare, linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Left ' , LEFT ) ; DUMPSTKELEM ( 'Right' , RIGHT ) ; end (* then *) ; //****************************************************** // load strcurr pointer - // stringcompare uses string workarea //****************************************************** GENRX ( XL , TRG1 , STRCURR , 12 , 0 ) ; with LEFT do begin //****************************************************** // if operand = single char // build char array of length one in scratch area // and call compare routine //****************************************************** if DTYPE = CHRC then begin GENSI ( XMVI , PIAKT -> . SCRATCHPOS , LBR , FPA . DSPLMT ) ; LITVALUE := 1 ; GENRXLIT ( XL , 14 , LITVALUE , 0 ) ; GENRX ( XST , 14 , 0 , TRG1 , 0 ) ; GENLA_LR ( 14 , PIAKT -> . SCRATCHPOS , LBR , 0 ) ; GENRX ( XST , 14 , 4 , TRG1 , 0 ) ; end (* then *) else begin if DTYPE = CARR then LITVALUE := PLEN else LITVALUE := - 1 ; //****************************************************** // store plen, if char array // or minus one, if varchar // or zero, if null string //****************************************************** if LITVALUE = 0 then begin GENRR ( XXR , 14 , 14 ) ; GENRX ( XST , 14 , 0 , TRG1 , 0 ) ; GENRX ( XST , 14 , 4 , TRG1 , 0 ) ; end (* then *) else begin GENRXLIT ( XL , 14 , LITVALUE , 0 ) ; GENRX ( XST , 14 , 0 , TRG1 , 0 ) ; //****************************************************** // store address of left operand // take care, if literal (carr constant) //****************************************************** GEN_STRING_ADRESSE ( LEFT , TRUE , DUMMY_OFFS , RGWORK ) ; GENRX ( XST , RGWORK , 4 , TRG1 , 0 ) ; end (* else *) end (* else *) end (* with *) ; //****************************************************** // do the same for the right operand // at offsets 8 and 12 from R1 //****************************************************** with RIGHT do begin if DTYPE = CHRC then begin GENSI ( XMVI , PIAKT -> . SCRATCHPOS , LBR , FPA . DSPLMT ) ; LITVALUE := 1 ; GENRXLIT ( XL , 14 , LITVALUE , 0 ) ; GENRX ( XST , 14 , 8 , TRG1 , 0 ) ; GENLA_LR ( 14 , PIAKT -> . SCRATCHPOS , LBR , 0 ) ; GENRX ( XST , 14 , 12 , TRG1 , 0 ) ; end (* then *) else begin if DTYPE = CARR then LITVALUE := PLEN else LITVALUE := - 1 ; if LITVALUE = 0 then begin GENRR ( XXR , 14 , 14 ) ; GENRX ( XST , 14 , 8 , TRG1 , 0 ) ; GENRX ( XST , 14 , 12 , TRG1 , 0 ) ; end (* then *) else begin GENRXLIT ( XL , 14 , LITVALUE , 0 ) ; GENRX ( XST , 14 , 8 , TRG1 , 0 ) ; GEN_STRING_ADRESSE ( RIGHT , TRUE , DUMMY_OFFS , RGWORK ) ; GENRX ( XST , RGWORK , 12 , TRG1 , 0 ) ; end (* else *) end (* else *) end (* with *) ; //****************************************************** // free the registers possibly in use // in the left and right operands //****************************************************** FREEREG ( LEFT ) ; FREEREG ( RIGHT ) ; //****************************************************** // call the $PASSCMP routine (in PASMONN) //****************************************************** LBL . NAM := '$PASSCMP' ; LBL . LEN := 8 ; GENRXLAB ( XL , TRG15 , LBL , - 3 ) ; GENRR ( XBALR , 14 , 15 ) ; //****************************************************** // indicate loss of reg 1 and reg 15 //****************************************************** CSPACTIVE [ TRG15 ] := FALSE ; CSPACTIVE [ TRG1 ] := FALSE ; //****************************************************** // set the condition mask for the following branch // depending on the opcode which started the string // comparison //****************************************************** BRCND := BRMSK [ OPCODE ] ; end (* STRINGCOMPARE *) ; procedure SETCOMPARE ( var L , R : DATUM ) ; (*************************************) (* GENERATE CODE FOR SET COMPARISONS *) (*************************************) var Q1 , Q2 , FIXUPLOC : ADRRNG ; P1 , P2 : LVLRNG ; EQ , INTCHG , CONSTSET , TEST_PENDING : BOOLEAN ; I , MIN : INTEGER ; procedure TESTNULL ( var STE : DATUM ; var Q : ADRRNG ; var P : LVLRNG ; LEN : ADRRNG ) ; begin (* TESTNULL *) if LEN < STE . PLEN then begin GETQB ( STE , Q , P , LEN ) ; GENSS ( XNC , STE . PLEN - LEN , Q + LEN , P , Q + LEN , P ) ; TEST_PENDING := TRUE ; STE . PLEN := LEN ; end (* then *) else GETQB ( STE , Q , P , 0 ) ; end (* TESTNULL *) ; procedure GENBRANCH ; (****************************************) (* GENERATES INTERMEDIATE TEST BRANCHES *) (****************************************) begin (* GENBRANCH *) if TEST_PENDING then begin TESTCNT := TESTCNT + 1 ; (************************************************) (* IF ASM THEN *) (* BEGIN FIXUPLOC := 0; *) (* WRITELN(PRR,' BNZ T',TESTCNT:1); *) (* END *) (* ELSE *) (************************************************) if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'BNZ T' , TESTCNT : 1 ) ; LIST002_NEWLINE ; end (* then *) ; begin GENRX ( XBC , NEQCND , 0 , 0 , 0 ) ; FIXUPLOC := PCOUNTER - 1 ; end ; end (* then *) end (* GENBRANCH *) ; procedure SETCONSTBOOL ( B : BOOLEAN ) ; begin (* SETCONSTBOOL *) FREEREG ( L ) ; L . FPA . LVL := 0 ; L . FPA . DSPLMT := ORD ( B ) ; L . VRBL := FALSE ; L . DRCT := TRUE ; L . VPA := NEITHER ; CONSTSET := TRUE ; end (* SETCONSTBOOL *) ; begin (* SETCOMPARE *) CONSTSET := FALSE ; INTCHG := FALSE ; TEST_PENDING := FALSE ; FIXUPLOC := - 1 ; if ( OPCODE = PEQU ) or ( OPCODE = PNEQ ) then begin repeat if INTCHG then begin L := STK [ TOP ] ; R := STK [ TOP - 1 ] ; end (* then *) else begin L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; end (* else *) ; INTCHG := FALSE ; if L . PLEN <= 0 then (*********************) (* NULL LEFT OPERAND *) (*********************) if R . PLEN <= 0 then (**********************) (* NULL RIGHT OPERAND *) (**********************) SETCONSTBOOL ( OPCODE = PEQU ) else if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then if R . PLEN = 4 then GENRR ( XLTR , R . RGADR , R . RGADR ) else GENRR ( XORX , R . RGADR , R . RGADR + 1 ) else (******************) (* R IS IN MEMORY *) (******************) TESTNULL ( R , Q2 , P2 , 0 ) else (*****************) (* R IS CONSTANT *) (*****************) SETCONSTBOOL ( OPCODE <> PEQU ) else if L . VRBL then if L . DRCT and ( L . VPA = RGS ) then if R . PLEN <= 0 then INTCHG := TRUE else if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then begin GENRR ( XXR , L . RGADR , R . RGADR ) ; if L . PLEN < R . PLEN then GENRR ( XORX , L . RGADR , R . RGADR + 1 ) else if L . PLEN > 4 then begin if R . PLEN > 4 then GENRR ( XXR , L . RGADR + 1 , R . RGADR + 1 ) ; GENRR ( XORX , L . RGADR , L . RGADR + 1 ) ; end (* then *) ; end (* then *) else (******************) (* R IS IN MEMORY *) (******************) begin TESTNULL ( R , Q2 , P2 , L . PLEN ) ; GENBRANCH ; GENRX ( XX , L . RGADR , Q2 , P2 , 0 ) ; if L . PLEN > 4 then begin if R . PLEN >= 8 then GENRX ( XX , L . RGADR + 1 , Q2 + 4 , P2 , 0 ) ; GENRR ( XORX , L . RGADR , L . RGADR + 1 ) ; end (* then *) end (* else *) else (*****************) (* R IS CONSTANT *) (*****************) if R . PLEN > L . PLEN then SETCONSTBOOL ( OPCODE <> PEQU ) else begin I_S_R . S := R . PCNST -> . S [ 1 ] ; if I_S_R . I1 <> 0 then GENRXLIT ( XX , L . RGADR , I_S_R . I1 , 0 ) ; if L . PLEN > 4 then begin if R . PLEN >= 8 then GENRXLIT ( XX , L . RGADR + 1 , I_S_R . I2 , 0 ) ; GENRR ( XORX , L . RGADR , L . RGADR + 1 ) ; end (* then *) end (* else *) else (******************) (* L IS IN MEMORY *) (******************) if ( R . PLEN = 0 ) or ( R . VRBL and R . DRCT and ( R . VPA = RGS ) ) then INTCHG := TRUE else if R . VRBL then (******************) (* R IS IN MEMORY *) (******************) begin TESTNULL ( L , Q1 , P1 , R . PLEN ) ; TXRG := TRG1 ; TESTNULL ( R , Q2 , P2 , L . PLEN ) ; TXRG := TRG14 ; GENBRANCH ; MIN := L . PLEN ; if MIN > R . PLEN then MIN := R . PLEN ; GENSS ( XCLC , MIN , Q1 , P1 , Q2 , P2 ) ; end (* then *) else (*****************) (* R IS CONSTANT *) (*****************) if L . PLEN < R . PLEN then SETCONSTBOOL ( OPCODE <> PEQU ) else begin TESTNULL ( L , Q1 , P1 , R . PLEN ) ; GENBRANCH ; GENSSLIT ( XCLC , R . PLEN , Q1 , P1 , R . PCNST -> ) ; end (* else *) else (*****************) (* L IS CONSTANT *) (*****************) if ( R . PLEN = 0 ) or R . VRBL then INTCHG := TRUE else begin EQ := TRUE ; for I := 1 to MXSETINX do if L . PCNST -> . S [ I ] <> R . PCNST -> . S [ I ] then EQ := FALSE ; SETCONSTBOOL ( ( OPCODE = PEQU ) = EQ ) ; end (* else *) ; until not INTCHG ; end (* then *) else begin (******************************************************) (* pcode IS PGEQ OR PLEQ *) (******************************************************) if OPCODE = PGEQ then begin L := STK [ TOP ] ; R := STK [ TOP - 1 ] end (* then *) else begin L := STK [ TOP - 1 ] ; R := STK [ TOP ] end (* else *) ; OPCODE := PEQU ; if L . PLEN <= 4 then begin LOAD ( L ) ; if R . PLEN = 0 then GENRR ( XLTR , L . RGADR , L . RGADR ) else if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then begin GENRR ( XORX , L . RGADR , R . RGADR ) ; GENRR ( XXR , L . RGADR , R . RGADR ) ; end (* then *) else begin GETOPERAND ( R , Q1 , P1 , B1 ) ; GENRX ( XO , L . RGADR , Q1 , P1 , B1 ) ; GENRX ( XX , L . RGADR , Q1 , P1 , B1 ) ; end (* else *) else (*****************) (* R IS CONSTANT *) (*****************) begin I_S_R . S := R . PCNST -> . S [ 1 ] ; GENRXLIT ( XO , L . RGADR , I_S_R . I1 , 0 ) ; GENRXLIT ( XX , L . RGADR , I_S_R . I1 , 0 ) ; end (* else *) end (* then *) else begin FORCESTK ( L ) ; TESTNULL ( L , Q1 , P1 , R . PLEN ) ; if R . PLEN > 0 then begin GENBRANCH ; if R . VRBL then if R . DRCT and ( R . VPA = RGS ) then begin GENRX ( XN , R . RGADR , Q1 , P1 , 0 ) ; GENRX ( XX , R . RGADR , Q1 , P1 , 0 ) ; if R . PLEN > 4 then begin GENRX ( XN , R . RGADR + 1 , Q1 + 4 , P1 , 0 ) ; GENRX ( XX , R . RGADR + 1 , Q1 + 4 , P1 , 0 ) ; GENRR ( XORX , R . RGADR , R . RGADR + 1 ) ; end (* then *) end (* then *) else begin TXRG := TRG1 ; GETQB ( R , Q2 , P2 , 0 ) ; TXRG := TRG14 ; GENSS ( XOC , L . PLEN , Q1 , P1 , Q2 , P2 ) ; GENSS ( XXC , L . PLEN , Q1 , P1 , Q2 , P2 ) ; end (* else *) else begin (*****************) (* R IS CONSTANT *) (*****************) GENSSLIT ( XOC , L . PLEN , Q1 , P1 , R . PCNST -> ) ; (**************************************************************) (* IF ASM THEN *) (* GENSSLIT( XXC, L.PLEN, Q1, P1, R.PCNST@ ) *) (* ELSE *) (* *) (* *) (* da machen wir nix, weil das, was unten kommt, *) (* ja seine befehle ausgeben sollte ... *) (* *) (**************************************************************) begin (********************************) (*KLUDGE TO RE-USE SAME CONSTANT*) (********************************) GENSS ( XXC , L . PLEN , Q1 , P1 , 0 , 0 ) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( CODE . H [ PCOUNTER - 4 ] ) ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := PCOUNTER - 1 ; LITTBL [ NXTLIT ] . LTYPE := 'X' ; LITTBL [ NXTLIT ] . LENGTH := 0 ; LITTBL [ NXTLIT ] . XIDP := 0 ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'setcompare: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'setcompare: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'setcompare: lnk/pc = ' , PCOUNTER - 1 ) ; WRITELN ( TRACEF , 'setcompare: ltype = ' , 'X' ) ; WRITELN ( TRACEF , 'setcompare: length = ' , 0 ) ; WRITELN ( TRACEF , 'setcompare: xidp = ' , 0 ) ; WRITELN ( TRACEF , 'setcompare: opt = ' , FALSE ) ; end (* then *) ; end ; end (* else *) end (* then *) end (* else *) end (* else *) ; FREEREG ( L ) ; FREEREG ( R ) ; L . DTYPE := BOOL ; if not CONSTSET then BRCND := BRMSK [ OPCODE ] ; if FIXUPLOC >= 0 then begin if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASML , 'T' , TESTCNT : 1 , ' DS 0H' ) ; LIST002_NEWLINE ; end (* then *) ; CODE . H [ FIXUPLOC ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER ) ) ; end (* then *) ; CSPACTIVE [ TRG1 ] := FALSE ; (**************************) (* INDICATE LOSS OF REG 1 *) (**************************) TXR_CONTENTS . VALID := FALSE ; end (* SETCOMPARE *) ; procedure COPERATION ; (***********************************) (* CONTROL AND BRANCH INSTRUCTIONS *) (* ------------------------------- *) (***********************************) var PCNEU : ICRNG ; PC : ICRNG ; CASE_LAUF : INTEGER ; CL : LBLRNG ; X1 : INTEGER ; X2 : INTEGER ; LBL_WORK : PLABEL ; procedure MKLBL ( var LBL : PLABEL ; Q : LBLRNG ) ; (*********************************) (* ASSUMES 0 <= Q <= 9999999 *) (*********************************) var I : 1 .. 8 ; begin (* MKLBL *) I := FLDW ( Q ) + 1 ; LBL . NAM := 'L ' ; LBL . LEN := I ; repeat LBL . NAM [ I ] := CHR ( ( Q MOD 10 ) + ORD ( '0' ) ) ; Q := Q DIV 10 ; I := I - 1 ; until Q = 0 ; end (* MKLBL *) ; procedure ADDLNP ( PCDIF : BYTE ) ; (*******************************************************) (* TO ADD A (SOURCE) LINE POINTER TO THE POINTER TABLE *) (* --------------------------------------------------- *) (*******************************************************) begin (* ADDLNP *) if NXTLNP < MXLNP then begin CODE . C [ MXCODE * 2 + NXTLNP ] := CHR ( PCDIF ) ; NXTLNP := NXTLNP + 1 ; end (* then *) end (* ADDLNP *) ; procedure UPDLNTBL ( PCDIF : ICRNG ) ; (**************************************************************) (* TO UPDATE LINE POINTER TABLE FOR THE RUN TIME DEBUG OPTION *) (* ---------------------------------------------------------- *) (**************************************************************) begin (* UPDLNTBL *) if PCDIF >= 250 then (*********************) (* ENTER ESCAPE MODE *) (*********************) begin ADDLNP ( 254 ) ; (*************) (*ESCAPE CHAR*) (*************) ADDLNP ( PCDIF DIV 256 ) ; ADDLNP ( PCDIF MOD 256 ) ; end (* then *) else ADDLNP ( PCDIF ) ; end (* UPDLNTBL *) ; procedure INIT_CSECT ; (*************************************************) (* TO INITIALIZE OBJECT CODE TABLES AND POINTERS *) (* --------------------------------------------- *) (*************************************************) var I : LBLRNG ; BTARGET : INTEGER ; CSECT_NAME : ALFA ; LEN_CSECTINFO : INTEGER ; CODEPOS : INTEGER ; IXCODE : INTEGER ; begin (* INIT_CSECT *) CSECT_NAME := LBL1 . NAM ; for I := 0 to LBLCNT do with LBLTBL [ I ] do begin DEFINED := FALSE ; LNK := 1 end (* with *) ; NXTLIT := 0 ; LX . NXTDBL := 0 ; LX . NXTCH := 0 ; LX . IHCONF := - 1 ; LX . RICONF := - 1 ; LX . RHCONF := - 1 ; LX . INT_GAP := - 1 ; LX . HW_GAP := - 1 ; POOL_SIZE := 0 ; NUMLITS := 0 ; DBLALN := FALSE ; LAST_CC . LAST_PC := 0 ; TXR_CONTENTS . VALID := FALSE ; FILADR_LOADED := FALSE ; LAST_STR . LAST_PC := 0 ; LAST_MVC . LAST_PC := 0 ; LAST_FILE . LAST_PC := 0 ; PRCTBL [ 0 ] . NAME := LBL1 . NAM ; PRCTBL [ 0 ] . LNK := 0 ; PRCTBL [ 1 ] . LNK := 0 ; NXTPRC := 1 ; NXTEP := PRCCNT ; CALL_DEPTH := 0 ; PCOUNTER := 0 ; MINLBL := LBLMAP ( PIAKT -> . SEGSZE . NAM ) ; LASTPC := 0 ; (*************************************************) (* header for pasmain contains compile timestamp *) (*************************************************) if CURLVL = 1 then LEN_CSECTINFO := 9 + IDLNGTH + 1 + HDRLNGTH else LEN_CSECTINFO := 9 + IDLNGTH ; if ASM then begin if CURLVL = 1 then begin WRITE ( LIST002 , ' ' , 'BGN ' : 26 , CSECT_NAME , ',' , PIAKT -> . CURPNAME , ',' , PROGHDR : 1 ) ; LIST002_NEWLINE ; end (* then *) else begin WRITE ( LIST002 , ' ' , 'BGN ' : 26 , CSECT_NAME , ',' , PIAKT -> . CURPNAME ) ; LIST002_NEWLINE ; end (* else *) ; HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , CSECT_NAME , ' CSECT' ) ; LIST002_NEWLINE ; end (* then *) ; (************************************************) (* branch over constants *) (* including procedure names *) (************************************************) BTARGET := ( 24 + LEN_CSECTINFO ) DIV 2 ; BTARGET := ALIGN ( BTARGET , 2 ) ; GENRX ( XBC , ANYCND , BTARGET * 2 , 0 , JREG ) ; (************************************************) (* pcounter = position after ep constants *) (************************************************) PCOUNTER := BTARGET ; PCAFTLIT := PCOUNTER ; (************************************************) (* format ep constants area and insert them *) (************************************************) for I := 2 to PCOUNTER - 1 do CODE . H [ I ] := 0 ; IXCODE := 4 ; CODE . C [ IXCODE ] := CHR ( LEN_CSECTINFO ) ; for I := 1 to 8 do CODE . C [ IXCODE + I ] := CSECT_NAME [ I ] ; IXCODE := 13 ; CODE . C [ IXCODE ] := ' ' ; for I := 1 to IDLNGTH do CODE . C [ IXCODE + I ] := PIAKT -> . CURPNAME [ I ] ; if CURLVL = 1 then begin IXCODE := 14 + IDLNGTH ; CODE . C [ IXCODE ] := ' ' ; for I := 1 to HDRLNGTH do CODE . C [ IXCODE + I ] := PROGHDR [ I ] ; end (* then *) ; (*************************************************) (* more ep constants: *) (*-----------------------------------------------*) (* pcounter - 9: Compiler signature (6 bytes) *) (* pcounter - 6: Compiler version (2 bytes) *) (*-----------------------------------------------*) (* pcounter - 5: stacksize (set by gen_csect) *) (*-----------------------------------------------*) (* pcounter - 4: DEBUG-Level *) (*-----------------------------------------------*) (* pcounter - 3: proclen (set by gen_csect) *) (*-----------------------------------------------*) (* pcounter - 2: pointer to static csect *) (* set by v-constant, see below *) (*************************************************) CODE . H [ PCOUNTER - 9 ] := TO_HINT ( ORD ( 'S' ) * 256 + ORD ( 'T' ) ) ; CODE . H [ PCOUNTER - 8 ] := TO_HINT ( ORD ( 'P' ) * 256 + ORD ( 'A' ) ) ; CODE . H [ PCOUNTER - 7 ] := TO_HINT ( ORD ( 'S' ) * 256 + ORD ( 'C' ) ) ; CODE . H [ PCOUNTER - 6 ] := VERSION2 ; CODE . H [ PCOUNTER - 5 ] := 0 ; CODE . H [ PCOUNTER - 4 ] := PIAKT -> . DEBUG_LEV ; CODE . H [ PCOUNTER - 3 ] := 0 ; CODE . H [ PCOUNTER - 2 ] := 0 ; CODE . H [ PCOUNTER - 1 ] := 0 ; (*********************************************) (* ins_prctbl: statname wird als v-adresse *) (* registriert. wert = pcounter - 2. wirkt *) (* genauso wie die ablage eines literals, *) (* aber an dieser definierten stelle. *) (* spaetere bezugnamen auf das literal *) (* Statname (als v-adresse) via *) (* UPD_PRCTBL holen dann ihre adresse *) (* von hier. *) (*********************************************) if PIAKT -> . STATNAME [ 1 ] <> ' ' then INS_PRCTBL ( PIAKT -> . STATNAME , PCOUNTER - 2 ) ; (*********************************************) (* pos of proc len *) (*********************************************) POSOFPROCLEN := ( PCOUNTER - 3 ) * 2 ; (*********************************************) (* UNIQUE PROC NO *) (*********************************************) CODE . H [ MXCODE ] := PIAKT -> . CURPNO ; (************************************************) (* the procedure name which is written *) (* in case of debug is larger now (20 instead *) (* of 12), so nxtnlp has to be started at *) (* 24 instead of 16 - opp 2016 *) (************************************************) if PIAKT -> . DEBUG_LEV > 0 then begin CODE . H [ MXCODE + 1 ] := LASTLN ; CODEPOS := MXCODE * 2 + 3 ; for I := 1 to 8 do begin CODEPOS := CODEPOS + 1 ; CODE . C [ CODEPOS ] := PIAKT -> . SOURCENAME [ I ] ; end (* for *) ; NXTLNP := 12 ; end (* then *) else NXTLNP := 0 ; if ASM then begin HEXHW ( 4 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , 'AL1(' , LEN_CSECTINFO : 1 , ')' ) ; LIST002_NEWLINE ; HEXHW ( 5 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , 'C''' ) ; for I := 1 to 8 do WRITE ( LIST002 , CSECT_NAME [ I ] ) ; WRITE ( LIST002 , ' ' ) ; for I := 1 to IDLNGTH do WRITE ( LIST002 , PIAKT -> . CURPNAME [ I ] ) ; if CURLVL = 1 then begin WRITE ( LIST002 , ' ' ) ; for I := 1 to HDRLNGTH do WRITE ( LIST002 , PROGHDR [ I ] ) ; end (* then *) ; WRITE ( LIST002 , '''' ) ; LIST002_NEWLINE ; HEXHW ( POSOFPROCLEN - 12 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , 'CL6''STPASC''' ' -- Compiler signature' ) ; LIST002_NEWLINE ; HEXHW ( POSOFPROCLEN - 6 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , VERSION3 , ' -- Compiler version' ) ; LIST002_NEWLINE ; HEXHW ( POSOFPROCLEN - 4 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , 'AL2(0)' , ' -- Stacksize' ) ; LIST002_NEWLINE ; HEXHW ( POSOFPROCLEN - 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , 'AL2(' , PIAKT -> . DEBUG_LEV : 1 , ')' , ' -- Debug-Level' ) ; LIST002_NEWLINE ; HEXHW ( POSOFPROCLEN , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; WRITE ( LIST002 , 'AL2(0)' , ' -- Length of Proc' ) ; LIST002_NEWLINE ; HEXHW ( POSOFPROCLEN + 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , 'DC ' : COLASMI , ' ' : SPACEASMI ) ; if PIAKT -> . STATNAME [ 1 ] <> ' ' then begin WRITE ( LIST002 , 'V(' , PIAKT -> . STATNAME , ')' , ' -- Static CSECT' ) ; LIST002_NEWLINE ; end (* then *) else begin WRITE ( LIST002 , 'A(0)' , ' -- Static CSECT' ) ; LIST002_NEWLINE ; end (* else *) end (* then *) ; end (* INIT_CSECT *) ; procedure GEN_CSECT ( STACKSIZE : INTEGER ) ; (************************************************) (* TO MERGE LITERAL POOLS AND GENERATE *) (* ONE OBJECT MODULE FOR THIS PROC *) (* -------------------------------------------- *) (************************************************) const XESD = 46523076 ; (**********************) (*EBCDIC FOR 2|'ESD' *) (**********************) XTXT = 48490467 ; (**********************) (* TXT *) (**********************) XRLD = 47829956 ; (**********************) (* RLD *) (**********************) XEND = 46519748 ; (**********************) (* END *) (**********************) BLNK1 = 64 ; (**********************) (* EBCDIC FOR ' ' *) (**********************) BLNK2 = 16448 ; BLNK3 = 4210752 ; BLNK4 = 1077952576 ; var I , J , K : INTEGER ; TPC , QPC : INTEGER ; LNGTH : STRLRNG ; BLNK80 : array [ 1 .. 80 ] of CHAR ; BLNK64 : array [ 1 .. 64 ] of CHAR ; CODESIZE : INTEGER ; CARD : record case INTEGER of 1 : ( C : array [ 1 .. 80 ] of CHAR ) ; (*****************) (*CHAR CARD IMAGE*) (*****************) 2 : ( I : array [ 1 .. 20 ] of INTEGER ) ; (*****************) (*INT. CARD IMAGE*) (*****************) 3 : ( H : array [ 1 .. 40 ] of HINTEGER ) (*******************) (*HALFWORD IMAGE *) (*******************) end ; ESD_CARD : record case INTEGER of 1 : ( C16 : array [ 1 .. 16 ] of CHAR ; C64 : array [ 1 .. 64 ] of CHAR ) ; 2 : ( I4 : array [ 1 .. 4 ] of INTEGER ; ITEM : array [ 1 .. 3 ] of record XNAME : ALFA ; F1 , F2 : INTEGER end ) ; 3 : ( C80 : array [ 1 .. 80 ] of CHAR ) end ; procedure PRINT_CSECT ( LPC1 : ICRNG ) ; label 10 ; var LPC , CON1 , CON2 : HEX4 ; APC , APC1 : ICRNG ; I , K : 0 .. 9999 ; REST_ZEILZAHL : INTEGER ; DUMMYINT : INTEGER ; LIMIT : INTEGER ; begin (* PRINT_CSECT *) //******************************************************** // schreiben tables of offsets and statement numbers //******************************************************** REST_ZEILZAHL := LIST002_HEADLINE ( 'R' , ' ' , ' ' , ' ' ) ; if REST_ZEILZAHL <= 10 then begin DUMMYINT := LIST002_HEADLINE ( 'S' , ' ' , ' ' , ' ' ) ; end (* then *) else LIST002_NEWLINE ; WRITE ( LIST002 , ' TABLES OF OFFSETS AND STATEMENT NUMBERS FOR ' , PIAKT -> . CURPNAME , ' (' , PRCTBL [ 0 ] . NAME , ')' ) ; LIST002_NEWLINE ; LIST002_NEWLINE ; K := 1 ; while TRUE do begin LIMIT := TOS_COUNT ; if LIMIT - K + 1 > 12 then LIMIT := K + 11 ; WRITE ( LIST002 , ' STMT =' ) ; for I := K to LIMIT do WRITE ( LIST002 , ' ' , TOS [ I ] . STMT : 5 ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' OFFS =' ) ; for I := K to LIMIT do begin HEXHW ( TOS [ I ] . OFFS * 2 , HEXPC ) ; WRITE ( LIST002 , HEXPC : 6 ) ; end (* for *) ; LIST002_NEWLINE ; K := LIMIT + 1 ; if K > TOS_COUNT then break ; REST_ZEILZAHL := LIST002_HEADLINE ( 'R' , ' ' , ' ' , ' ' ) ; if REST_ZEILZAHL <= 4 then begin DUMMYINT := LIST002_HEADLINE ( 'S' , ' ' , ' ' , ' ' ) ; end (* then *) else LIST002_NEWLINE ; end (* while *) ; //****************************************** // schreiben object code in hex //****************************************** if ASM then begin REST_ZEILZAHL := LIST002_HEADLINE ( 'R' , ' ' , ' ' , ' ' ) ; if REST_ZEILZAHL <= 10 then begin DUMMYINT := LIST002_HEADLINE ( 'S' , ' ' , ' ' , ' ' ) ; end (* then *) else LIST002_NEWLINE ; WRITE ( LIST002 , ' OBJECT CODE FOR CSECT' , PRCTBL [ 0 ] . NAME : 9 , '(PROCEDURE ' : 13 , PIAKT -> . CURPNAME , ')' ) ; LIST002_NEWLINE ; APC := 0 ; APC1 := 0 ; repeat LIST002_NEWLINE ; HEXHW ( 2 * APC , LPC ) ; WRITE ( LIST002 , LPC : 5 , ':' ) ; for I := 0 to 7 do (*********************) (* 32 BYTES PER LINE *) (*********************) begin if I = 4 then WRITE ( LIST002 , ' ' ) ; HEXHW ( CODE . H [ APC1 ] , CON1 ) ; HEXHW ( CODE . H [ APC1 + 1 ] , CON2 ) ; WRITE ( LIST002 , ' ' , CON1 , CON2 ) ; APC := APC + 2 ; APC1 := APC1 + 2 ; if APC1 >= LPC1 then goto 10 end (* for *) ; until FALSE ; end (* then *) ; //****************************************** // schreiben external references usw. //****************************************** 10 : K := 0 ; if ( NXTPRC > 1 ) or ( NXTEP < PRCCNT ) then begin LIST002_NEWLINE ; REST_ZEILZAHL := LIST002_HEADLINE ( 'R' , ' ' , ' ' , ' ' ) ; if REST_ZEILZAHL <= 10 then begin DUMMYINT := LIST002_HEADLINE ( 'S' , ' ' , ' ' , ' ' ) ; end (* then *) else LIST002_NEWLINE ; WRITE ( LIST002 , ' EXTERNAL REFERENCES AND LABEL DEFINITIONS:' ) ; LIST002_NEWLINE ; for I := 0 to PRCCNT do if ( I < NXTPRC ) or ( I > NXTEP ) then with PRCTBL [ I ] do if LNK > 0 then begin if ( K MOD 3 ) = 0 then LIST002_NEWLINE ; K := K + 1 ; HEXHW ( LNK * 2 , CON1 ) ; WRITE ( LIST002 , CON1 : 5 , ':' , NAME : 9 ) ; if I < NXTPRC then WRITE ( LIST002 , ' (ER); ' ) else WRITE ( LIST002 , ' (LD); ' ) ; end (* then *) ; LIST002_NEWLINE ; end (* then *) else LIST002_NEWLINE ; //****************************************** // schreiben debug informationen //****************************************** if PIAKT -> . DEBUG_LEV > 0 then begin REST_ZEILZAHL := LIST002_HEADLINE ( 'R' , ' ' , ' ' , ' ' ) ; if REST_ZEILZAHL <= 10 then begin DUMMYINT := LIST002_HEADLINE ( 'S' , ' ' , ' ' , ' ' ) ; end (* then *) else LIST002_NEWLINE ; WRITE ( LIST002 , ' DEBUG INFORMATION:' ) ; LIST002_NEWLINE ; LIST002_NEWLINE ; WRITE ( LIST002 , ' DEBUG LEVEL = ' , PIAKT -> . DEBUG_LEV : 1 ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' SOURCENAME = ' , PIAKT -> . SOURCENAME ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' PROCNAME = ' , PIAKT -> . CURPNAME ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' CODESIZE = ' , CODESIZE : 1 ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' STATIC CSECT = ' , PIAKT -> . STATNAME ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' STACKSIZE = ' , STACKSIZE : 1 ) ; LIST002_NEWLINE ; end (* then *) ; LIST002_NEWLINE ; DUMMYINT := LIST002_HEADLINE ( 'V' , ' ' , ' ' , ' ' ) ; ASM := FALSE ; end (* PRINT_CSECT *) ; begin (* GEN_CSECT *) QPC := LBLTBL [ MINLBL ] . LNK ; while QPC > 1 do begin TPC := CODE . H [ QPC ] ; UPD_INTTBL ( QPC , STACKSIZE ) ; QPC := TPC ; end (* while *) ; DUMP_LITERALS ; (********************************) (* PROCESS EXTERNAL REFERENCES *) (********************************) for I := 0 to NXTPRC - 1 do with PRCTBL [ I ] do if LNK > 0 then begin TPC := LNK ; if FLOW_TRACE and ( NAME [ 1 ] <> '$' ) then LNK := - PCOUNTER * 2 else if VPOS > 0 then LNK := BASE_DSPLMT ( VPOS ) else LNK := BASE_DSPLMT ( PCOUNTER ) ; repeat QPC := CODE . H [ TPC ] ; CODE . H [ TPC ] := TO_HINT ( LNK ) ; TPC := QPC ; until TPC = 0 ; if VPOS > 0 then LNK := VPOS else begin LNK := PCOUNTER ; CODE . I [ PCOUNTER DIV 2 ] := 0 ; PCOUNTER := NEXTPC ( 2 ) ; end (* else *) end (* then *) ; TPC := PCOUNTER ; (************************************************) (* SET Proc SIZE FIELD at position posofproclen *) (* for debug purposes *) (* ... and stacksize *) (************************************************) CODESIZE := PCOUNTER * 2 ; CODE . H [ POSOFPROCLEN DIV 2 ] := TO_HINT ( CODESIZE ) ; CODE . H [ POSOFPROCLEN DIV 2 - 2 ] := TO_HINT ( STACKSIZE ) ; if PIAKT -> . DEBUG_LEV > 0 then begin repeat ADDLNP ( 255 ) until NXTLNP MOD 4 = 0 ; end (* then *) ; (*********************) (*SHORT PROC TOO LONG*) (*********************) if not PIAKT -> . LARGE_PROC then if PCOUNTER > 4096 then ERROR ( 609 ) ; (****************************) (* OUTPUT THE OBJECT CODE *) (****************************) for I := 1 to 20 do CARD . I [ I ] := BLNK4 ; BLNK80 := CARD . C ; PACK ( BLNK80 , 1 , BLNK64 ) ; (****************************) (* OUTPUT THE 'ESD' ENTRIES *) (****************************) if CURLVL = 1 then if not MUSIC then begin PRCTBL [ NXTPRC ] . NAME := '$PASENT ' ; NXTPRC := NXTPRC + 1 end (* then *) ; with ESD_CARD do begin I4 [ 1 ] := XESD ; I4 [ 2 ] := BLNK4 ; C64 := BLNK64 ; I := 0 ; J := 0 ; K := BLNK2 * SL16 + 1 ; repeat J := J + 1 ; with ITEM [ J ] , PRCTBL [ I ] do begin XNAME := NAME ; if I < NXTPRC then if I = 0 then (**********************) (* NAME OF THIS CSECT *) (**********************) begin F1 := 0 ; F2 := BLNK1 * SL24 + PCOUNTER * 2 + NXTLNP ; (************) (*CSECT SIZE*) (************) end (* then *) else (**********************) (* EXTERNAL REFERENCE *) (**********************) begin F1 := 2 * SL24 ; F2 := BLNK4 ; end (* else *) else (********************) (* LABEL DEFINITION *) (********************) begin F1 := 1 * SL24 + LNK * 2 ; F2 := BLNK1 * SL24 + 1 ; end (* else *) end (* with *) ; I := I + 1 ; if I = NXTPRC then I := NXTEP + 1 ; if ( J = 3 ) or ( I > PRCCNT ) then begin I4 [ 3 ] := BLNK2 * SL16 + J * 16 ; I4 [ 4 ] := K ; WRITE ( OBJCODE , C80 ) ; if I < NXTPRC then K := K + 3 else K := BLNK4 ; C64 := BLNK64 ; J := 0 end (* then *) ; until I > PRCCNT ; end (* with *) ; if CURLVL = 1 then if not MUSIC then NXTPRC := NXTPRC - 1 ; (****************************) (* OUTPUT THE 'TXT' CARDS *) (****************************) CARD . I [ 1 ] := XTXT ; CARD . I [ 2 ] := BLNK1 * SL24 + 0 ; CARD . I [ 3 ] := BLNK2 * SL16 + SIZE_TXTCHUNK ; CARD . I [ 4 ] := BLNK2 * SL16 + 01 ; TPC := MXCODE ; QPC := TPC + NXTLNP DIV 2 ; while TPC < QPC do begin CODE . H [ PCOUNTER ] := TO_HINT ( CODE . H [ TPC ] ) ; PCOUNTER := PCOUNTER + 1 ; TPC := TPC + 1 ; end (* while *) ; TPC := 0 ; I := 0 ; QPC := PCOUNTER * 2 ; LNGTH := SIZE_TXTCHUNK ; while TPC < QPC do begin if ( QPC - TPC ) < SIZE_TXTCHUNK then begin LNGTH := QPC - TPC ; CARD . H [ 6 ] := LNGTH ; end (* then *) ; CARD . H [ 4 ] := TPC ; WRITE ( OBJCODE , CARD . C : 16 , CODE . TXTCARD [ I ] : LNGTH , ' ' : 64 - LNGTH ) ; I := I + 1 ; TPC := TPC + SIZE_TXTCHUNK ; end (* while *) ; (****************************) (* OUTPUT THE 'RLD' ENTRIES *) (****************************) CARD . C := BLNK80 ; CARD . I [ 1 ] := XRLD ; I := 0 ; LNGTH := 0 ; repeat (*************************************) (* SCAN OVER ALL EXTERNAL REFERENCES *) (*************************************) with PRCTBL [ I ] do begin I := I + 1 ; (*********************************************) (* I NOW BECOMES ESDID FOR THE CURRENT ENTRY *) (*********************************************) if LNK > 0 then (**************************) (* IMPLIES RECURSIVE CALL *) (**************************) begin CARD . I [ LNGTH + 5 ] := I * SL16 + 01 ; (**********************) (* 'P#', 'R#' FIELDS *) (**********************) CARD . I [ LNGTH + 6 ] := 28 * SL24 + LNK * 2 ; (**********************) (* ADCON DISPLACEMENT *) (**********************) LNGTH := LNGTH + 2 ; if ( LNGTH >= 14 ) or ( I >= NXTPRC ) then (*********************) (* OUTPUT THE BUFFER *) (*********************) begin CARD . H [ 6 ] := LNGTH * 4 ; (***********************) (* # OF RLD DATA BYTES *) (***********************) while LNGTH < 14 do begin CARD . I [ LNGTH + 5 ] := BLNK4 ; LNGTH := LNGTH + 1 end (* while *) ; WRITE ( OBJCODE , CARD . C ) ; LNGTH := 0 ; end (* then *) ; end (* then *) ; end (* with *) until I >= NXTPRC ; (*********************) (* OUTPUT 'END' CARD *) (*********************) CARD . C := BLNK80 ; CARD . I [ 1 ] := XEND ; if CURLVL = 1 then if not MUSIC then begin CARD . I [ 2 ] := BLNK1 * SL24 ; CARD . H [ 8 ] := NXTPRC + 1 end (* then *) ; WRITE ( OBJCODE , CARD . C : 32 , 'PASCAL:' : 7 , DATE : 11 , ' ' : 30 ) ; PRINT_CSECT ( PCOUNTER ) ; if PIAKT -> . ASMVERB then begin WRITELN ( OUTPUT , '****' : 7 , ' PROC: ' , PRCTBL [ 0 ] . NAME , '; ' , PIAKT -> . CODE_SIZE : 1 , ' P-STMTS, ' , PCOUNTER * 2 : 1 , ' BYTES, ' , NXTPRC - 1 : 1 , ' EXT. REFS., ' , NUMLITS : 1 , ' CONSTANTS, ' , POOL_SIZE : 1 , ' BYTES OF CONSTANTS.' ) ; WRITELN ( OUTPUT ) ; end (* then *) ; TOTALBYTES := TOTALBYTES + QPC ; end (* GEN_CSECT *) ; procedure DUMPCONSTBLK ( CLOSE : BOOLEAN ) ; var CPC1 , LEN , I , J : HINTEGER ; TXTNUM : 0 .. 150 ; begin (* DUMPCONSTBLK *) if CSEGSTRT = 0 then (**************) (* FIRST CALL *) (**************) begin (***********************************) (* PUT OUT ESD CARD TO BEGIN CSECT *) (***********************************) WRITE ( OBJCODE , CHR ( 02 ) , 'ESD ' , CHR ( 0 ) , CHR ( 16 ) , ' ' , CHR ( 0 ) , CHR ( 1 ) , PRCTBL [ 0 ] . NAME , CHR ( 0 ) , CHR ( 0 ) , CHR ( 0 ) , CHR ( 0 ) , ' ' , CHR ( 0 ) , CHR ( 0 ) , CHR ( 0 ) , ' ' : 48 ) ; end (* then *) ; CPC1 := CSEGSTRT ; TXTNUM := 0 ; LEN := SIZE_TXTCHUNK ; while CPC1 < CPCOUNTER do begin if ( CPCOUNTER - CPC1 ) < SIZE_TXTCHUNK then LEN := CPCOUNTER - CPC1 ; if ( LEN = SIZE_TXTCHUNK ) or CLOSE then WRITE ( OBJCODE , CHR ( 02 ) , 'TXT ' , CHR ( 0 ) , CHR ( CPC1 DIV 256 ) , CHR ( CPC1 MOD 256 ) , ' ' , CHR ( 0 ) , CHR ( LEN ) , ' ' , CHR ( 0 ) , CHR ( 1 ) , CODE . TXTCARD [ TXTNUM ] : LEN , ' ' : 64 - LEN ) ; TXTNUM := TXTNUM + 1 ; CPC1 := CPC1 + LEN ; end (* while *) ; if CLOSE then (*******************************) (* LAST CALL, PUT OUT END CARD *) (*******************************) begin WRITE ( OBJCODE , CHR ( 02 ) , 'END' , ' ' : 24 , CHR ( 0 ) , CHR ( 0 ) , CHR ( CPC1 DIV 256 ) , CHR ( CPC1 MOD 256 ) , ' ' : 48 ) ; if CST_ASMVERB then begin WRITELN ( OUTPUT , '****' : 7 , ' CONSTS: ' , PRCTBL [ 0 ] . NAME , '; ' , CPC1 : 1 , ' BYTES.' ) ; WRITELN ( OUTPUT ) ; end (* then *) ; end (* then *) else begin J := CPC1 - LEN - CSEGSTRT ; CSEGSTRT := CPC1 - LEN ; I := 0 ; while I < LEN do begin CODE . C [ I ] := CODE . C [ J + I ] ; I := I + 1 end (* while *) ; CSEGLIMIT := CSEGSTRT + SIZE_TXTCHUNK * 145 ; end (* else *) ; end (* DUMPCONSTBLK *) ; procedure ENT_RET ; var STATIC_ADDR : ADRRNG ; OFFS_WORK : ADRRNG ; SIZE_REST : ADRRNG ; begin (* ENT_RET *) PROCOFFSET_OLD := 0 ; if OPCODE = PENT then begin (***********************************************************) (* ON ENTRY TRG1 POINTS TO DATA AREA *) (* for the called routine *) (***********************************************************) CURLVL := P ; INIT_CSECT ; (*********************************) (*INITIALIZE NEW CSECT PARAMETERS*) (*********************************) STATIC_ADDR := PCOUNTER * 2 - 4 ; //*********************************************************** // if there are local calls, the display value at the // current static level has to saved and restored at // the end ... load it to R0, it will be saved by the // following stm 14,12,... //*********************************************************** if PIAKT -> . CALL_HIGHER then begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- save display level ' , CURLVL : 1 ) ; LIST002_NEWLINE ; end (* then *) ; GENRX ( XL , TRG0 , DISPLAY + 4 * CURLVL , GBR , 0 ) ; end (* then *) ; (***************************) (* TO SAVE DISPLAY[CURLVL] *) (***************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- save registers and chain areas' ) ; LIST002_NEWLINE ; end (* then *) ; GENRS ( XSTM , 14 , 12 , 12 , TRG1 ) ; (*********************************) (*SAVE OLD DISPLAY[CURLVL] & REGS*) (*********************************) GENRX ( XST , TRG1 , 8 , LBR , 0 ) ; (*****************************) (*FORWARD CHAIN OF SAVE AREAS*) (*****************************) GENRX ( XST , LBR , 4 , TRG1 , 0 ) ; (************************************) (*DYNAMIC LINK, ALSO SAVE AREA CHAIN*) (************************************) (*************************** *) (* SAVE DYNAMIC LINK + REGS *) (*************************** *) GENRR ( XLR , LBR , TRG1 ) ; (*****************) (*UPDATE THE 'MP'*) (*****************) if PIAKT -> . CALL_HIGHER then begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- update current display' ) ; LIST002_NEWLINE ; end (* then *) ; GENRX ( XST , LBR , DISPLAY + 4 * CURLVL , GBR , 0 ) ; end (* then *) ; (************************) (*UPDATE DISPLAY[CURLVL]*) (************************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- setup base registers' ) ; LIST002_NEWLINE ; end (* then *) ; GENRR ( XLR , PBR1 , JREG ) ; (*********************************) (* SET UP PROGRAM BASE REGISTERS *) (*********************************) if PIAKT -> . LARGE_PROC then GENLA_LR ( PBR2 , 4092 , PBR1 , 0 ) ; if DEBUG or MUSIC then begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- check for enough stack space' ) ; LIST002_NEWLINE ; end (* then *) ; if PIAKT -> . DATA_SIZE < 4096 then GENLA_LR ( TRG1 , PIAKT -> . DATA_SIZE , TRG1 , 0 ) else GENRXLAB ( XA , TRG1 , PIAKT -> . SEGSZE , - 1 ) ; GENRX ( XC , TRG1 , NEWPTR , GBR , 0 ) ; //************************************************ // COMPARE 'SP' AND 'NP' //************************************************ GENRX ( XBC , GEQCND , STKCHK , GBR , 0 ) ; //************************************************ // BRANCH TO ERROR ? //************************************************ if DEBUG then if CURLVL = 1 then begin //******************************************************** // ENTERING PASMAIN, CLEAR STACK/HEAP AREA //******************************************************** if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- clear stack/heap area' ) ; LIST002_NEWLINE ; end (* then *) ; //******************************************************** // L 15,72(12) end of stack area // LA 14,400(12) first global variable address // SR 15,14 length to initialize in R15 // XR 0,0 source adr zero // LA 1,129 source len zero // SLL 1,24 pattern x'81' in leftmost 8 bytes // MVCL 14,0 move init pattern //******************************************************** GENRX ( XL , TRG15 , NEWPTR , GBR , 0 ) ; GENLA_LR ( TRG14 , FRSTGVAR , GBR , 0 ) ; GENRR ( XSR , TRG15 , TRG14 ) ; GENRR ( XXR , TRG0 , TRG0 ) ; GENLA_LR ( TRG1 , 129 , 0 , 0 ) ; GENRS ( XSLL , TRG1 , 0 , 24 , 0 ) ; GENRR ( XMVCL , TRG14 , TRG0 ) ; end (* then *) ; end (* then *) ; CSPACTIVE [ TRG15 ] := FALSE ; PROCOFFSET_OLD := 0 ; end (* then *) else (************************************************) (* pcode = PRET *) (************************************************) begin (***********************************************) (*RESTORES DISPLAY[CURLVL] AND MP, THEN RETURNS*) (***********************************************) if DEBUG and ( CURLVL > 1 ) and ( PIAKT -> . DATA_SIZE > 80 ) then if PIAKT -> . DATA_SIZE < 1500 then begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- clear stack frame using MVCs' ) ; LIST002_NEWLINE ; end (* then *) ; //************************************************ // optimizing: generate MVC instead of MVCL // MVI 80(13),X'81' // MVC 81(256,13),80(13) ... //************************************************ GENSI ( XMVI , LCAFTMST , LBR , 0x81 ) ; OFFS_WORK := LCAFTMST + 1 ; SIZE_REST := PIAKT -> . DATA_SIZE - LCAFTMST - 1 ; while SIZE_REST > 256 do begin GENSS ( XMVC , 256 , OFFS_WORK , LBR , OFFS_WORK - 1 , LBR ) ; OFFS_WORK := OFFS_WORK + 256 ; SIZE_REST := SIZE_REST - 256 end (* while *) ; GENSS ( XMVC , SIZE_REST , OFFS_WORK , LBR , OFFS_WORK - 1 , LBR ) ; end (* then *) else begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- clear stack frame using MVCL' ) ; LIST002_NEWLINE ; end (* then *) ; //****************************** // clear the stack frame // that is: // LA 0,80(13) // length into R1 // XR R14,R14 // LA R15,X'81' // SLL R15,24 // MVCL R0,R14 //****************************** GENLA_LR ( TRG0 , LCAFTMST , LBR , 0 ) ; if PIAKT -> . DATA_SIZE < 4096 then GENLA_LR ( TRG1 , PIAKT -> . DATA_SIZE - LCAFTMST , 0 , 0 ) else begin GENRXLAB ( XL , TRG1 , PIAKT -> . SEGSZE , - 1 ) ; GENRXLIT ( XS , TRG1 , LCAFTMST - REALSIZE , 0 ) ; end (* else *) ; GENRR ( XXR , TRG14 , TRG14 ) ; GENLA_LR ( TRG15 , 0x81 , 0 , 0 ) ; GENRX ( XSLL , TRG15 , 24 , 0 , 0 ) ; GENRR ( XMVCL , TRG0 , TRG14 ) ; end (* else *) ; //************************************************ // restore the general registers //************************************************ if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- restore registers' ) ; LIST002_NEWLINE ; end (* then *) ; GENRS ( XLM , 14 , 12 , 12 , LBR ) ; GENRX ( XL , LBR , 4 , LBR , 0 ) ; //************************************************ // restore the display value at the // current static level; it has been reloaded from // the // save area to R0 ... //************************************************ if PIAKT -> . CALL_HIGHER then begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- restore display level ' , CURLVL : 1 ) ; LIST002_NEWLINE ; end (* then *) ; GENRX ( XST , TRG0 , DISPLAY + 4 * CURLVL , GBR , 0 ) ; end (* then *) ; if DEBUG and ( CURLVL > 1 ) then (***********************) (* CLEAR THE SAVE AREA *) (***********************) begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- clear the save area' ) ; LIST002_NEWLINE ; end (* then *) ; I := 80 ; if OPNDTYPE <> PROC then I := 72 ; GENSS ( XMVC , I , 0 , TRG1 , 80 , TRG1 ) ; end (* then *) ; if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- branch to return address' ) ; LIST002_NEWLINE ; end (* then *) ; if FLOW_TRACE then begin GENRR ( XLR , 0 , RTREG ) ; GENRX ( XBAL , RTREG , TRACER , GBR , 0 ) ; if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , ' DC AL2(0)' ) ; LIST002_NEWLINE ; end (* then *) ; CODE . H [ PCOUNTER ] := 0 ; PCOUNTER := NEXTPC ( 1 ) ; end (* then *) else GENRR ( XBCR , ANYCND , RTREG ) ; RELEASE ( HEAPMARK ) ; if CKMODE then CHECKFREEREGS ; end (* else *) end (* ENT_RET *) ; procedure DEF_OPERATION ; begin (* DEF_OPERATION *) /***************************************************/ /* pdef steht entweder am Ende einer Prozedur */ /* bzw. funktion und gibt deren laenge an */ /* oder am anfang einer branch table, */ /* dann zweimal fuer lower und upper limit */ /***************************************************/ if GS . MOD2DEFSTEP >= 0 then begin /***************************************************/ /* ende einer prozedur ... hier folgen */ /* ab 2018.03 noch mehrere defs, die weitere */ /* informationen fuer die prozedur enthalten */ /***************************************************/ case GS . MOD2DEFSTEP of 0 : GS . MOD2DEFSTEP := 1 ; 1 : GS . MOD2DEFSTEP := 2 ; 2 : begin GS . MOD2DEFSTEP := - 1 ; PDEF_CNT := 0 ; GEN_CSECT ( Q ) ; GS . FILL_LINEPTR := FALSE ; PIAKT := NIL ; PCOUNTER := 0 ; end (* tag/ca *) end (* case *) ; return end (* then *) ; /***************************************************/ /* am anfang einer branch table, */ /* dann zweimal fuer lower und upper limit */ /***************************************************/ if LBL1 . LEN > 0 then begin PDEF_CNT := PDEF_CNT + 1 ; /*************************************/ /* CTR/CASE EXPRESSION RANGE, */ /* PUT BOUNDS IN 'CONSTANT' TABLE */ /* but not for constants */ /* in new portable branch table */ /*************************************/ UPD_INTTBL ( LBLTBL [ LBLMAP ( LBL1 . NAM ) ] . LNK , Q ) ; end (* then *) else begin PDEF_CNT := PDEF_CNT + 1 ; if PDEF_CNT = 1 then begin CASE_LOW := Q ; CASE_HIGH := Q ; end (* then *) ; if not CASE_FLAG_NEW then /**********************************/ /* portable branch table beginnt */ /**********************************/ begin CASE_FLAG := TRUE ; CASE_FLAG_NEW := TRUE ; CASE_DEFAULT := LBLMAP ( LBL1 . NAM ) + 1 ; CASE_OPNDTYPE := OPNDTYPE ; /**********************************/ /* pre-format area of branch- */ /* table with zeroes */ /**********************************/ PCNEU := NEXTPC ( CIXMAX ) ; for PC := PCOUNTER to PCNEU do CODE . H [ PC ] := 0 ; if CASE_OPNDTYPE = CHRC then for C := CHR ( 0 ) to CHR ( 255 ) do CASE_CHARTABLE [ C ] := - 1 ; if FALSE then begin WRITELN ( TRACEF , '---------------------' '---------------------' ) ; WRITELN ( TRACEF , 'pcounter = ' , PCOUNTER ) ; WRITELN ( TRACEF , 'case_low = ' , CASE_LOW ) ; WRITELN ( TRACEF , 'case_flag = ' , CASE_FLAG ) ; WRITELN ( TRACEF , 'case_flag_new = ' , CASE_FLAG_NEW ) ; WRITELN ( TRACEF , 'case_default = ' , CASE_DEFAULT ) ; WRITELN ( TRACEF , 'case_opndtype = ' , CASE_OPNDTYPE ) ; WRITELN ( TRACEF , '---------------------' '---------------------' ) ; end (* then *) ; end (* then *) ; CASE_LABEL := Q ; if FALSE then begin WRITELN ( TRACEF , 'case_label = ' , CASE_LABEL ) ; WRITELN ( TRACEF , '---------------------' '---------------------' ) ; end (* then *) end (* else *) end (* DEF_OPERATION *) ; procedure LAB_OPERATION ; begin (* LAB_OPERATION *) if CASE_FLAG then begin if CASE_FLAG_NEW then /****************************************/ /* portable branch table komplettieren */ /* und pcounter hochsetzen */ /****************************************/ begin PCNEU := NEXTPC ( CASE_HIGH - CASE_LOW ) ; /****************************************/ /* im fall char erst jetzt alle */ /* adresskonstanten anhand von */ /* case_chartable erzeugen - weil erst */ /* jetzt case_low und case_high */ /* festliegen */ /****************************************/ if CASE_OPNDTYPE = CHRC then begin CASE_LAUF := CASE_LOW ; for PC := PCOUNTER to PCNEU do begin CL := CASE_CHARTABLE [ CHR ( CASE_LAUF ) ] ; if CL >= 0 then begin MKLBL ( LBL_WORK , CL ) ; GENAL2 ( PC , LBL_WORK ) ; end (* then *) else begin MKLBL ( LBL_WORK , CASE_DEFAULT ) ; GENAL2 ( PC , LBL_WORK ) ; end (* else *) ; CASE_LAUF := CASE_LAUF + 1 ; end (* for *) ; end (* then *) /****************************************/ /* andernfalls war vorher schon alles */ /* klar (case_low lag schon fest, */ /* erste def_konstante) und jetzt sind */ /* nur noch die luecken zu fuellen */ /****************************************/ else begin for PC := PCOUNTER to PCNEU do begin if CODE . H [ PC ] = 0 then begin MKLBL ( LBL_WORK , CASE_DEFAULT ) ; GENAL2 ( PC , LBL_WORK ) ; end (* then *) end (* for *) end (* else *) ; PCOUNTER := PCNEU ; PCOUNTER := NEXTPC ( 1 ) ; (***********************************************) (* Konstanten bei neuer portabler Branch Table *) (* als literale ablegen *) (***********************************************) UPD_INTTBL ( LBLTBL [ CASE_DEFAULT - 3 ] . LNK , CASE_LOW ) ; if ASM then begin MKLBL ( LBLX , CASE_DEFAULT - 3 ) ; HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , LBLX . NAM , ' EQU ' , CASE_LOW : 1 ) ; LIST002_NEWLINE ; end (* then *) ; UPD_INTTBL ( LBLTBL [ CASE_DEFAULT - 2 ] . LNK , CASE_HIGH ) ; if ASM then begin MKLBL ( LBLX , CASE_DEFAULT - 2 ) ; HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , LBLX . NAM , ' EQU ' , CASE_HIGH : 1 ) ; LIST002_NEWLINE ; end (* then *) ; CASE_FLAG_NEW := FALSE ; end (* then *) ; PDEF_CNT := 0 ; CASE_FLAG := FALSE ; end (* then *) ; (***********************) (* END OF BRANCH TABLE *) (***********************) if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; X1 := 8 ; while LBL1 . NAM [ X1 ] = ' ' do X1 := X1 - 1 ; if X1 < 5 then X1 := 5 ; for X2 := 1 to X1 do WRITE ( LIST002 , LBL1 . NAM [ X2 ] ) ; WRITE ( LIST002 , ' DS 0H' ) ; LIST002_NEWLINE ; end (* then *) ; (******************) (*LABEL DEFINITION*) (******************) UPD_LBLTBL ( PCOUNTER , LBLMAP ( LBL1 . NAM ) , TRUE , FALSE ) ; (******************************************) (* if old opcode = PDEF and pdef_cnt = 2, *) (* start of branch table *) (******************************************) if FALSE then begin WRITELN ( TRACEF , 'oldopcode = ' , OLDOPCODE ) ; WRITELN ( TRACEF , 'pdef_cnt = ' , PDEF_CNT ) ; end (* then *) ; CASE_FLAG := ( OLDOPCODE = PDEF ) and ( PDEF_CNT = 2 ) ; (**********************) (* some inits *) (**********************) CSPACTIVE [ TRG15 ] := FALSE ; PROCOFFSET_OLD := 0 ; TXR_CONTENTS . VALID := FALSE ; FILADR_LOADED := FALSE ; LAST_CC . LAST_PC := 0 ; LAST_STR . LAST_PC := 0 ; LAST_FILE . LAST_PC := 0 ; LAST_MVC . LAST_PC := 0 ; if CKMODE then CHECKFREEREGS ; end (* LAB_OPERATION *) ; begin (* COPERATION *) case OPCODE of (************************) (* P_MACHINE PSEUDO OPS *) (************************) PXLB : begin GENRELRX ( XBC , ANYCND , 14 ) ; (********************************) (* B *+28, SKIP OVER ENTRY CODE *) (********************************) with PRCTBL [ NXTEP ] do begin NAME := LBL1 . NAM ; LNK := PCOUNTER end (* with *) ; if NXTEP > NXTPRC then NXTEP := NXTEP - 1 else ERROR ( 256 ) ; (**************************) (* COLLISION OF TWO LISTS *) (**************************) GENRR ( XBALR , RTREG , 0 ) ; (************************************) (* FORCE A BASE REG. FOR NEXT INST. *) (************************************) GENRX ( XBAL , PBR1 , 6 , RTREG , 0 ) ; CODE . H [ PCOUNTER ] := TO_HINT ( PCOUNTER * 2 ) ; PCOUNTER := NEXTPC ( 1 ) ; GENLA_LR ( PBR1 , 4 , RTREG , 0 ) ; (*******************) (* CLEAR HIGH BYTE *) (*******************) GENRX ( XSH , PBR1 , 4 , RTREG , 0 ) ; if PIAKT -> . LARGE_PROC then GENLA_LR ( PBR2 , 4092 , PBR1 , 0 ) else GENRX ( XBC , NOCND , 0 , 0 , 0 ) ; GENRX ( XL , LBR , DISPLAY + 4 * CURLVL , GBR , 0 ) ; (******************************************************) (* PLAB INSTR. IS NEXT ==> NO NEED TO RESET ANY FLAGS *) (******************************************************) end (* tag/ca *) ; PLAB : LAB_OPERATION ; PLOC : begin //********************************************************** // new 05.2019: // to create tables of offsets and statement numbers //********************************************************** if TOS_COUNT = 0 then begin TOS_COUNT := 1 ; TOS [ TOS_COUNT ] . STMT := Q ; TOS [ TOS_COUNT ] . OFFS := PCOUNTER end (* then *) else begin if TOS [ TOS_COUNT ] . STMT < Q then begin TOS_COUNT := TOS_COUNT + 1 ; TOS [ TOS_COUNT ] . STMT := Q ; TOS [ TOS_COUNT ] . OFFS := PCOUNTER end (* then *) ; if TOS [ TOS_COUNT ] . STMT = Q then if TOS [ TOS_COUNT ] . OFFS > PCOUNTER then TOS [ TOS_COUNT ] . OFFS := PCOUNTER end (* else *) ; (***************************************) (* FILL THE ENTRIES OF LINE PTR TABLE *) (***************************************) if GS . FILL_LINEPTR then begin if PIAKT -> . DEBUG_LEV > 0 then for I := LASTLN to Q - 1 do begin UPDLNTBL ( PCOUNTER - LASTPC ) ; LASTPC := PCOUNTER ; end (* for *) ; end (* then *) ; LASTLN := Q ; (***************************) (* TO TREAT THIS AS A NOOP *) (***************************) OPCODE := OLDOPCODE ; end (* tag/ca *) ; PDEF : DEF_OPERATION ; (*******************************) (* BRANCH/CONTROL INSTRUCTIONS *) (*******************************) PUJP : begin if FLOW_TRACE and not CASE_FLAG then begin GENRX ( XBAL , RTREG , TRACER , GBR , 0 ) ; if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , ' DC AL2(' , LBL2 . NAM : LBL2 . LEN , '-' , PRCTBL [ 0 ] . NAME , ')' ) ; LIST002_NEWLINE ; end (* then *) ; UPD_LBLTBL ( PCOUNTER , LBLMAP ( LBL2 . NAM ) , FALSE , TRUE ) ; PCOUNTER := NEXTPC ( 1 ) ; end (* then *) else if not CASE_FLAG_NEW then begin GENRXLAB ( XBC , 15 , LBL2 , 0 ) end (* then *) else begin if CASE_LOW > CASE_LABEL then CASE_LOW := CASE_LABEL ; if CASE_HIGH < CASE_LABEL then CASE_HIGH := CASE_LABEL ; if CASE_OPNDTYPE = CHRC then begin CASE_CHARTABLE [ CHR ( CASE_LABEL ) ] := LBLMAP ( LBL2 . NAM ) ; end (* then *) else begin PC := PCOUNTER + CASE_LABEL - CASE_LOW ; GENAL2 ( PC , LBL2 ) end (* else *) ; end (* else *) ; end (* tag/ca *) ; PUXJ : begin if PIAKT -> . CALL_HIGHER then begin GENRX ( XL , TRG0 , 20 , LBR , 0 ) ; GENRX ( XST , TRG0 , DISPLAY + 4 * CURLVL , GBR , 0 ) ; end (* then *) ; if FLOW_TRACE then begin GENRXLAB ( XL , TRG0 , LBL2 , - 3 ) ; GENRX ( XBAL , RTREG , TRACER , GBR , 0 ) ; CODE . H [ PCOUNTER ] := 0 ; PCOUNTER := NEXTPC ( 1 ) ; end (* then *) else begin GENRXLAB ( XL , RTREG , LBL2 , - 3 ) ; GENRR ( XBCR , ANYCND , RTREG ) ; end (* else *) ; OPCODE := PUJP ; end (* tag/ca *) ; PFJP : begin TOP := TOP - 1 ; if ( BRCND >= 0 ) and ( not NEG_CND ) then (***********************) (* COND. CODE IS ALIVE *) (***********************) BRCND := 15 - BRCND else with STK [ TOP ] do begin if VRBL then begin if DRCT and ( VPA = MEM ) then begin GETOPERAND ( STK [ TOP ] , Q1 , P1 , B1 ) ; if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; GENSI ( XTM , Q1 , P1 , 1 ) ; BRCND := 8 ; (********) (* BZ *) (********) if NEG_CND then BRCND := 1 ; (********) (* BO *) (********) end (* then *) else if not DRCT then begin GETADR ( STK [ TOP ] , Q1 , P1 , B1 ) ; if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; GENSI ( XTM , Q1 , P1 , 1 ) ; BRCND := 8 ; if NEG_CND then BRCND := 1 ; end (* then *) else begin LOAD ( STK [ TOP ] ) ; GENRR ( XLTR , RGADR , RGADR ) ; BRCND := EQUCND ; if NEG_CND then BRCND := NEQCND ; end (* else *) ; FREEREG ( STK [ TOP ] ) ; end (* then *) else (**********) (*NOT VRBL*) (**********) if FPA . DSPLMT = 0 then begin BRCND := ANYCND ; OPCODE := PUJP end (* then *) else BRCND := NOCND ; (***************) (*DO NOT BRANCH*) (***************) if VRBL then if ( VPA = RGS ) then AVAIL [ RGADR ] := TRUE ; end (* with *) ; if BRCND <> NOCND then if FLOW_TRACE then begin BRCND := 15 - BRCND ; if BRCND > 0 then GENRELRX ( XBC , BRCND , 5 ) ; (*****************) (* BC BRCND,*+10 *) (*****************) GENRX ( XBAL , RTREG , TRACER , GBR , 0 ) ; if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , ' DC AL2(' , LBL2 . NAM : LBL2 . LEN , '-' , PRCTBL [ 0 ] . NAME , ')' ) ; LIST002_NEWLINE ; end (* then *) ; UPD_LBLTBL ( PCOUNTER , LBLMAP ( LBL2 . NAM ) , FALSE , TRUE ) ; PCOUNTER := NEXTPC ( 1 ) ; end (* then *) else GENRXLAB ( XBC , BRCND , LBL2 , 0 ) ; (****************************) (* CLEAR C.C./ NEGATE FLAGS *) (****************************) BRCND := - 1 ; NEG_CND := FALSE ; end (* tag/ca *) ; PXJP : (***********************************************) (* LBL2 = LOWER BOUND, CASE EXPRESSION *) (* LBL2+1 = UPPER BOUND, *) (* LBL2+2 = BRANCH TABLE LABEL *) (* LBL2+3 = CASE EXIT LABEL *) (***********************************************) begin TOP := TOP - 1 ; LOAD ( STK [ TOP ] ) ; with STK [ TOP ] do begin Q := LBLMAP ( LBL2 . NAM ) ; /****************************************/ /* new xjp = xjp without def constants */ /* for high and low values */ /* ------------------------------------ */ /* pascal1 has left 2 labels unused */ /* in this case to be used by code */ /* generators for their own fields */ /* to store the min and max values */ /* determined during branch table scan */ /****************************************/ if XJPFLAG = 'N' then begin Q := Q - 2 ; MKLBL ( LBL2 , Q ) ; end (* then *) ; MKLBL ( LBL1 , Q + 1 ) ; MKLBL ( LBL_WORK , Q + 3 ) ; if FLOW_TRACE then begin GENRXLAB ( XLA , JREG , LBL_WORK , - 1 ) ; GENRR ( XSR , JREG , PBR1 ) ; GENRXLAB ( XC , RGADR , LBL1 , - 1 ) ; GENRELRX ( XBC , GRTCND , 9 ) ; (***********) (* BH *+18 *) (***********) GENRXLAB ( XS , RGADR , LBL2 , - 1 ) ; GENRELRX ( XBC , LESCND , 5 ) ; (***********) (* BM *+10 *) (***********) GENRR ( XAR , RGADR , RGADR ) ; MKLBL ( LBL_WORK , Q + 2 ) ; GENRXLAB ( XLH , JREG , LBL_WORK , RGADR ) ; GENRELRX ( XSTH , JREG , 4 ) ; (****************) (* STH JREG,*+8 *) (****************) GENRX ( XBAL , RTREG , TRACER , GBR , 0 ) ; CODE . H [ PCOUNTER ] := 0 ; PCOUNTER := NEXTPC ( 1 ) ; end (* then *) else begin GENRXLAB ( XC , RGADR , LBL1 , - 1 ) ; (*****************************) (* CHECK AGAINST UPPER BOUND *) (*****************************) GENRXLAB ( XBC , GRTCND , LBL_WORK , 0 ) ; (*****************************) (* GO TO EXIT IF OUT OF RANGE*) (*****************************) GENRXLAB ( XS , RGADR , LBL2 , - 1 ) ; (*****************************) (* ELSE SUBTRACT LOWER BOUND *) (*****************************) GENRXLAB ( XBC , LESCND , LBL_WORK , 0 ) ; (*****************************) (* CASE_EXIT IF OUT OF RANGE *) (*****************************) MKLBL ( LBL_WORK , Q + 2 ) ; GENRR ( XAR , RGADR , RGADR ) ; (*******************************) (* CONV. INDEX TO TABLE OFFSET *) (*******************************) GENRXLAB ( XLH , JREG , LBL_WORK , RGADR ) ; GENRX ( XBC , ANYCND , 0 , JREG , PBR1 ) ; end (* else *) ; AVAIL [ RGADR ] := TRUE ; end (* with *) ; end (* tag/ca *) ; PPOP : begin TOP := TOP - 1 ; FREEREG ( STK [ TOP ] ) ; end (* tag/ca *) ; PMST : if CALL_DEPTH < MAX_CALL_DEPTH then begin CALL_DEPTH := CALL_DEPTH + 1 ; if FALSE then WRITELN ( TRACEF , 'call_depth ++ ' , CALL_DEPTH , ' linecnt = ' , LINECNT : 1 ) ; with CALL_MST_STACK [ CALL_DEPTH ] do begin PFLEV := P ; DISPSAV := Q end (* with *) ; end (* then *) else begin WRITELN ( 'call_depth = ' , CALL_DEPTH ) ; ERROR ( 759 ) ; end (* else *) ; PCUP : begin CALLSUB ; if OPNDTYPE <> PROC then with STK [ TOP ] do begin STK [ TOP ] := DATNULL ; //****************************************************** // extlang = fortran: // COPY RESULT FROM REGISTER ZERO //****************************************************** case EXTLANG of 'F' : case OPNDTYPE of BOOL : begin FINDRG ; GENRR ( XLR , NXTRG , 0 ) end (* tag/ca *) ; INT : begin FINDRG ; GENRR ( XLR , NXTRG , 0 ) end (* tag/ca *) ; REEL : begin FINDFP ; GENRR ( XLDR , NXTRG , 0 ) end (* tag/ca *) ; end (* case *) ; //****************************************************** // extlang = assembler: // COPY RESULT FROM REGISTER ZERO //****************************************************** 'A' : case OPNDTYPE of ADR , INT : begin FINDRG ; GENRR ( XLR , NXTRG , 0 ) end (* tag/ca *) ; HINT : begin FINDRG ; GENRR ( XLR , NXTRG , 0 ) end (* tag/ca *) ; BOOL , CHRC : begin FINDRG ; GENRR ( XLR , NXTRG , 0 ) end (* tag/ca *) ; PSET : ERROR ( 616 ) ; REEL : begin FINDFP ; GENRR ( XLDR , NXTRG , 0 ) end (* tag/ca *) ; end (* case *) ; //****************************************************** // extlang = pascal: // COPY RESULT FROM 72 (R1) //****************************************************** otherwise case OPNDTYPE of ADR , INT : begin FINDRG ; GENRX ( XL , NXTRG , FNCRSLT , TRG1 , 0 ) end (* tag/ca *) ; HINT : begin FINDRG ; GENRX ( XLH , NXTRG , FNCRSLT , TRG1 , 0 ) ; end (* tag/ca *) ; BOOL , CHRC : begin FINDRG ; GENRR ( XSR , NXTRG , NXTRG ) ; GENRX ( XIC , NXTRG , FNCRSLT , TRG1 , 0 ) ; end (* tag/ca *) ; PSET : ERROR ( 616 ) ; REEL : begin FINDFP ; GENRX ( XLD , NXTRG , FNCRSLT , TRG1 , 0 ) end (* tag/ca *) ; VARC : begin FINDRG ; GENLA_LR ( NXTRG , FNCRSLT , TRG1 , 0 ) ; PLEN := - 1 ; end (* tag/ca *) ; end (* case *) end (* case *) ; VRBL := TRUE ; DRCT := TRUE ; FPA := ZEROBL ; VPA := RGS ; RGADR := NXTRG ; DTYPE := OPNDTYPE ; TOP := TOP + 1 ; end (* with *) else if CKMODE then CHECKFREEREGS ; CSPACTIVE [ TRG15 ] := FALSE ; CSPACTIVE [ TRG1 ] := FALSE ; end (* tag/ca *) ; PENT , PRET : begin if OPCODE = PENT then begin GS . IN_PROCBODY := TRUE ; GS . FILL_LINEPTR := TRUE ; end (* then *) else begin GS . IN_PROCBODY := FALSE ; GS . MOD2DEFSTEP := 0 end (* else *) ; ENT_RET ; end (* tag/ca *) ; PCSP : case CSP of PDAT : CALLSTNDRD ; PTIM : CALLSTNDRD ; otherwise CALLSTNDRD ; end (* case *) ; PCST : begin (************************************************) (* BEGINNING OF A CSECT OF STRUCTURED CONSTANTS *) (************************************************) PRCTBL [ 0 ] . NAME := LBL1 . NAM ; PRCTBL [ 0 ] . LNK := 0 ; for CPCOUNTER := 0 to 7 do CODE . C [ CPCOUNTER ] := LBL1 . NAM [ CPCOUNTER + 1 ] ; for CPCOUNTER := 8 to 15 do CODE . C [ CPCOUNTER ] := CHR ( 0 ) ; CPCOUNTER := 16 ; PCOUNTER := CPCOUNTER ; CSTBLK := TRUE ; CSEGSTRT := 0 ; CSEGLIMIT := SIZE_TXTCHUNK * 145 ; end (* tag/ca *) ; PDFC : begin (********************************************) (* A SIMPLE CONSTANT IN THE CONSTANTS CSECT *) (********************************************) if CSTBLK then if LBL1 . CADDR <= 32767 then begin if CPCOUNTER > LBL1 . CADDR then ERROR ( 617 ) ; while CPCOUNTER < LBL1 . CADDR do begin if CPCOUNTER = CSEGLIMIT then DUMPCONSTBLK ( FALSE ) ; CODE . C [ CPCOUNTER - CSEGSTRT ] := CHR ( 0 ) ; CPCOUNTER := CPCOUNTER + 1 ; end (* while *) ; PCOUNTER := LBL1 . CADDR ; Q := PCOUNTER - CSEGSTRT ; case OPNDTYPE of NON : begin CPCOUNTER := LBL1 . CADDR + SLNGTH ; end (* tag/ca *) ; BOOL , CHRC : begin if not ( IVAL in [ 0 .. 255 ] ) then ERROR ( 301 ) ; CODE . C [ Q ] := CHR ( IVAL ) ; CPCOUNTER := CPCOUNTER + 1 ; end (* tag/ca *) ; HINT : begin if ( IVAL < - 32768 ) or ( IVAL > 32767 ) then ERROR ( 301 ) ; if ODD ( Q ) then ERROR ( 610 ) ; CODE . H [ Q DIV 2 ] := TO_HINT ( IVAL ) ; CPCOUNTER := CPCOUNTER + 2 ; end (* tag/ca *) ; INT , ADR : begin if Q MOD 4 <> 0 then ERROR ( 611 ) ; CODE . I [ Q DIV 4 ] := IVAL ; CPCOUNTER := CPCOUNTER + 4 ; end (* tag/ca *) ; PSET : begin if Q MOD 4 <> 0 then ERROR ( 611 ) ; for P := 1 to PSLNGTH do begin CODE . C [ Q ] := PSVAL . C [ P ] ; Q := Q + 1 ; end (* for *) ; CPCOUNTER := LBL1 . CADDR + PSLNGTH ; end (* tag/ca *) ; CARR : begin for P := 1 to SLNGTH do begin CODE . C [ Q ] := SVAL [ P ] ; Q := Q + 1 ; end (* for *) ; CPCOUNTER := LBL1 . CADDR + SLNGTH ; end (* tag/ca *) ; REEL : begin if Q MOD 8 <> 0 then ERROR ( 612 ) ; CODE . R [ Q DIV 8 ] := RVAL ; CPCOUNTER := CPCOUNTER + 8 ; end (* tag/ca *) ; end (* case *) ; end (* then *) else ERROR ( 251 ) ; end (* tag/ca *) ; PEND : if CSTBLK then begin (********************************) (* store length of static csect *) (* at addr of static csect + 8 *) (********************************) CODE . H [ 4 ] := TO_HINT ( CPCOUNTER ) ; if CPCOUNTER > 16 then DUMPCONSTBLK ( TRUE ) ; TOTALBYTES := TOTALBYTES + CPCOUNTER ; CSTBLK := FALSE ; end (* then *) ; PSTP : if ASM then begin (*******************************) (* GENERATE ASSEMBLER END CARD *) (*******************************) WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'EXTRN $PASENT' ) ; LIST002_NEWLINE ; WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'END $PASENT' ) ; LIST002_NEWLINE ; end (* then *) ; end (* case *) ; end (* COPERATION *) ; procedure UOPERATION ; (********************) (* UNARY OPERATIONS *) (********************) begin (* UOPERATION *) case OPCODE of PFLT , PFLO : begin if OPCODE = PFLT then OPPTR := TOP - 1 else OPPTR := TOP - 2 ; with STK [ OPPTR ] do if VRBL then begin LOAD ( STK [ OPPTR ] ) ; FINDFP ; GENRX ( XX , RGADR , FL2 + 4 , GBR , 0 ) ; GENRX ( XST , RGADR , FL1 + 4 , GBR , 0 ) ; GENRX ( XLD , NXTRG , FL1 , GBR , 0 ) ; GENRX ( XSD , NXTRG , FL2 , GBR , 0 ) ; AVAIL [ RGADR ] := TRUE ; DTYPE := REEL ; RGADR := NXTRG ; end (* then *) else (***********) (* CONSTANT*) (***********) begin DTYPE := REEL ; RCNST := FPA . DSPLMT ; FPA . DSPLMT := 0 ; end (* else *) end (* tag/ca *) ; PNGR : with STK [ TOP - 1 ] do if VRBL then begin LOAD ( STK [ TOP - 1 ] ) ; GENRR ( XLCDR , RGADR , RGADR ) end (* then *) else (************) (* CONSTANT *) (************) RCNST := - RCNST ; PNGI : with STK [ TOP - 1 ] do if VRBL then begin LOAD ( STK [ TOP - 1 ] ) ; GENRR ( XLCR , RGADR , RGADR ) ; end (* then *) else FPA . DSPLMT := - FPA . DSPLMT ; PABI : with STK [ TOP - 1 ] do if VRBL then begin LOAD ( STK [ TOP - 1 ] ) ; GENRR ( XLPR , RGADR , RGADR ) ; end (* then *) else FPA . DSPLMT := ABS ( FPA . DSPLMT ) ; PABR : with STK [ TOP - 1 ] do begin LOAD ( STK [ TOP - 1 ] ) ; GENRR ( XLPDR , RGADR , RGADR ) end (* with *) ; PSQI : with STK [ TOP - 1 ] do begin MDTAG := PMPI ; LOAD ( STK [ TOP - 1 ] ) ; MDTAG := PBGN ; GENRR ( XMR , RGADR , RGADR + 1 ) ; AVAIL [ RGADR ] := TRUE ; RGADR := RGADR + 1 ; end (* with *) ; PSQR : with STK [ TOP - 1 ] do begin LOAD ( STK [ TOP - 1 ] ) ; GENRR ( XMDR , RGADR , RGADR ) end (* with *) ; PXPO : with STK [ TOP - 1 ] do begin FINDRG ; if VRBL then GETOPERAND ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) else LOAD ( STK [ TOP - 1 ] ) ; if ( VPA = RGS ) and DRCT then begin GENRX ( XSTD , RGADR , FL3 , GBR , 0 ) ; GENRX ( XIC , NXTRG , FL3 , GBR , 0 ) ; AVAILFP [ RGADR ] := TRUE ; end (* then *) else begin GENRX ( XIC , NXTRG , Q1 , P1 , B1 ) ; VPA := RGS ; DRCT := TRUE ; end (* else *) ; GENLA_LR ( 0 , 127 , 0 , 0 ) ; GENRR ( XNR , NXTRG , 0 ) ; GENLA_LR ( 0 , 64 , 0 , 0 ) ; GENRR ( XSR , NXTRG , 0 ) ; RGADR := NXTRG ; DTYPE := INT ; end (* with *) ; PNOT : with STK [ TOP - 1 ] do if OPNDTYPE = INT then begin LOAD ( STK [ TOP - 1 ] ) ; GENRXLIT ( XX , RGADR , - 1 , 0 ) ; end (* then *) else begin if BRCND >= 0 then if NEG_CND then (*********************) (* CLEAR NEGATE FLAG *) (*********************) begin NEG_CND := FALSE ; BRCND := - 1 ; end (* then *) else BRCND := 15 - BRCND else (***************************) (* NEGATING A BOOLEAN VLUE *) (***************************) if VRBL then begin NEG_CND := TRUE ; BRCND := 0 end (* then *) else if FPA . DSPLMT = 0 then FPA . DSPLMT := 1 else FPA . DSPLMT := 0 end (* else *) ; PODD : with STK [ TOP - 1 ] do begin if VRBL then if DRCT and ( VPA = MEM ) then begin if ODD ( FPA . DSPLMT ) then Q := 14 else Q := 1 ; FPA . DSPLMT := 0 ; GETOPERAND ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; if DTYPE = HINT then Q1 := Q1 + 1 else Q1 := Q1 + 3 ; GENSI ( XTM , Q1 , P1 , 1 ) ; (***********************************) (* RIGHT MOST BYTE IS BEING TESTED *) (***********************************) BRCND := Q ; (*************) (* BO OR BNO *) (*************) end (* then *) else begin LOAD ( STK [ TOP - 1 ] ) ; GENRXLIT ( XN , RGADR , 1 , 0 ) end (* else *) else if ODD ( FPA . DSPLMT ) then FPA . DSPLMT := 1 else FPA . DSPLMT := 0 ; DTYPE := BOOL end (* with *) ; PINC : with STK [ TOP - 1 ] do begin if PROCNAME <> ' ' then begin if FALSE then begin WRITELN ( TRACEF , '---------------------------------------' ) ; WRITELN ( TRACEF , 'INC at linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'procname = ' , PROCNAME ) ; WRITELN ( TRACEF , 'q = ' , Q ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) ; end (* then *) ; if not DRCT then begin LOAD ( STK [ TOP - 1 ] ) ; end (* then *) ; GENRXLIT ( XA , RGADR , Q , 0 ) ; //***************************************** // procname cannot be deleted here // because procedure filesetup does some // register mangling when procname is set //***************************************** end (* then *) else begin if not DRCT then begin LOAD ( STK [ TOP - 1 ] ) ; end (* then *) ; FPA . DSPLMT := FPA . DSPLMT + Q ; end (* else *) end (* with *) ; PDEC : with STK [ TOP - 1 ] do begin Q := - Q ; if not DRCT then LOAD ( STK [ TOP - 1 ] ) ; FPA . DSPLMT := FPA . DSPLMT + Q ; end (* with *) ; PCHR : with STK [ TOP - 1 ] do if DTYPE > CHRC then begin if VRBL then LOAD ( STK [ TOP - 1 ] ) ; DTYPE := CHRC end (* then *) ; PORD : with STK [ TOP - 1 ] do if DTYPE <= CHRC then begin if VRBL then LOAD ( STK [ TOP - 1 ] ) ; DTYPE := INT end (* then *) ; PNEW : begin TOP := TOP - 1 ; GENRX ( XL , TRG0 , NEWPTR , GBR , 0 ) ; GENRXLIT ( XS , TRG0 , P , 0 ) ; if Q <> 4 then (****************************) (* MUST ALIGN TO DOUBLEWORD *) (****************************) GENRXLIT ( XN , TRG0 , - 8 , 0 ) ; GENRX ( XST , TRG0 , NEWPTR , GBR , 0 ) ; if not STK [ TOP ] . DRCT then LOAD ( STK [ TOP ] ) ; GETADR ( STK [ TOP ] , Q1 , P1 , B1 ) ; GENRX ( XST , TRG0 , Q1 , B1 , P1 ) ; FREEREG ( STK [ TOP ] ) ; if DEBUG or MUSIC then (*************************************) (* CHECK FOR STACK-HEAP INTERFERENCE *) (*************************************) begin GENRXLAB ( XS , TRG0 , PIAKT -> . SEGSZE , - 1 ) ; GENRR ( XCR , TRG0 , LBR ) ; GENRR ( XBALR , RTREG , 0 ) ; GENRX ( XBC , LEQCND , STKCHK , GBR , 0 ) ; end (* then *) ; end (* tag/ca *) ; PSAV : begin TOP := TOP - 1 ; GENRX ( XL , TRG0 , NEWPTR , GBR , 0 ) ; if not STK [ TOP ] . DRCT then LOAD ( STK [ TOP ] ) ; GETADR ( STK [ TOP ] , Q1 , P1 , B1 ) ; GENRX ( XST , TRG0 , Q1 , B1 , P1 ) ; FREEREG ( STK [ TOP ] ) ; end (* tag/ca *) ; PRST : begin TOP := TOP - 1 ; with STK [ TOP ] do begin LOAD ( STK [ TOP ] ) ; if DEBUG then (*********************************) (* SEE IF NEW HEAP POINTER VALID *) (*********************************) begin if RGADR <> 2 then begin if not AVAIL [ 2 ] then ERROR ( 760 ) ; GENRR ( XLR , 2 , RGADR ) ; end (* then *) ; GENRX ( XBAL , RTREG , PTRCHK , GBR , 0 ) ; end (* then *) ; (**********************************************************) (* CODE FOR CLEARING THE RELEASE HEAP AREA SHOULD GO HERE *) (* SEE RETURN SEQUENCE 'PRET' AS AN EXAMPLE. *) (**********************************************************) GENRX ( XST , RGADR , NEWPTR , GBR , 0 ) ; AVAIL [ RGADR ] := TRUE ; end (* with *) ; end (* tag/ca *) ; PCTS : begin (************************************) (* SET/INITIALIZE RUN TIME COUNTERS *) (************************************) GENRXLAB ( XL , 2 , LBL2 , - 1 ) ; CSP := PCTR ; GOTOCSP ; end (* tag/ca *) ; PCTI : begin (****************************************) (* INCREMENT THE COUNT OF COUNTER # 'Q' *) (****************************************) GENRX ( XL , TRG1 , HEAPLMT , GBR , 0 ) ; GENLA_LR ( TRG14 , 1 , 0 , 0 ) ; Q := 4 * Q + DYN2LEN ; if Q > SHRTINT then begin GENRXLIT ( XA , TRG1 , Q , 0 ) ; Q := 0 ; end (* then *) ; GENRX ( XA , TRG14 , Q , TRG1 , 0 ) ; GENRX ( XST , TRG14 , Q , TRG1 , 0 ) ; end (* tag/ca *) ; end (* case *) ; end (* UOPERATION *) ; procedure PACK_UNPACK ( var L , R : DATUM ) ; var XOPC : BYTE ; begin (* PACK_UNPACK *) LOAD ( L ) ; (***********************) (* LOAD SOURCE ADDRESS *) (***********************) LOAD ( R ) ; (****************************) (* LOAD DESTINATION ADDRESS *) (****************************) if P = 1 then GENRR ( XSR , TRG0 , TRG0 ) ; (*********************) (*FOR BYTE INSERTIONS*) (*********************) if IVAL <= 0 then begin ERROR ( 619 ) ; IVAL := 1 end (* then *) ; FINDRG ; (***************************) (* REGISTER FOR LOOP COUNT *) (***************************) GENRXLIT ( XL , NXTRG , IVAL , 0 ) ; GENRR ( XBALR , TRG1 , 0 ) ; CSPACTIVE [ TRG1 ] := FALSE ; if P = 1 then XOPC := XIC else if P = 2 then XOPC := XLH else begin XOPC := XL ; if P <> 4 then ERROR ( 619 ) end (* else *) ; GENRX ( XOPC , TRG0 , 0 , 0 , L . RGADR ) ; if Q = 1 then XOPC := XSTC else if Q = 2 then XOPC := XSTH else begin XOPC := XST ; if Q <> 4 then ERROR ( 619 ) end (* else *) ; GENRX ( XOPC , TRG0 , 0 , 0 , R . RGADR ) ; GENLA_LR ( L . RGADR , P , 0 , L . RGADR ) ; GENLA_LR ( R . RGADR , Q , 0 , R . RGADR ) ; GENRR ( XBCTR , NXTRG , TRG1 ) ; AVAIL [ NXTRG ] := TRUE ; AVAIL [ L . RGADR ] := TRUE ; AVAIL [ R . RGADR ] := TRUE ; end (* PACK_UNPACK *) ; procedure MFIOPERATION ( var LEFT , PAT : DATUM ; LEN : INTEGER ) ; //**************************************************************** // generate overlapping MVC for short MFI // and MVCL for long MFI //**************************************************************** var P1 , B1 , P2 , B2 , PX , BX : LVLRNG ; Q1 , QX : ADRRNG ; begin (* MFIOPERATION *) if LEN > 0 then //****************************************************** // if length <= 256 generate overlapping MVC //****************************************************** if LEN <= 256 then begin //****************************************************** // get address of left operand //****************************************************** GETADR2 ( LEFT , Q1 , P1 , B1 ) ; if not LEFT . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; //****************************************************** // consolidate index and base reg to base reg b1 //****************************************************** CONS_REGS ( B1 , P1 ) ; //****************************************************** // move pattern to byte 1 //****************************************************** GEN_MOVECHAR ( Q1 , B1 , PAT ) ; //****************************************************** // operlapping MVC //****************************************************** if LEN > 1 then GENSS ( XMVC , LEN - 1 , Q1 + 1 , B1 , Q1 , B1 ) ; end (* then *) else begin //****************************************************** // get address of left operand //****************************************************** GETADR2 ( LEFT , Q1 , P1 , B1 ) ; if not LEFT . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; //****************************************************** // get init pattern //****************************************************** if FALSE then begin WRITELN ( TRACEF , '--- vor getop_simple ---' ) ; WRITELN ( TRACEF , 'linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'pat.drct = ' , PAT . DRCT ) ; WRITELN ( TRACEF , 'pat.vrbl = ' , PAT . VRBL ) ; WRITELN ( TRACEF , 'pat.dtype = ' , PAT . DTYPE ) ; WRITELN ( TRACEF , 'pat.vpa = ' , PAT . VPA ) ; WRITELN ( TRACEF , 'pat.rgadr = ' , PAT . RGADR ) ; end (* then *) ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'MVCL' INSTRUNCTION SHOULD BE // REPLACED BY A subroutine or a loop or MVC; // because the length of the operands is not // known at compile time in this case, a fix list // of MVCs is not sufficient //************************************************** if B1 < 0 then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; P2 := NXTRG ; B2 := NXTRG + 1 ; //****************************************************** // const length operand // generate LA //****************************************************** GENLA_LR ( B1 , LEN , 0 , 0 ) ; //****************************************************** // source address is zero //****************************************************** GENRR ( XXR , P2 , P2 ) ; //****************************************************** // pattern operand // generate L or LR //****************************************************** GETOP_SIMPLE ( PAT , QX , PX , BX , B2 , FALSE ) ; GENRX ( XSLL , B2 , 24 , 0 , 0 ) ; //****************************************************** // generate MVCL instruction //****************************************************** GENRR ( XMVCL , P1 , P2 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; end (* else *) ; FREEREG ( LEFT ) ; FREEREG ( PAT ) ; end (* MFIOPERATION *) ; procedure MZEOPERATION ( var L : DATUM ; LEN : INTEGER ) ; //**************************************************************** // generate XC for short MZE // and MVCL for long MZE //**************************************************************** begin (* MZEOPERATION *) if LEN > 0 then //****************************************************** // if length <= 256 generate XC //****************************************************** if LEN <= 256 then begin //****************************************************** // get address of left operand //****************************************************** GETADR ( L , Q1 , P1 , B1 ) ; if not L . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; //****************************************************** // consolidate index and base reg to base reg b1 //****************************************************** CONS_REGS ( B1 , P1 ) ; //****************************************************** // XC is used to zero the area //****************************************************** GENSS ( XXC , LEN , Q1 , B1 , Q1 , B1 ) ; end (* then *) else begin //****************************************************** // get address of left operand //****************************************************** GETADR ( L , Q1 , P1 , B1 ) ; if not L . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'MVCL' INSTRUNCTION SHOULD BE // REPLACED BY A subroutine or a loop or MVC; // because the length of the operands is not // known at compile time in this case, a fix list // of MVCs is not sufficient //************************************************** if B1 < 0 then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; P2 := NXTRG ; B2 := NXTRG + 1 ; //****************************************************** // const length operand // generate LA //****************************************************** GENLA_LR ( B1 , LEN , 0 , 0 ) ; //****************************************************** // source address is zero //****************************************************** GENRR ( XXR , P2 , P2 ) ; //****************************************************** // pattern is zero //****************************************************** GENRR ( XXR , B2 , B2 ) ; //****************************************************** // generate MVCL instruction //****************************************************** GENRR ( XMVCL , P1 , P2 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; end (* else *) ; FREEREG ( L ) ; end (* MZEOPERATION *) ; procedure MCPOPERATION ( var L , R , LEN : DATUM ) ; //**************************************************************** // generate MVCL instruction for MEMCPY // no other possibility, since length it not known // at compile time //**************************************************************** var P1 , B1 , P2 , B2 , PX , BX : LVLRNG ; Q1 , Q2 , QX : ADRRNG ; BPC : ICRNG ; begin (* MCPOPERATION *) //****************************************************** // get address of left operand //****************************************************** GETADR2 ( L , Q1 , P1 , B1 ) ; if not L . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; TXRG := TRG1 ; //****************************************************** // TO AVOID REASSIGNM. OF THE SAME BASE REG //****************************************************** CSPACTIVE [ TRG1 ] := FALSE ; // INDICATES LOSS OF TRG1 //****************************************************** // get address of right operand //****************************************************** GETADR2 ( R , Q2 , P2 , B2 ) ; if not R . DRCT then begin GENRX ( XL , TXRG , Q2 , B2 , P2 ) ; Q2 := 0 ; B2 := 0 ; P2 := TXRG ; end (* then *) ; TXRG := TRG14 ; //****************************************************** // get length //****************************************************** if FALSE then begin WRITELN ( TRACEF , '--- vor getop_simple ---' ) ; WRITELN ( TRACEF , 'linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'len.drct = ' , LEN . DRCT ) ; WRITELN ( TRACEF , 'len.vrbl = ' , LEN . VRBL ) ; WRITELN ( TRACEF , 'len.dtype = ' , LEN . DTYPE ) ; WRITELN ( TRACEF , 'len.vpa = ' , LEN . VPA ) ; WRITELN ( TRACEF , 'len.rgadr = ' , LEN . RGADR ) ; end (* then *) ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; if P2 < 0 then begin B2 := P2 ; P2 := 0 ; end (* then *) ; //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'MVCL' INSTRUNCTION SHOULD BE // REPLACED BY A subroutine or a loop or MVC; // because the length of the operands is not // known at compile time in this case, a fix list // of MVCs is not sufficient //************************************************** if ( B1 < 0 ) or ( B2 < 0 ) then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; GENLA_LR ( NXTRG , Q2 , B2 , P2 ) ; P2 := NXTRG ; B2 := NXTRG + 1 ; //****************************************************** // length operand // generate L or LR //****************************************************** GETOP_SIMPLE ( LEN , QX , PX , BX , B1 , TRUE ) ; //****************************************************** // copy length in register b1 to register b2 // and test //****************************************************** GENRR ( XLTR , B2 , B1 ) ; //****************************************************** // check length for positive // address of branch will be filled in later //****************************************************** GENRX ( XBC , LEQCND , 0 , 0 , 0 ) ; BPC := PCOUNTER ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'BNP @NOMV' ) ; LIST002_NEWLINE ; end (* then *) ; //****************************************************** // generate MVCL instruction //****************************************************** GENRR ( XMVCL , P1 , P2 ) ; //****************************************************** // generate label after MVCL //****************************************************** CODE . H [ BPC - 1 ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER ) ) ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASML , '@NOMV DS 0H' ) ; LIST002_NEWLINE ; end (* then *) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; FREEREG ( L ) ; FREEREG ( R ) ; FREEREG ( LEN ) ; end (* MCPOPERATION *) ; procedure MSEOPERATION ( var L , PAT , LEN : DATUM ; REVERSE : INTEGER ) ; //**************************************************************** // generate MVCL instruction for MEMSET // no other possibility, since length it not known // at compile time //**************************************************************** var P1 , B1 , P2 , B2 , PX , BX : LVLRNG ; Q1 , QX : ADRRNG ; BPC : ICRNG ; XPAT , XLEN : DATUM ; begin (* MSEOPERATION *) //****************************************************** // get address of left operand //****************************************************** if REVERSE > 0 then begin XPAT := LEN ; XLEN := PAT ; end (* then *) else begin XPAT := PAT ; XLEN := LEN ; end (* else *) ; //****************************************************** // get address of left operand //****************************************************** GETADR ( L , Q1 , P1 , B1 ) ; if not L . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; //****************************************************** // get init pattern //****************************************************** if FALSE then begin WRITELN ( TRACEF , '--- vor getop_simple ---' ) ; WRITELN ( TRACEF , 'linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'pat.drct = ' , XPAT . DRCT ) ; WRITELN ( TRACEF , 'pat.vrbl = ' , XPAT . VRBL ) ; WRITELN ( TRACEF , 'pat.dtype = ' , XPAT . DTYPE ) ; WRITELN ( TRACEF , 'pat.vpa = ' , XPAT . VPA ) ; WRITELN ( TRACEF , 'pat.rgadr = ' , XPAT . RGADR ) ; end (* then *) ; //****************************************************** // get length //****************************************************** if FALSE then begin WRITELN ( TRACEF , '--- vor getop_simple ---' ) ; WRITELN ( TRACEF , 'linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'len.drct = ' , XLEN . DRCT ) ; WRITELN ( TRACEF , 'len.vrbl = ' , XLEN . VRBL ) ; WRITELN ( TRACEF , 'len.dtype = ' , XLEN . DTYPE ) ; WRITELN ( TRACEF , 'len.vpa = ' , XLEN . VPA ) ; WRITELN ( TRACEF , 'len.rgadr = ' , XLEN . RGADR ) ; end (* then *) ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'MVCL' INSTRUNCTION SHOULD BE // REPLACED BY A subroutine or a loop or MVC; // because the length of the operands is not // known at compile time in this case, a fix list // of MVCs is not sufficient //************************************************** if B1 < 0 then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; P2 := NXTRG ; B2 := NXTRG + 1 ; //****************************************************** // length operand // generate L or LR //****************************************************** GETOP_SIMPLE ( XLEN , QX , PX , BX , B1 , TRUE ) ; //****************************************************** // check length for positive // address of branch will be filled in later *) //****************************************************** GENRR ( XLTR , B1 , B1 ) ; GENRX ( XBC , LEQCND , 0 , 0 , 0 ) ; BPC := PCOUNTER ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASMX , 'BNP @NOMV' ) ; LIST002_NEWLINE ; end (* then *) ; //****************************************************** // source address is zero //****************************************************** GENRR ( XXR , P2 , P2 ) ; //****************************************************** // pattern operand // generate L or LR //****************************************************** GETOP_SIMPLE ( XPAT , QX , PX , BX , B2 , FALSE ) ; GENRX ( XSLL , B2 , 24 , 0 , 0 ) ; //****************************************************** // generate MVCL instruction //****************************************************** GENRR ( XMVCL , P1 , P2 ) ; //****************************************************** // generate label after MVCL //****************************************************** CODE . H [ BPC - 1 ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER ) ) ; if ASM then begin WRITE ( LIST002 , ' ' , '## ' , ' ' : SPACEASML , '@NOMV DS 0H' ) ; LIST002_NEWLINE ; end (* then *) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; FREEREG ( L ) ; FREEREG ( XPAT ) ; FREEREG ( XLEN ) ; end (* MSEOPERATION *) ; procedure MCVOPERATION ( var L , R , LEN : DATUM ) ; //**************************************************************** // generate CLCL instruction for MEMCMP // length is not known at compile time //**************************************************************** var P1 , B1 , P2 , B2 , PX , BX : LVLRNG ; Q1 , Q2 , QX : ADRRNG ; TARGET_REG : RGRNG ; begin (* MCVOPERATION *) //****************************************************** // get address of left operand //****************************************************** GETADR2 ( L , Q1 , P1 , B1 ) ; if not L . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; TXRG := TRG1 ; //****************************************************** // TO AVOID REASSIGNM. OF THE SAME BASE REG //****************************************************** CSPACTIVE [ TRG1 ] := FALSE ; // INDICATES LOSS OF TRG1 //****************************************************** // get address of right operand //****************************************************** GETADR2 ( R , Q2 , P2 , B2 ) ; if not R . DRCT then begin GENRX ( XL , TXRG , Q2 , B2 , P2 ) ; Q2 := 0 ; B2 := 0 ; P2 := TXRG ; end (* then *) ; TXRG := TRG14 ; //****************************************************** // get length //****************************************************** if FALSE then begin WRITELN ( TRACEF , '--- vor getop_simple ---' ) ; WRITELN ( TRACEF , 'linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'len.drct = ' , LEN . DRCT ) ; WRITELN ( TRACEF , 'len.vrbl = ' , LEN . VRBL ) ; WRITELN ( TRACEF , 'len.dtype = ' , LEN . DTYPE ) ; WRITELN ( TRACEF , 'len.vpa = ' , LEN . VPA ) ; WRITELN ( TRACEF , 'len.rgadr = ' , LEN . RGADR ) ; end (* then *) ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; if P2 < 0 then begin B2 := P2 ; P2 := 0 ; end (* then *) ; //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'MVCL' INSTRUNCTION SHOULD BE // REPLACED BY A subroutine or a loop or MVC; // because the length of the operands is not // known at compile time in this case, a fix list // of MVCs is not sufficient //************************************************** if ( B1 < 0 ) or ( B2 < 0 ) then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; GENLA_LR ( NXTRG , Q2 , B2 , P2 ) ; P2 := NXTRG ; B2 := NXTRG + 1 ; //****************************************************** // find number of target register and // generate code to set target register to zero // before doing the comparison //****************************************************** FINDRG ; TARGET_REG := NXTRG ; GENRR ( XXR , TARGET_REG , TARGET_REG ) ; //****************************************************** // length operand // generate L or LR //****************************************************** GETOP_SIMPLE ( LEN , QX , PX , BX , B1 , TRUE ) ; //****************************************************** // copy length in register b1 to register b2 // and test //****************************************************** GENRR ( XLTR , B2 , B1 ) ; //****************************************************** // check length for positive // address of branch will be filled in later //****************************************************** GENRELRX ( XBC , LEQCND , 10 ) ; //****************************************************** // generate CLCL instruction //****************************************************** GENRR ( XCLCL , P1 , P2 ) ; //****************************************************** // set result in target rec depending on CC //****************************************************** GENRELRX ( XBC , EQUCND , 7 ) ; GENRR ( XBCTR , TARGET_REG , 0 ) ; GENRELRX ( XBC , LESCND , 4 ) ; GENLA_LR ( TARGET_REG , 1 , 0 , 0 ) ; //****************************************************** // free temporary registers //****************************************************** AVAIL [ TARGET_REG ] := TRUE ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; FREEREG ( L ) ; FREEREG ( R ) ; FREEREG ( LEN ) ; //****************************************************** // result is in top stack element (register) //****************************************************** with L do begin DTYPE := INT ; PLEN := 0 ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := TARGET_REG ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; end (* MCVOPERATION *) ; procedure MCCOPERATION ( var L , R : DATUM ; LEN : INTEGER ) ; //**************************************************************** // generate CLC or CLCL instruction for MEMCMP // length is known at compile time //**************************************************************** var P1 , B1 , P2 , B2 : LVLRNG ; Q1 , Q2 : ADRRNG ; TARGET_REG : RGRNG ; begin (* MCCOPERATION *) //****************************************************** // get address of left operand //****************************************************** GETADR2 ( L , Q1 , P1 , B1 ) ; if not L . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; TXRG := TRG1 ; //****************************************************** // TO AVOID REASSIGNM. OF THE SAME BASE REG //****************************************************** CSPACTIVE [ TRG1 ] := FALSE ; // INDICATES LOSS OF TRG1 //****************************************************** // get address of right operand //****************************************************** GETADR2 ( R , Q2 , P2 , B2 ) ; if not R . DRCT then begin GENRX ( XL , TXRG , Q2 , B2 , P2 ) ; Q2 := 0 ; B2 := 0 ; P2 := TXRG ; end (* then *) ; TXRG := TRG14 ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; if P2 < 0 then begin B2 := P2 ; P2 := 0 ; end (* then *) ; //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'MVCL' INSTRUNCTION SHOULD BE // REPLACED BY A subroutine or a loop or MVC; // because the length of the operands is not // known at compile time in this case, a fix list // of MVCs is not sufficient //************************************************** if ( B1 < 0 ) or ( B2 < 0 ) then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; GENLA_LR ( NXTRG , Q2 , B2 , P2 ) ; P2 := NXTRG ; B2 := NXTRG + 1 ; //****************************************************** // find number of target register and // generate code to set target register to zero // before doing the comparison //****************************************************** FINDRG ; TARGET_REG := NXTRG ; GENRR ( XXR , TARGET_REG , TARGET_REG ) ; //****************************************************** // don't generate compare instructions, // if length is less or equal to zero // generate CLC, if length <= 256 // otherwise CLCL //****************************************************** if LEN > 0 then if LEN <= 256 then begin GENSS ( XCLC , LEN , 0 , P1 , 0 , P2 ) ; end (* then *) else begin //****************************************************** // copy length in register b1 to register b2 // and test //****************************************************** GENLA_LR ( B1 , LEN , 0 , 0 ) ; GENRR ( XLR , B2 , B1 ) ; //****************************************************** // generate CLCL instruction //****************************************************** GENRR ( XCLCL , P1 , P2 ) ; end (* else *) ; //****************************************************** // set result in target rec depending on CC //****************************************************** GENRELRX ( XBC , EQUCND , 7 ) ; GENRR ( XBCTR , TARGET_REG , 0 ) ; GENRELRX ( XBC , LESCND , 4 ) ; GENLA_LR ( TARGET_REG , 1 , 0 , 0 ) ; //****************************************************** // free temporary registers //****************************************************** AVAIL [ TARGET_REG ] := TRUE ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; FREEREG ( L ) ; FREEREG ( R ) ; //****************************************************** // result is in top stack element (register) //****************************************************** with L do begin DTYPE := INT ; PLEN := 0 ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := TARGET_REG ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; end (* MCCOPERATION *) ; procedure STROPERATION_MVI ( var LEFT : DATUM ; CCONST : CHAR ) ; //**************************************************************** // MVI to string target / implement VST after VC1 //**************************************************************** var P1 , B1 : LVLRNG ; Q1 : ADRRNG ; begin (* STROPERATION_MVI *) //****************************************************** // get address of left operand //****************************************************** GETADR2 ( LEFT , Q1 , P1 , B1 ) ; if not LEFT . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; CONS_REGS ( B1 , P1 ) ; GENSI ( XMVI , Q1 , B1 , ORD ( CCONST ) ) ; end (* STROPERATION_MVI *) ; procedure STROPERATION_MVC1 ( var TARGET : DATUM ; var SOURCE : DATUM ) ; //**************************************************************** // MVC to string target / implement VST after VC1 //**************************************************************** var P1 , B1 : LVLRNG ; Q1 : ADRRNG ; begin (* STROPERATION_MVC1 *) if FALSE then begin WRITELN ( TRACEF , 'start STROPERATION_MVC1, linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Target' , TARGET ) ; DUMPSTKELEM ( 'Source' , SOURCE ) ; end (* then *) ; //****************************************************** // get address of left operand //****************************************************** GETADR2 ( TARGET , Q1 , P1 , B1 ) ; if not TARGET . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; CONS_REGS ( B1 , P1 ) ; GEN_MOVECHAR ( Q1 , B1 , SOURCE ) ; end (* STROPERATION_MVC1 *) ; procedure COMPARE_CARR ( var LEFT , RIGHT : DATUM ; LENL , LENR : INTEGER ; COMPTYPE : CHAR ) ; //**************************************************************** // generate code FOR CHAR ARRAY COMPARE OPERATION (not string!) //**************************************************************** // 2020.12: two lenghts, lengths may be different and zero // 2020.12: comptype may be M, 1 and 2 // 2020.12: if M, both sides are char arrays // 2020.12: if 1, left side is single char, not char pointer // 2020.12: if 2, right side is single char, not char pointer //**************************************************************** var P1 , B1 , P2 , B2 : LVLRNG ; Q1 , Q2 : ADRRNG ; GEN_LIT_LINKS , GEN_LIT_RECHTS : BOOLEAN ; begin (* COMPARE_CARR *) if FALSE then begin WRITELN ( TRACEF , 'start compare_carr, linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Left ' , LEFT ) ; DUMPSTKELEM ( 'Right' , RIGHT ) ; WRITELN ( TRACEF , 'lenl = ' , LENL ) ; WRITELN ( TRACEF , 'lenr = ' , LENR ) ; WRITELN ( TRACEF , 'comptype = ' , COMPTYPE ) ; end (* then *) ; //****************************************************** // if comptype = '1' then // left operand is single char // if memory operand, change attributes of stack element // else (constant) generate MVI to scratchpad area // and set attributes of stack element to address there //****************************************************** if COMPTYPE = '1' then begin COMPTYPE := 'M' ; if LEFT . VPA = MEM then begin LEFT . DTYPE := ADR ; LEFT . FPA := LEFT . MEMADR ; LEFT . VPA := NEITHER ; LEFT . VRBL := FALSE ; end (* then *) else begin GENSI ( XMVI , PIAKT -> . SCRATCHPOS , LBR , LEFT . FPA . DSPLMT ) ; P1 := LBR ; Q1 := PIAKT -> . SCRATCHPOS ; LEFT . DTYPE := ADR ; LEFT . FPA . LVL := CURLVL ; LEFT . FPA . DSPLMT := PIAKT -> . SCRATCHPOS ; end (* else *) ; if FALSE then begin WRITELN ( TRACEF , 'nach Modifikation:' ) ; DUMPSTKELEM ( 'Left ' , LEFT ) ; end (* then *) end (* then *) ; //****************************************************** // if comptype = '2' then // do the same for the right operand //****************************************************** if COMPTYPE = '2' then begin COMPTYPE := 'M' ; if RIGHT . VPA = MEM then begin RIGHT . DTYPE := ADR ; RIGHT . FPA := RIGHT . MEMADR ; RIGHT . VPA := NEITHER ; RIGHT . VRBL := FALSE ; end (* then *) else begin GENSI ( XMVI , PIAKT -> . SCRATCHPOS , LBR , RIGHT . FPA . DSPLMT ) ; P2 := LBR ; Q2 := PIAKT -> . SCRATCHPOS ; RIGHT . DTYPE := ADR ; RIGHT . FPA . LVL := CURLVL ; RIGHT . FPA . DSPLMT := PIAKT -> . SCRATCHPOS ; end (* else *) ; if FALSE then begin WRITELN ( TRACEF , 'nach Modifikation:' ) ; DUMPSTKELEM ( 'Right' , RIGHT ) ; end (* then *) end (* then *) ; //****************************************************** // get address of left operand //****************************************************** if LENL > 0 then begin GETADR2 ( LEFT , Q1 , P1 , B1 ) ; if FALSE then WRITELN ( TRACEF , 'getadr left, q1, p1, b1 = ' , Q1 : 6 , P1 : 6 , B1 : 6 ) ; if not LEFT . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; if FALSE then WRITELN ( TRACEF , 'load txrg, q1, p1, b1 = ' , Q1 : 6 , P1 : 6 , B1 : 6 ) ; end (* then *) ; TXRG := TRG1 ; //****************************************************** // TO AVOID REASSIGNM. OF THE SAME BASE REG //****************************************************** CSPACTIVE [ TRG1 ] := FALSE ; // INDICATES LOSS OF TRG1 end (* then *) ; //****************************************************** // get address of right operand //****************************************************** if LENR > 0 then begin GETADR2 ( RIGHT , Q2 , P2 , B2 ) ; if FALSE then WRITELN ( TRACEF , 'getadr right, q2, p2, b2 = ' , Q2 : 6 , P2 : 6 , B2 : 6 ) ; if not RIGHT . DRCT then begin GENRX ( XL , TXRG , Q2 , B2 , P2 ) ; Q2 := 0 ; B2 := 0 ; P2 := TXRG ; if FALSE then WRITELN ( TRACEF , 'load txrg, q2, p2, b2 = ' , Q2 : 6 , P2 : 6 , B2 : 6 ) ; end (* then *) ; TXRG := TRG14 ; end (* then *) ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** // if p1 or p2 < 0 (that is: literal) // move px to bx and set px to zero //****************************************************** if LENL > 0 then if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; if LENR > 0 then if P2 < 0 then begin B2 := P2 ; P2 := 0 ; end (* then *) ; if FALSE then begin WRITELN ( TRACEF , 'after restore, q1, p1, b1 = ' , Q1 : 6 , P1 : 6 , B1 : 6 ) ; WRITELN ( TRACEF , 'after restore, q2, p2, b2 = ' , Q2 : 6 , P2 : 6 , B2 : 6 ) ; end (* then *) ; //****************************************************** // SHORT MOVE = length (q) <= 256 // 2020.12: if lenl <> lenr, use CLCL //****************************************************** // if px and bx both greater zero // generate AR instructions for px // bx is no longer needed // otherwise if bx less than zero // generate literals //****************************************************** if ( LENL > 0 ) and ( LENL <= 256 ) and ( LENL = LENR ) then begin if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; if B2 > 0 then if P2 > 0 then GENRR ( XAR , P2 , B2 ) else P2 := B2 ; GENSS ( XCLC , LENL , Q1 , P1 , Q2 , P2 ) ; if B1 < 0 then begin if FALSE then begin WRITELN ( TRACEF , 'sop lit links, b1 = ' , B1 ) ; WRITELN ( TRACEF , 'sop lit links, index = ' , LEFT . SCNSTNO ) ; WRITELN ( TRACEF , 'sop cod links, pcnt = ' , PCOUNTER - 2 ) ; WRITELN ( TRACEF , 'sop cod links, code = ' , TO_HINT ( Q1 ) ) end (* then *) ; if B1 = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 3 - index = ' , LEFT . SCNSTNO : 1 , ' pc = ' , PCOUNTER - 2 : 1 ) ; LITTBL [ LEFT . SCNSTNO ] . LNK := PCOUNTER - 2 ; end (* then *) ; CODE . H [ PCOUNTER - 2 ] := TO_HINT ( Q1 ) ; end (* then *) ; if B2 < 0 then begin if FALSE then begin WRITELN ( TRACEF , 'sop lit rechts, b2 = ' , B2 ) ; WRITELN ( TRACEF , 'sop lit rechts, index = ' , RIGHT . SCNSTNO ) ; WRITELN ( TRACEF , 'sop cod rechts, pcnt = ' , PCOUNTER - 1 ) ; WRITELN ( TRACEF , 'sop cod rechts, code = ' , TO_HINT ( Q2 ) ) end (* then *) ; if B2 = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 4 - index = ' , RIGHT . SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ RIGHT . SCNSTNO ] . LNK := PCOUNTER - 1 ; end (* then *) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q2 ) ; end (* then *) ; end (* then *) //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'CLCL' INSTRUCTION SHOULD BE // REPLACED BY AN APPROPRIATE NUMBER OF 'CLC'S //************************************************** else begin if FALSE then begin WRITELN ( TRACEF , 'start gen CLCL' ) ; WRITELN ( TRACEF , 'lenl, b1 = ' , LENL , B1 ) ; WRITELN ( TRACEF , 'lenr, b2 = ' , LENR , B2 ) ; end (* then *) ; //************************************** // check if literals must be generated //************************************** GEN_LIT_LINKS := FALSE ; if LENL > 0 then if B1 < 0 then GEN_LIT_LINKS := TRUE ; GEN_LIT_RECHTS := FALSE ; if LENR > 0 then if B2 < 0 then GEN_LIT_RECHTS := TRUE ; FINDRP ; if LENL > 0 then begin if FALSE then WRITELN ( TRACEF , 'gen la - nxtrg = ' , NXTRG : 1 , ' ' , Q1 : 1 , ' ' , B1 : 1 , ' ' , P1 : 1 ) ; if GEN_LIT_LINKS then begin GENLA_LR ( NXTRG , Q1 , 0 , P1 ) ; if B1 = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 5 - index = ' , LEFT . SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ LEFT . SCNSTNO ] . LNK := PCOUNTER - 1 end (* then *) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q1 ) ; end (* then *) else GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; end (* then *) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; if LENR > 0 then begin if GEN_LIT_RECHTS then begin GENLA_LR ( NXTRG , Q2 , 0 , P2 ) ; if B2 = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 6 - index = ' , RIGHT . SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ RIGHT . SCNSTNO ] . LNK := PCOUNTER - 1 end (* then *) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q2 ) ; end (* then *) else GENLA_LR ( NXTRG , Q2 , B2 , P2 ) ; end (* then *) ; P2 := NXTRG ; B2 := NXTRG + 1 ; if LENR = LENL then begin GENRXLIT ( XL , B1 , LENL , 0 ) ; GENRR ( XLR , B2 , B1 ) end (* then *) else begin GENRXLIT ( XL , B1 , LENL , 0 ) ; GENRXLIT ( XL , B2 , 0x40 * SL24 , 0 ) ; GENRXLIT ( XA , B2 , LENR , 0 ) ; end (* else *) ; GENRR ( XCLCL , P1 , P2 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; if FALSE then WRITELN ( TRACEF , 'end gen CLCL' ) ; end (* else *) ; FREEREG ( LEFT ) ; FREEREG ( RIGHT ) ; end (* COMPARE_CARR *) ; procedure SOPERATION ( var LEFT , RIGHT : DATUM ; PCODEPARM : OPTYPE ; LENPARM : INTEGER ) ; //**************************************************************** // SET UP FOR STRING MOVE OPERATIONS //**************************************************************** var P1 , B1 , P2 , B2 : LVLRNG ; Q1 , Q2 : ADRRNG ; XOPC : BYTE ; begin (* SOPERATION *) if PCODEPARM <> PMOV then begin WRITELN ( 'soperation: pcodeparm = ' , PCODEPARM ) ; ERROR ( 720 ) end (* then *) ; //****************************************************** // get address of left operand //****************************************************** GETADR2 ( LEFT , Q1 , P1 , B1 ) ; if not LEFT . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; TXRG := TRG1 ; //****************************************************** // TO AVOID REASSIGNM. OF THE SAME BASE REG //****************************************************** CSPACTIVE [ TRG1 ] := FALSE ; // INDICATES LOSS OF TRG1 //****************************************************** // get address of right operand //****************************************************** GETADR2 ( RIGHT , Q2 , P2 , B2 ) ; if not RIGHT . DRCT then begin GENRX ( XL , TXRG , Q2 , B2 , P2 ) ; Q2 := 0 ; B2 := 0 ; P2 := TXRG ; end (* then *) ; TXRG := TRG14 ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; if P2 < 0 then begin B2 := P2 ; P2 := 0 ; end (* then *) ; //****************************************************** // SHORT MOVE = length (q) <= 256 //****************************************************** if ( LENPARM > 0 ) and ( LENPARM <= 256 ) then begin if B1 > 0 then if P1 > 0 then GENRR ( XAR , P1 , B1 ) else P1 := B1 ; if B2 > 0 then if P2 > 0 then GENRR ( XAR , P2 , B2 ) else P2 := B2 ; XOPC := XMVC ; if PCODEPARM <> PMOV then XOPC := XCLC ; GENSS ( XOPC , LENPARM , Q1 , P1 , Q2 , P2 ) ; if B1 < 0 then begin if FALSE then begin WRITELN ( 'sop lit links, b1 = ' , B1 ) ; WRITELN ( 'sop lit links, index = ' , LEFT . SCNSTNO ) ; WRITELN ( 'sop cod links, pcnt = ' , PCOUNTER - 2 ) ; WRITELN ( 'sop cod links, code = ' , TO_HINT ( Q1 ) ) end (* then *) ; if B1 = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 7 - index = ' , LEFT . SCNSTNO : 1 , ' pc = ' , PCOUNTER - 2 : 1 ) ; LITTBL [ LEFT . SCNSTNO ] . LNK := PCOUNTER - 2 ; end (* then *) ; CODE . H [ PCOUNTER - 2 ] := TO_HINT ( Q1 ) ; end (* then *) ; if B2 < 0 then begin if FALSE then begin WRITELN ( 'sop lit rechts, b2 = ' , B2 ) ; WRITELN ( 'sop lit rechts, index = ' , RIGHT . SCNSTNO ) ; WRITELN ( 'sop cod rechts, pcnt = ' , PCOUNTER - 1 ) ; WRITELN ( 'sop cod rechts, code = ' , TO_HINT ( Q2 ) ) end (* then *) ; if B2 = - 1 then begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 8 - index = ' , RIGHT . SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ RIGHT . SCNSTNO ] . LNK := PCOUNTER - 1 ; end (* then *) ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q2 ) ; end (* then *) ; if OPT_FLG then if XOPC = XMVC then with LAST_MVC do begin if PCOUNTER = ( LAST_PC + 3 ) then //****************************************************** // CONSECUTIVE MVC INSTS // check if new MVC can be eliminated by changing // length of previous MVC //****************************************************** if ( CODE . H [ LAST_PC - 2 ] + LLEN ) = CODE . H [ PCOUNTER - 2 ] then if ( CODE . H [ LAST_PC - 1 ] + LLEN ) = CODE . H [ PCOUNTER - 1 ] then if ( LLEN + LENPARM ) <= 256 then begin if ASM then begin HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- instruction is not' ) ; LIST002_NEWLINE ; HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- generated; length' ) ; LIST002_NEWLINE ; HEXHW ( PCOUNTER * 2 , HEXPC ) ; WRITE ( LIST002 , ' ' , ASMTAG , HEXPC , ': ' ) ; WRITE ( LIST002 , '*' , ' ' : 26 , '-- of prev. instr. changed' ) ; LIST002_NEWLINE ; end (* then *) ; CODE . H [ LAST_PC - 3 ] := TO_HINT ( CODE . H [ LAST_PC - 3 ] + LENPARM ) ; LENPARM := LENPARM + LLEN ; PCOUNTER := LAST_PC ; if B2 = - 1 then if RIGHT . SCNSTNO = NXTLIT - 1 then NXTLIT := NXTLIT - 1 else begin if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 9 - index = ' , RIGHT . SCNSTNO : 1 , ' pc = ' , 0 : 1 ) ; if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 10 - index = ' , RIGHT . SCNSTNO : 1 , ' optimized ' ) ; LITTBL [ RIGHT . SCNSTNO ] . LNK := 0 ; LITTBL [ RIGHT . SCNSTNO ] . OPTIMIZED := TRUE end (* else *) ; end (* then *) ; LAST_PC := PCOUNTER ; LLEN := LENPARM ; end (* with *) ; end (* then *) //************************************************** // THIS IS ONLY VALID FOR THE 370, // FOR THE 360 THE 'CLCL' INSTRUCTION SHOULD BE // REPLACED BY AN APPROPRIATE NUMBER OF 'CLC'S //************************************************** else begin if ( B1 < 0 ) or ( B2 < 0 ) then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; GENLA_LR ( NXTRG , Q2 , B2 , P2 ) ; P2 := NXTRG ; B2 := NXTRG + 1 ; GENRXLIT ( XL , B1 , LENPARM , 0 ) ; GENRR ( XLR , B2 , B1 ) ; XOPC := XMVCL ; if PCODEPARM <> PMOV then XOPC := XCLCL ; GENRR ( XOPC , P1 , P2 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; end (* else *) ; FREEREG ( LEFT ) ; FREEREG ( RIGHT ) ; end (* SOPERATION *) ; procedure STROPERATION_LEN ( var LEFT , RIGHT : DATUM ; PCODEPARM : OPTYPE ; LEN_REG : RGRNG ; LEN_OFFS : ADRRNG ; STR_ADDRMODE : INTEGER ) ; //**************************************************************** // SET UP FOR STRING MOVE/COMPARE OPERATIONS // if len_reg < 0, len_reg contains length // otherwise: len_reg and len_offs contain address of 2 byte // length field //**************************************************************** var P1 , B1 , P2 , B2 : LVLRNG ; Q1 , Q2 : ADRRNG ; XOPC : BYTE ; begin (* STROPERATION_LEN *) //****************************************************** // get address of left operand //****************************************************** GETADR2 ( LEFT , Q1 , P1 , B1 ) ; if not LEFT . DRCT then begin GENRX ( XL , TXRG , Q1 , B1 , P1 ) ; Q1 := 0 ; B1 := 0 ; P1 := TXRG ; end (* then *) ; TXRG := TRG1 ; //****************************************************** // TO AVOID REASSIGNM. OF THE SAME BASE REG //****************************************************** CSPACTIVE [ TRG1 ] := FALSE ; // INDICATES LOSS OF TRG1 //****************************************************** // get address of right operand //****************************************************** GETADR2 ( RIGHT , Q2 , P2 , B2 ) ; if not RIGHT . DRCT then begin GENRX ( XL , TXRG , Q2 , B2 , P2 ) ; Q2 := 0 ; B2 := 0 ; P2 := TXRG ; end (* then *) ; TXRG := TRG14 ; //****************************************************** // RESTORE THE OLD MIDLEVEL BASE REG //****************************************************** if P1 < 0 then begin B1 := P1 ; P1 := 0 ; end (* then *) ; if P2 < 0 then begin B2 := P2 ; P2 := 0 ; end (* then *) ; if ( B1 < 0 ) or ( B2 < 0 ) then ERROR ( 202 ) ; FINDRP ; GENLA_LR ( NXTRG , Q1 , P1 , B1 ) ; P1 := NXTRG ; B1 := NXTRG + 1 ; FINDRP ; if STR_ADDRMODE > 0 then GENLA_LR ( NXTRG , Q2 , P2 , B2 ) else if STR_ADDRMODE < 0 then GENRX ( XL , NXTRG , Q2 , P2 , B2 ) else begin GENLA_LR ( NXTRG , Q2 , P2 , B2 ) ; GENRX ( XLH , NXTRG + 1 , Q2 - 4 , P2 , B2 ) ; GENRR ( XLTR , NXTRG + 1 , NXTRG + 1 ) ; GENRELRX ( XBC , GEQCND , 4 ) ; GENRX ( XL , NXTRG , Q2 , P2 , B2 ) ; end (* else *) ; P2 := NXTRG ; B2 := NXTRG + 1 ; if LEN_REG < 0 then GENRR ( XLR , B1 , - LEN_REG ) else GENRX ( XLH , B1 , LEN_OFFS , LEN_REG , 0 ) ; GENRR ( XLR , B2 , B1 ) ; XOPC := XMVCL ; if PCODEPARM <> PMOV then XOPC := XCLCL ; GENRR ( XOPC , P1 , P2 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; FREEREG ( LEFT ) ; FREEREG ( RIGHT ) ; end (* STROPERATION_LEN *) ; procedure ASSIGN_STRING ( TARGET , SOURCE : DATUM ; LEN_REG : RGRNG ; LEN_OFFS : ADRRNG ; STR_ADDRMODE : INTEGER ; INCR_TARGET : BOOLEAN ; INCR_SOURCE : BOOLEAN ) ; //**************************************************************** // assign_string: // different variants of string assignment // single characters (s..MVC1, s..MVI) // string operation controlled by length field (s..len) // constant moves (soperation) //**************************************************************** begin (* ASSIGN_STRING *) if FALSE then begin WRITELN ( TRACEF , 'start assign_string, linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Target' , TARGET ) ; DUMPSTKELEM ( 'Source' , SOURCE ) ; WRITELN ( TRACEF , 'len_reg = ' , LEN_REG ) ; WRITELN ( TRACEF , 'len_offs = ' , LEN_OFFS ) ; end (* then *) ; if INCR_TARGET then if TARGET . DTYPE = VARC then TARGET . FPA . DSPLMT := TARGET . FPA . DSPLMT + 4 ; if INCR_SOURCE then if SOURCE . DTYPE = VARC then SOURCE . FPA . DSPLMT := SOURCE . FPA . DSPLMT + 4 ; if SOURCE . DTYPE = CHRC then begin if SOURCE . VRBL then begin if FALSE then WRITELN ( TRACEF , 'STROPERATION_MVC1' ) ; STROPERATION_MVC1 ( TARGET , SOURCE ) end (* then *) else begin if FALSE then WRITELN ( TRACEF , 'STROPERATION_MVI' ) ; STROPERATION_MVI ( TARGET , CHR ( SOURCE . FPA . DSPLMT ) ) ; end (* else *) ; return end (* then *) ; if LEN_REG <> 0 then begin if FALSE then WRITELN ( TRACEF , 'STROPERATION_LEN' ) ; STROPERATION_LEN ( TARGET , SOURCE , PMOV , LEN_REG , LEN_OFFS , STR_ADDRMODE ) ; return ; end (* then *) ; if FALSE then WRITELN ( TRACEF , 'SOPERATION' ) ; SOPERATION ( TARGET , SOURCE , PMOV , SOURCE . PLEN ) ; end (* ASSIGN_STRING *) ; procedure STRING_GET_ACTLEN ( S : DATUM ; NEW_REG : BOOLEAN ; var TARGET_REG : RGRNG ; GEN_ADD : BOOLEAN ) ; begin (* STRING_GET_ACTLEN *) //****************************************************** // generate instructions to fetch actual length // into target register //****************************************************** if NEW_REG then begin FINDRG ; TARGET_REG := NXTRG end (* then *) ; if FALSE then begin WRITELN ( TRACEF , 'start STRING_GET_ACTLEN, linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'S = ' , S ) ; end (* then *) ; with S do begin GETADR2 ( S , Q2 , P2 , B2 ) ; if FALSE then begin WRITELN ( TRACEF , 'after getadr2' ) ; WRITELN ( TRACEF , 'p2 = ' , P2 : 4 ) ; WRITELN ( TRACEF , 'q2 = ' , Q2 : 4 ) ; WRITELN ( TRACEF , 'b2 = ' , B2 : 4 ) ; end (* then *) ; if GEN_ADD then GENRX ( XAH , TARGET_REG , 2 + Q2 , B2 , P2 ) else GENRX ( XLH , TARGET_REG , 2 + Q2 , B2 , P2 ) end (* with *) end (* STRING_GET_ACTLEN *) ; procedure STRINGOPS ; var P1 , B1 , P2 , B2 : LVLRNG ; Q1 , Q2 : ADRRNG ; PX , BX : LVLRNG ; QX : ADRRNG ; B : LVLRNG ; MAXL : INTEGER ; LEN : INTEGER ; COPYSTRING : BOOLEAN ; RGWORK : RGRNG ; RGWORK1 : RGRNG ; RGWORK2 : RGRNG ; PATBLANK : DATUM ; LITVALUE : INTEGER ; DATWORKAREA : DATUM ; LEN1 , LEN2 : INTEGER ; LEN_NEW : INTEGER ; LEN_REG : RGRNG ; LEN_OFFS : ADRRNG ; COUNT : INTEGER ; NEWLEN : INTEGER ; SP1 : INTEGER ; SP2 : INTEGER ; procedure WORK_VC2_NEW ( var X : DATUM ; Q : ADRRNG ) ; begin (* WORK_VC2_NEW *) //*********************************************** // address of char array is on stack // VC2 converts char array to string // of length q // q = instruction operand // set plen of stack item to q // datatype to varc //********************************************* with X do begin PLEN := Q ; DTYPE := CARR ; end (* with *) end (* WORK_VC2_NEW *) ; procedure WORK_VC2 ; begin (* WORK_VC2 *) if Q > 0 then WORK_VC2_NEW ( STK [ TOP - 1 ] , Q ) else begin //********************************************* // 2020.12: compiler generates an instruction // LDC N before VC2 0 //********************************************* with STK [ TOP - 1 ] do if ( DTYPE = ADR ) and ( FPA . DSPLMT = - 1 ) then else begin TOP := TOP + 1 ; STK [ TOP - 1 ] := DATNULL ; end (* else *) ; WORK_VC2_NEW ( STK [ TOP - 1 ] , 0 ) end (* else *) ; end (* WORK_VC2 *) ; procedure WORK_VCC ; var LBL : PLABEL ; DO_STATICWORK : BOOLEAN ; begin (* WORK_VCC *) if FALSE then begin WRITELN ( TRACEF , 'start WORK_VCC, linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Top - 2' , STK [ TOP - 2 ] ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) end (* then *) ; DO_STATICWORK := TRUE ; //********************************************* // get lengths of both strings on stack //********************************************* DATWORKAREA := DATNULL ; with DATWORKAREA do begin DTYPE := VARC ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := TXRG ; end (* with *) ; LEN1 := STK [ TOP - 1 ] . PLEN ; LEN2 := STK [ TOP - 2 ] . PLEN ; //********************************************* // if one of the lengths is zero // don't really concatenate //********************************************* if LEN1 = 0 then begin //********************************************* // if LEN2 is known at compile time // build string descriptor for right side // in workarea //********************************************* if LEN2 > 0 then begin //********************************************** // WORK_VC2_NEW ( STK [ TOP - 2 ] , LEN2 ) ; //********************************************** LEN_NEW := LEN2 ; FINDRG ; RGWORK := NXTRG ; P1 := 1 ; Q1 := STRCURR ; BASE ( Q1 , P1 , B1 ) ; GENRX ( XL , RGWORK , Q1 , B1 , P1 ) ; LITVALUE := LEN_NEW * 65536 + LEN_NEW ; GENRXLIT ( XL , TXRG , LITVALUE , 1 ) ; GENRX ( XST , TXRG , 0 , RGWORK , 0 ) ; GENRR ( XLR , TXRG , RGWORK ) ; //********************************************* // copy string into workarea and // store new strcurr pointer //********************************************* ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 2 ] , 0 , 0 , 0 , TRUE , TRUE ) ; if LEN_NEW < 4096 then GENLA_LR ( TXRG , LEN_NEW + 4 , TXRG , 0 ) else GENRXLIT ( XAH , TXRG , LEN_NEW + 4 , 1 ) ; GENRX ( XST , RGWORK , Q1 , B1 , P1 ) ; end (* then *) ; //*********************************************** // otherwise the existing string descriptor // is the result //*********************************************** FREEREG_COND ( STK [ TOP - 2 ] , RGWORK ) ; FREEREG_COND ( STK [ TOP - 1 ] , RGWORK ) ; TOP := TOP - 1 ; with STK [ TOP - 1 ] do begin DTYPE := VARC ; PLEN := LEN_NEW ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := RGWORK ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; return end (* then *) ; if LEN2 = 0 then begin //********************************************* // if LEN1 is known at compile time // build string descriptor for right side // in workarea //********************************************* if LEN1 > 0 then begin //********************************************** // WORK_VC2_NEW ( STK [ TOP - 1 ] , LEN1 ) ; //********************************************** LEN_NEW := LEN1 ; FINDRG ; RGWORK := NXTRG ; P1 := 1 ; Q1 := STRCURR ; BASE ( Q1 , P1 , B1 ) ; GENRX ( XL , RGWORK , Q1 , B1 , P1 ) ; LITVALUE := LEN_NEW * 65536 + LEN_NEW ; GENRXLIT ( XL , TXRG , LITVALUE , 1 ) ; GENRX ( XST , TXRG , 0 , RGWORK , 0 ) ; GENRR ( XLR , TXRG , RGWORK ) ; //********************************************* // copy string into workarea and // store new strcurr pointer //********************************************* ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 1 ] , 0 , 0 , 0 , TRUE , TRUE ) ; if LEN_NEW < 4096 then GENLA_LR ( TXRG , LEN_NEW + 4 , TXRG , 0 ) else GENRXLIT ( XAH , TXRG , LEN_NEW + 4 , 1 ) ; GENRX ( XST , RGWORK , Q1 , B1 , P1 ) ; end (* then *) ; //*********************************************** // otherwise the existing string descriptor // is the result //*********************************************** FREEREG_COND ( STK [ TOP - 2 ] , RGWORK ) ; FREEREG_COND ( STK [ TOP - 1 ] , RGWORK ) ; STK [ TOP - 2 ] := STK [ TOP - 1 ] ; TOP := TOP - 1 ; with STK [ TOP - 1 ] do begin DTYPE := VARC ; PLEN := LEN_NEW ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := RGWORK ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; return end (* then *) ; //********************************************* // if both lengths are known at compile time // build string descriptor element in // workarea - load strcurr pointer first //********************************************* if ( LEN1 > 0 ) and ( LEN2 > 0 ) then begin LEN_NEW := LEN1 + LEN2 ; FINDRG ; RGWORK := NXTRG ; P1 := 1 ; Q1 := STRCURR ; BASE ( Q1 , P1 , B1 ) ; GENRX ( XL , RGWORK , Q1 , B1 , P1 ) ; LITVALUE := LEN_NEW * 65536 + LEN_NEW ; GENRXLIT ( XL , TXRG , LITVALUE , 1 ) ; GENRX ( XST , TXRG , 0 , RGWORK , 0 ) ; GENRR ( XLR , TXRG , RGWORK ) ; //********************************************* // concatenate strings in workarea and // store new strcurr pointer //********************************************* ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 2 ] , 0 , 0 , 0 , TRUE , TRUE ) ; if LEN2 < 4096 then GENLA_LR ( TXRG , LEN2 , TXRG , 0 ) else GENRXLIT ( XAH , TXRG , LEN2 , 1 ) ; ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 1 ] , 0 , 0 , 0 , TRUE , TRUE ) ; if LEN1 + 4 < 4096 then GENLA_LR ( TXRG , LEN1 + 4 , TXRG , 0 ) else GENRXLIT ( XAH , TXRG , LEN1 + 4 , 1 ) ; GENRX ( XST , TXRG , Q1 , B1 , P1 ) ; end (* then *) //********************************************* // if one of the lengths is not known // at compile time // build string descriptor element in // workarea from existent string descriptors //********************************************* else begin LEN_NEW := - 1 ; FINDRG ; RGWORK := NXTRG ; P1 := 1 ; Q1 := STRCURR ; BASE ( Q1 , P1 , B1 ) ; if LEN1 > 0 then begin GENRX ( XL , RGWORK , Q1 , B1 , P1 ) ; //********************************************* // length 1 ist known, that is // the length of the second operand //********************************************* STRING_GET_ACTLEN ( STK [ TOP - 2 ] , FALSE , TXRG , FALSE ) ; GENRS ( XSLL , TXRG , 0 , 16 , 0 ) ; if LEN1 < 4095 then GENLA_LR ( TXRG , LEN1 , TXRG , 0 ) else begin LITVALUE := LEN1 ; GENRXLIT ( XA , TXRG , LITVALUE , 1 ) end (* else *) ; GENRX ( XST , TXRG , 0 , RGWORK , 0 ) ; GENLA_LR ( TXRG , 4 , RGWORK , 0 ) ; //********************************************* // concatenate strings in workarea and // store new strcurr pointer //********************************************* ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 2 ] , RGWORK , 0 , 0 , FALSE , TRUE ) ; GENRX ( XAH , TXRG , 0 , RGWORK , 0 ) ; ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 1 ] , 0 , 0 , 0 , FALSE , TRUE ) ; end (* then *) else if LEN2 > 0 then begin //********************************************* // length 2 ist known, that is // the length of the first operand //********************************************* LITVALUE := LEN2 * 65536 ; GENRXLIT ( XL , RGWORK , LITVALUE , 1 ) ; STRING_GET_ACTLEN ( STK [ TOP - 1 ] , FALSE , RGWORK , TRUE ) ; GENRR ( XLR , TXRG , RGWORK ) ; GENRX ( XL , RGWORK , Q1 , B1 , P1 ) ; GENRX ( XST , TXRG , 0 , RGWORK , 0 ) ; GENLA_LR ( TXRG , 4 , RGWORK , 0 ) ; //********************************************* // concatenate strings in workarea and // store new strcurr pointer //********************************************* ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 2 ] , 0 , 0 , 0 , FALSE , TRUE ) ; GENRX ( XAH , TXRG , 0 , RGWORK , 0 ) ; ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 1 ] , RGWORK , 2 , 0 , FALSE , TRUE ) ; end (* then *) else begin //********************************************* // both lengths are unknown // if rgwork is not reg2 or reg3, // there will be a register conflict // (regs 4 to 7 are needed for MVCL) // in this case: fall back to subroutine //********************************************* if not ( RGWORK in [ 2 , 3 ] ) then begin AVAIL [ RGWORK ] := TRUE ; GENRX ( XL , TRG1 , STRCURR , 12 , 0 ) ; //************************************************ // again: error solved by using getadr2 //************************************************ if FALSE then begin WRITELN ( TRACEF , 'VCC - linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Top - 2' , STK [ TOP - 2 ] ) end (* then *) ; GETADR2 ( STK [ TOP - 2 ] , Q2 , P2 , B2 ) ; GENLA_LR ( TXRG , Q2 , B2 , P2 ) ; //************************************************ // store adr of first string to // first parm position //************************************************ GENRX ( XST , TXRG , 0 , TRG1 , 0 ) ; //************************************************ // again: error solved by using getadr2 //************************************************ if FALSE then begin WRITELN ( TRACEF , 'VCC - linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) end (* then *) ; GETADR2 ( STK [ TOP - 1 ] , Q2 , P2 , B2 ) ; GENLA_LR ( TXRG , Q2 , B2 , P2 ) ; //************************************************ // store adr of second string to // second parm position //************************************************ GENRX ( XST , TXRG , 4 , TRG1 , 0 ) ; //****************************************************** // free the registers possibly in use // in the left and right operands //****************************************************** FREEREG ( STK [ TOP - 2 ] ) ; FREEREG ( STK [ TOP - 1 ] ) ; //****************************************************** // call the $PASSVCC routine (in PASMONN) //****************************************************** LBL . NAM := '$PASSVCC' ; LBL . LEN := 8 ; GENRXLAB ( XL , TRG15 , LBL , - 3 ) ; GENRR ( XBALR , 14 , 15 ) ; //****************************************************** // indicate loss of reg 1 and reg 15 //****************************************************** CSPACTIVE [ TRG15 ] := FALSE ; CSPACTIVE [ TRG1 ] := FALSE ; //****************************************************** // load result string address in target reg //****************************************************** FINDRG ; RGWORK := NXTRG ; GENRX ( XL , RGWORK , 12 , TRG1 , 0 ) ; GENRX ( XST , RGWORK , STRCURR , 12 , 0 ) ; GENRX ( XL , RGWORK , 8 , TRG1 , 0 ) ; DO_STATICWORK := FALSE ; end (* then *) else begin STRING_GET_ACTLEN ( STK [ TOP - 2 ] , FALSE , RGWORK , FALSE ) ; GENRS ( XSLL , RGWORK , 0 , 16 , 0 ) ; STRING_GET_ACTLEN ( STK [ TOP - 1 ] , FALSE , RGWORK , TRUE ) ; GENRR ( XLR , TXRG , RGWORK ) ; GENRX ( XL , RGWORK , Q1 , B1 , P1 ) ; GENRX ( XST , TXRG , 0 , RGWORK , 0 ) ; GENLA_LR ( TXRG , 4 , RGWORK , 0 ) ; //********************************************* // concatenate strings in workarea and // store new strcurr pointer //********************************************* ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 2 ] , RGWORK , 0 , 0 , FALSE , TRUE ) ; GENRX ( XAH , TXRG , 0 , RGWORK , 0 ) ; ASSIGN_STRING ( DATWORKAREA , STK [ TOP - 1 ] , RGWORK , 2 , 0 , FALSE , TRUE ) ; end (* else *) end (* else *) ; if DO_STATICWORK then begin GENRX ( XAH , TXRG , 2 , RGWORK , 0 ) ; GENLA_LR ( TXRG , 4 , TXRG , 0 ) ; GENRX ( XST , TXRG , Q1 , B1 , P1 ) ; GENRX ( XLH , TXRG , 0 , RGWORK , 0 ) ; GENRX ( XAH , TXRG , 2 , RGWORK , 0 ) ; GENRX ( XSTH , TXRG , 0 , RGWORK , 0 ) ; GENRX ( XSTH , TXRG , 2 , RGWORK , 0 ) ; end (* then *) end (* else *) ; //********************************************* // new string is addressed by register // in workarea - points to string descriptor //********************************************* FREEREG_COND ( STK [ TOP - 2 ] , RGWORK ) ; FREEREG_COND ( STK [ TOP - 1 ] , RGWORK ) ; TOP := TOP - 1 ; with STK [ TOP - 1 ] do begin DTYPE := VARC ; PLEN := LEN_NEW ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := RGWORK ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) end (* WORK_VCC *) ; procedure WORK_VST ; begin (* WORK_VST *) if FALSE then begin WRITELN ( TRACEF , 'start WORK_VST, linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'p = ' , P : 4 , ' q = ' , Q : 4 ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) ; DUMPSTKELEM ( 'Top - 2' , STK [ TOP - 2 ] ) ; end (* then *) ; //************************************************ // p = mode (0 or 1) // q = maxLength of Target //************************************************ if P = 0 then if Q > 0 then begin //********************************************* // VST 0,n (n > 0) is used to store strings // TOP - 2 contains the target address // Maxlength at target addr is set to n // TOP - 1 contains the varchar // two items popped //********************************************* //********************************************* // fetch length from stack // element and store length and maxlength // in string // target - literal consisting of two halfwords //********************************************* MAXL := Q ; LEN := STK [ TOP - 1 ] . PLEN ; LEN_REG := 0 ; LEN_OFFS := 0 ; GETADR2 ( STK [ TOP - 2 ] , Q1 , P1 , B1 ) ; CONS_REGS ( B1 , P1 ) ; FINDRG ; if LEN >= 0 then begin //****************************************************** // in this case len_reg remains at zero, // so assign_string uses the compile time // len to control the transport //****************************************************** LITVALUE := MAXL * 65536 + LEN ; GENRXLIT ( XL , NXTRG , LITVALUE , 1 ) ; end (* then *) else begin LITVALUE := MAXL * 65536 ; GENRXLIT ( XL , NXTRG , LITVALUE , 1 ) ; STRING_GET_ACTLEN ( STK [ TOP - 1 ] , FALSE , NXTRG , TRUE ) ; //****************************************************** // this is done to make assign_string // fetch the length from the target // string descriptor //****************************************************** LEN_REG := B1 ; LEN_OFFS := Q1 + 2 ; end (* else *) ; GENRX ( XST , NXTRG , Q1 , B1 , P1 ) ; AVAIL [ NXTRG ] := TRUE ; //********************************************* // assign string to stk [top - 2 ] //********************************************* STK [ TOP - 2 ] . DTYPE := VARC ; if LEN <> 0 then ASSIGN_STRING ( STK [ TOP - 2 ] , STK [ TOP - 1 ] , LEN_REG , LEN_OFFS , 0 , TRUE , TRUE ) ; FREEREG ( STK [ TOP - 1 ] ) ; FREEREG ( STK [ TOP - 2 ] ) ; TOP := TOP - 2 end (* then *) else if Q = 0 then begin //********************************************* // VST 0,0 is used to store // string from stack to target addr // actual length of string must be less // or equal than maxlength of target (!) // TOP - 2 = target addr of String variable // TOP - 1 = source varchar (String on stack) // two items popped //********************************************* GETADR2 ( STK [ TOP - 2 ] , Q1 , P1 , B1 ) ; FINDRG ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; with STK [ TOP - 2 ] do begin DTYPE := VARC ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := NXTRG ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; GENRX ( XLH , 14 , 0 , NXTRG , 0 ) ; with STK [ TOP - 1 ] do begin if PLEN > 0 then begin LITVALUE := PLEN ; GENRXLIT ( XC , 14 , LITVALUE , 1 ) ; GENRS ( XSLL , 14 , 0 , 16 , 0 ) ; GENRXLIT ( XA , 14 , LITVALUE , 1 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; LEN_REG := 0 ; LEN_OFFS := 0 ; end (* then *) else begin if VPA = RGS then begin LEN_REG := RGADR ; LEN_OFFS := 2 ; end (* then *) else begin P2 := FPA . LVL ; Q2 := FPA . DSPLMT + 2 ; BASE ( Q2 , P2 , B2 ) ; CONS_REGS ( B2 , P2 ) ; LEN_REG := B2 ; LEN_OFFS := Q2 ; end (* else *) ; GENRX ( XCH , 14 , LEN_OFFS , LEN_REG , 0 ) ; GENRS ( XSLL , 14 , 0 , 16 , 0 ) ; GENRX ( XAH , 14 , LEN_OFFS , LEN_REG , 0 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; end (* else *) end (* with *) ; //********************************************* // assign string to stk [top - 2 ] //********************************************* ASSIGN_STRING ( STK [ TOP - 2 ] , STK [ TOP - 1 ] , LEN_REG , LEN_OFFS , 0 , TRUE , TRUE ) ; AVAIL [ NXTRG ] := TRUE ; FREEREG ( STK [ TOP - 1 ] ) ; FREEREG ( STK [ TOP - 2 ] ) ; TOP := TOP - 2 end (* then *) else begin //********************************************* // VST 0,-1 is used to move "String on stack" // representation to memory (8 bytes) // used for function results (conformant // String type as function result type) // pop 2 stack items // stack is empty after that // the function result is pushed to the stack // by the RET instruction //********************************************* GETADR2 ( STK [ TOP - 2 ] , Q1 , P1 , B1 ) ; FINDRG ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; with STK [ TOP - 2 ] do begin DTYPE := VARC ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := NXTRG ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; with STK [ TOP - 1 ] do if PLEN > 0 then begin if FALSE then begin WRITELN ( TRACEF , 'VST - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'VST - p = ' , P ) ; WRITELN ( TRACEF , 'VST - q = ' , Q ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) ; WRITELN ( TRACEF , 'scnstno = ' , SCNSTNO : 1 ) ; WRITELN ( TRACEF , 'plen = ' , PLEN : 1 ) ; end (* then *) ; LITVALUE := - 65536 + PLEN ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; //********************************************* // error fixed 17.05.2019: // the LA instruction was not generated with // the correct base register. GETADR2 must be // used (this is again the solution). // See the LA below, which uses Q2, P2 and B2; // don't know if the literal logic is correct // here //********************************************* GETADR2 ( STK [ TOP - 1 ] , Q2 , P2 , B2 ) ; if FALSE then begin WRITELN ( TRACEF , 'after getadr2' ) ; WRITELN ( TRACEF , 'p2 = ' , P2 : 4 ) ; WRITELN ( TRACEF , 'q2 = ' , Q2 : 4 ) ; WRITELN ( TRACEF , 'b2 = ' , B2 : 4 ) ; WRITELN ( TRACEF , 'scnstno = ' , SCNSTNO : 4 ) ; WRITELN ( TRACEF , 'plen = ' , PLEN : 4 ) ; end (* then *) ; if P2 < 0 then begin if SCNSTNO > 0 then begin if PLEN > 0 then begin GENLA_LR ( 14 , Q2 , 0 , 0 ) ; if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 11 - index = ' , SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ SCNSTNO ] . LNK := PCOUNTER - 1 ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q2 ) ; end (* then *) else begin GENRR ( XXR , 14 , 14 ) ; GENRR ( XBCTR , 14 , 0 ) ; end (* else *) ; end (* then *) end (* then *) else GENLA_LR ( 14 , Q2 + 4 , B2 , P2 ) ; GENRX ( XST , 14 , 4 , NXTRG , 0 ) ; end (* then *) else if PLEN = 0 then begin LITVALUE := - 65536 ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; LITVALUE := - 1 ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; GENRX ( XST , 14 , 4 , NXTRG , 0 ) ; end (* then *) else begin if FALSE then begin WRITELN ( TRACEF , 'VST - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'VST - p = ' , P ) ; WRITELN ( TRACEF , 'VST - q = ' , Q ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) ; end (* then *) ; LITVALUE := - 65536 ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; if VPA = RGS then begin LEN_REG := RGADR ; LEN_OFFS := 0 ; end (* then *) else begin P2 := FPA . LVL ; Q2 := FPA . DSPLMT ; BASE ( Q2 , P2 , B2 ) ; CONS_REGS ( B2 , P2 ) ; LEN_REG := B2 ; LEN_OFFS := Q2 ; end (* else *) ; if FALSE then begin WRITELN ( TRACEF , 'VPA = ' , VPA ) ; WRITELN ( TRACEF , 'len_reg = ' , LEN_REG ) ; end (* then *) ; GENRX ( XAH , 14 , LEN_OFFS + 2 , LEN_REG , 0 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; if VPA <> RGS then begin RGWORK := NXTRG ; FINDRP ; P1 := NXTRG ; B1 := NXTRG + 1 ; GENRX ( XL , P1 , STRCURR , 12 , 0 ) ; GENRX ( XST , P1 , 4 , RGWORK , 0 ) ; GENRX ( XLH , B1 , LEN_OFFS + 2 , LEN_REG , 0 ) ; FINDRP ; GENLA_LR ( NXTRG , LEN_OFFS + 4 , LEN_REG , 0 ) ; GENRR ( XLR , NXTRG + 1 , B1 ) ; P2 := NXTRG ; B2 := NXTRG + 1 ; GENRR ( XMVCL , P1 , P2 ) ; GENRX ( XST , P1 , STRCURR , 12 , 0 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; S370CNT := S370CNT + 1 ; end (* then *) else begin GENRX ( XLH , 14 , LEN_OFFS , LEN_REG , 0 ) ; GENRR ( XLTR , 14 , 14 ) ; GENRELRX ( XBC , GEQCND , 6 ) ; GENRX ( XL , 14 , LEN_OFFS + 4 , LEN_REG , 0 ) ; GENRELRX ( XBC , ANYCND , 4 ) ; GENLA_LR ( 14 , LEN_OFFS + 4 , LEN_REG , 0 ) ; GENRX ( XST , 14 , 4 , NXTRG , 0 ) ; end (* else *) end (* else *) ; AVAIL [ NXTRG ] := TRUE ; FREEREG ( STK [ TOP - 1 ] ) ; FREEREG ( STK [ TOP - 2 ] ) ; TOP := TOP - 2 end (* else *) else if Q > 0 then begin //********************************************* // VST 1,n (n > 0) is used to move strings // to a parameter list (value parameters) // TOP - 1 contains the target address // Maxlength at target addr is set to n // TOP - 2 contains the varchar // two items popped //********************************************* //********************************************* // fetch length from stack // element and store length and maxlength // in string // target - literal consisting of two halfwords //********************************************* MAXL := Q ; LEN := STK [ TOP - 2 ] . PLEN ; LEN_REG := 0 ; LEN_OFFS := 0 ; GETADR2 ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; CONS_REGS ( B1 , P1 ) ; FINDRG ; if LEN >= 0 then begin //****************************************************** // in this case len_reg remains at zero, // so assign_string uses the compile time // len to control the transport //****************************************************** LITVALUE := MAXL * 65536 + LEN ; GENRXLIT ( XL , NXTRG , LITVALUE , 1 ) ; end (* then *) else begin LITVALUE := MAXL * 65536 ; GENRXLIT ( XL , NXTRG , LITVALUE , 1 ) ; STRING_GET_ACTLEN ( STK [ TOP - 2 ] , FALSE , NXTRG , TRUE ) ; //****************************************************** // this is done to make assign_string // fetch the length from the target // string descriptor //****************************************************** LEN_REG := B1 ; LEN_OFFS := Q1 + 2 ; end (* else *) ; GENRX ( XST , NXTRG , Q1 , B1 , P1 ) ; AVAIL [ NXTRG ] := TRUE ; //********************************************* // assign string to stk [top - 2 ] //********************************************* STK [ TOP - 1 ] . DTYPE := VARC ; if LEN <> 0 then ASSIGN_STRING ( STK [ TOP - 1 ] , STK [ TOP - 2 ] , LEN_REG , LEN_OFFS , 0 , TRUE , TRUE ) ; FREEREG ( STK [ TOP - 1 ] ) ; FREEREG ( STK [ TOP - 2 ] ) ; TOP := TOP - 2 end (* then *) else if Q = 0 then begin end (* then *) else begin //********************************************* // VST 1,-1 is used to store 8 bytes // string on stack representation to // a procedure parameter list, for example // TOP - 1 contains the target address // TOP - 2 contains the varchar // (can be VC2 char constant, too) // two items popped, the target is pushed //********************************************* with STK [ TOP - 2 ] do begin if FALSE then begin WRITELN ( TRACEF , 'VST - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'VST - p = ' , P ) ; WRITELN ( TRACEF , 'VST - q = ' , Q ) ; DUMPSTKELEM ( 'Top - 2' , STK [ TOP - 2 ] ) ; WRITELN ( TRACEF , 'scnstno = ' , SCNSTNO : 1 ) ; WRITELN ( TRACEF , 'plen = ' , PLEN : 1 ) ; end (* then *) ; if PLEN = 1 then begin GETADR2 ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; LITVALUE := PLEN * 65536 + PLEN ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; FINDRG ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; GETADR2 ( STK [ TOP - 2 ] , Q2 , P2 , B2 ) ; GENLA_LR ( 14 , Q2 , 0 , 0 ) ; GENRX ( XSTC , 14 , 4 , NXTRG , 0 ) ; end (* then *) else if PLEN >= 0 then begin GETADR2 ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; LITVALUE := - 65536 ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; LITVALUE := PLEN ; if PLEN > 0 then GENRXLIT ( XA , 14 , LITVALUE , 1 ) ; FINDRG ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; //********************************************* // error fixed 17.05.2019: // the LA instruction was not generated with // the correct base register. GETADR2 must be // used (this is again the solution). // See the LA below, which uses Q2, P2 and B2; // don't know if the literal logic is correct // here //********************************************* GETADR2 ( STK [ TOP - 2 ] , Q2 , P2 , B2 ) ; if FALSE then begin WRITELN ( TRACEF , 'after getadr2 ' 'for STK-2' ) ; WRITELN ( TRACEF , 'p2 = ' , P2 : 4 ) ; WRITELN ( TRACEF , 'q2 = ' , Q2 : 4 ) ; WRITELN ( TRACEF , 'b2 = ' , B2 : 4 ) ; WRITELN ( TRACEF , 'scnstno = ' , SCNSTNO : 4 ) ; WRITELN ( TRACEF , 'plen = ' , PLEN : 4 ) ; end (* then *) ; if P2 < 0 then begin if SCNSTNO > 0 then begin if PLEN > 0 then begin GENLA_LR ( 14 , Q2 , 0 , 0 ) ; if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 12 - index = ' , SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ SCNSTNO ] . LNK := PCOUNTER - 1 ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( Q2 ) ; if FALSE then WRITELN ( TRACEF , 'set literal ' , Q2 : 1 , ' at position ' , PCOUNTER - 1 : 1 ) ; end (* then *) else begin GENRR ( XXR , 14 , 14 ) ; GENRR ( XBCTR , 14 , 0 ) ; end (* else *) ; end (* then *) end (* then *) //********************************************* // error fixed 26.05.2019: // offset must be 4 in case of VARC, but // zero in case of CARR (no length fields) //********************************************* else if DTYPE = CARR then GENLA_LR ( 14 , Q2 , B2 , P2 ) else GENLA_LR ( 14 , Q2 + 4 , B2 , P2 ) ; GENRX ( XST , 14 , 4 , NXTRG , 0 ) ; end (* then *) else begin GETADR2 ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; LITVALUE := - 65536 ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; //************************************************ // maybe wrong //************************************************ if VPA = RGS then begin LEN_REG := RGADR ; LEN_OFFS := 2 ; GENRX ( XAH , 14 , 2 , RGADR , 0 ) ; end (* then *) else begin P2 := FPA . LVL ; Q2 := FPA . DSPLMT + 2 ; BASE ( Q2 , P2 , B2 ) ; CONS_REGS ( B2 , P2 ) ; LEN_REG := B2 ; LEN_OFFS := Q2 ; GENRX ( XAH , 14 , Q2 , B2 , 0 ) ; end (* else *) ; FINDRG ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; GENRX ( XST , 14 , 0 , NXTRG , 0 ) ; GENRX ( XLH , 14 , LEN_OFFS - 2 , LEN_REG , 0 ) ; GENRR ( XLTR , 14 , 14 ) ; GENRELRX ( XBC , GEQCND , 6 ) ; GENRX ( XL , 14 , LEN_OFFS + 2 , LEN_REG , 0 ) ; GENRELRX ( XBC , ANYCND , 4 ) ; GENLA_LR ( 14 , LEN_OFFS + 2 , LEN_REG , 0 ) ; GENRX ( XST , 14 , 4 , NXTRG , 0 ) ; end (* else *) end (* with *) ; FREEREG_COND ( STK [ TOP - 2 ] , - 1 ) ; STK [ TOP - 2 ] := STK [ TOP - 1 ] ; TOP := TOP - 1 ; with STK [ TOP - 1 ] do begin DTYPE := VARC ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := NXTRG ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) end (* else *) end (* WORK_VST *) ; begin (* STRINGOPS *) if FALSE then begin WRITE ( TRACEF , 'start stringops - pcode = ' , OPCODE ) ; WRITELN ( TRACEF , ' linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'start stringops - p = ' , P ) ; WRITELN ( TRACEF , 'start stringops - q = ' , Q ) ; DUMPSTK ( 1 , TOP - 1 ) ; end (* then *) ; if FALSE then begin WRITE ( TRACEF , 'start stringops - pcode = ' , OPCODE ) ; WRITELN ( TRACEF , ' linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'start stringops - p = ' , P ) ; WRITELN ( TRACEF , 'start stringops - q = ' , Q ) ; DUMPAVAIL ; end (* then *) ; case OPCODE of //******************************************************* // varchar push: save string workarea address //******************************************************* PVPU : begin //********************************************* // save strcurr ptr into given location //********************************************* FINDRG ; P2 := P ; BASE ( Q , P2 , B ) ; GENRX ( XL , NXTRG , STRCURR , 12 , 0 ) ; GENRX ( XST , NXTRG , Q , B , P2 ) ; AVAIL [ NXTRG ] := TRUE end (* tag/ca *) ; //******************************************************* // varchar pop: restore string workarea address //******************************************************* PVPO : begin //********************************************* // restore strcurr ptr from given location //********************************************* FINDRG ; P2 := P ; BASE ( Q , P2 , B ) ; GENRX ( XL , NXTRG , Q , B , P2 ) ; GENRX ( XST , NXTRG , STRCURR , 12 , 0 ) ; AVAIL [ NXTRG ] := TRUE end (* tag/ca *) ; //******************************************************* // varchar convert 1: convert single char to string //******************************************************* PVC1 : with STK [ TOP - 1 ] do begin //********************************************* // address of char array is on stack // VC1 converts single char to string // of length 1 // set plen of stack item to 1 // datatype to varc //********************************************* PLEN := 1 ; DTYPE := CHRC ; end (* with *) ; //******************************************************* // varchar convert 2: convert char array to string // if q = zero: build null string on stack //******************************************************* PVC2 : WORK_VC2 ; //******************************************************* // varchar store: store string to memory //******************************************************* PVST : WORK_VST ; //******************************************************* // varchar load: load string from memory to stack //******************************************************* PVLD : begin COPYSTRING := ( P <> 0 ) ; LEN := Q ; if not COPYSTRING then with STK [ TOP - 1 ] do begin PLEN := - 1 ; DTYPE := VARC ; if Q = 0 then begin if FALSE then begin WRITELN ( TRACEF , 'VLD - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'VLD - p = ' , P ) ; WRITELN ( TRACEF , 'VLD - q = ' , Q ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) end (* then *) ; FINDRG ; //********************************************* // error fixed 17.05.2019: // wrong code generation with array elements // GETADR2 must be used // (this is again the solution). // the original code made a difference // depending on VRBL ... don't know if this // is correct //********************************************* GETADR2 ( STK [ TOP - 1 ] , Q2 , P2 , B2 ) ; if not CHECK_ZERO_REG ( STK [ TOP - 1 ] , Q2 , P2 , B2 ) then begin GENLA_LR ( NXTRG , Q2 , B2 , P2 ) ; FREEREG ( STK [ TOP - 1 ] ) ; FPA := ZEROBL ; VPA := RGS ; MEMADR := ZEROBL ; RGADR := NXTRG ; VRBL := TRUE ; end (* then *) else begin //****************************************************** // work done by check_zero_reg //****************************************************** end (* else *) ; if FALSE then begin WRITELN ( TRACEF , 'VLD - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'VLD - p = ' , P ) ; WRITELN ( TRACEF , 'VLD - q = ' , Q ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) end (* then *) ; end (* then *) end (* with *) else with STK [ TOP - 1 ] do begin if FALSE then begin WRITELN ( TRACEF , 'VLD - linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'VLD - p = ' , P ) ; WRITELN ( TRACEF , 'VLD - q = ' , Q ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) end (* then *) ; FINDRG ; RGWORK1 := NXTRG ; GENRX ( XL , RGWORK1 , STRCURR , 12 , 0 ) ; FINDRP ; P1 := NXTRG ; B1 := NXTRG + 1 ; //********************************************* // error fixed 17.05.2019: // wrong code generation with array elements // GETADR2 must be used // (this is again the solution). // the original code made a difference // depending on VRBL ... don't know if this // is correct //********************************************* GETADR2 ( STK [ TOP - 1 ] , Q2 , P2 , B2 ) ; GENLA_LR ( P1 , Q2 , B2 , P2 ) ; FREEREG ( STK [ TOP - 1 ] ) ; GENRX ( XLH , B1 , 2 , P1 , 0 ) ; GENRX ( XSTH , B1 , 0 , RGWORK1 , 0 ) ; GENRX ( XSTH , B1 , 2 , RGWORK1 , 0 ) ; FINDRP ; P2 := NXTRG ; B2 := NXTRG + 1 ; GENLA_LR ( P2 , 4 , RGWORK1 , 0 ) ; GENRR ( XLR , B2 , B1 ) ; GENRX ( XLH , 14 , 0 , P1 , 0 ) ; GENLA_LR ( P1 , 4 , P1 , 0 ) ; GENRR ( XLTR , 14 , 14 ) ; GENRELRX ( XBC , GEQCND , 4 ) ; GENRX ( XL , P1 , 0 , P1 , 0 ) ; GENRR ( XMVCL , P2 , P1 ) ; GENRX ( XST , P2 , STRCURR , 12 , 0 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; PLEN := - 1 ; DTYPE := VARC ; FPA := ZEROBL ; VPA := RGS ; MEMADR := ZEROBL ; RGADR := RGWORK1 ; end (* with *) end (* tag/ca *) ; //******************************************************* // varchar move: move string to char array //******************************************************* PVMV : begin if Q < 0 then begin SP1 := TOP - 2 ; SP2 := TOP - 1 ; Q := - Q ; end (* then *) else begin SP1 := TOP - 1 ; SP2 := TOP - 2 ; end (* else *) ; //********************************************* // patblank = blank pattern for mfioperation //********************************************* //********************************************* // set target to blanks //********************************************* PATBLANK := DATNULL ; PATBLANK . FPA . DSPLMT := ORD ( ' ' ) ; MFIOPERATION ( STK [ SP2 ] , PATBLANK , Q ) ; //********************************************* // assign string //********************************************* STRING_GET_ACTLEN ( STK [ SP1 ] , TRUE , RGWORK , FALSE ) ; GENRXLIT ( XC , RGWORK , Q , 0 ) ; ASSIGN_STRING ( STK [ SP2 ] , STK [ SP1 ] , - RGWORK , 0 , 0 , TRUE , TRUE ) ; AVAIL [ RGWORK ] := TRUE ; TOP := TOP - 2 end (* tag/ca *) ; //******************************************************* // varchar index: retrieve single string char via index //******************************************************* PVIX : begin //****************************************************** // load index value from Top - 1 //****************************************************** with STK [ TOP - 1 ] do begin if VPA = RGS then RGWORK2 := RGADR else begin LOAD ( STK [ TOP - 1 ] ) ; RGWORK2 := NXTRG ; end (* else *) end (* with *) ; with STK [ TOP - 2 ] do begin //********************************************* // load maxlength field // later: decide where string addr is //********************************************* GETADR2 ( STK [ TOP - 2 ] , Q1 , P1 , B1 ) ; FINDRG ; RGWORK1 := NXTRG ; FINDRG ; RGWORK := NXTRG ; GENLA_LR ( RGWORK1 , Q1 , B1 , P1 ) ; GENRX ( XLH , RGWORK , 0 , RGWORK1 , 0 ) ; GENRR ( XLTR , RGWORK , RGWORK ) ; GENLA_LR ( RGWORK , 4 , RGWORK1 , 0 ) ; GENRELRX ( XBC , GEQCND , 4 ) ; GENRX ( XL , RGWORK , 4 , RGWORK1 , 0 ) ; GENRR ( XBCTR , RGWORK , 0 ) ; //********************************************* // load length field // later: to check for index inside bounds //********************************************* GENRX ( XLH , RGWORK1 , 2 , RGWORK1 , 0 ) ; //********************************************* // string address minus one is in rgwork // (virtual origin) // add index value to virtual origin //********************************************* GENRR ( XCR , RGWORK2 , RGWORK1 ) ; GENRR ( XAR , RGWORK2 , RGWORK ) ; AVAIL [ RGWORK ] := TRUE ; AVAIL [ RGWORK1 ] := TRUE ; end (* with *) ; //********************************************* // set top stack element (= string) // to register address //********************************************* TOP := TOP - 1 ; with STK [ TOP - 1 ] do begin FPA := ZEROBL ; DRCT := TRUE ; VRBL := TRUE ; VPA := RGS ; RGADR := RGWORK2 ; end (* with *) ; end (* tag/ca *) ; //******************************************************* // varchar concat: concatenate varchars in workarea //******************************************************* PVCC : WORK_VCC ; //******************************************************* // varchar set maxlength: sets maxlength on varchar // used on potentially uninitialized varchars, when // passed as var parameters (so that the procedure // can determine their maximum length) //******************************************************* PVSM : begin GENRXLIT ( XLH , 14 , Q , - 1 ) ; FINDRG ; GETADR2 ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; GENLA_LR ( NXTRG , Q1 , B1 , P1 ) ; GENRX ( XSTH , 14 , 0 , NXTRG , 0 ) ; AVAIL [ NXTRG ] := TRUE ; with STK [ TOP - 1 ] do begin DTYPE := VARC ; PLEN := Q ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := NXTRG ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) end (* tag/ca *) ; //******************************************************* // varchar load maxlength: loads maxlength in certain // situations, for example when a string expression // has been built and the maxlength of this expression // is requested (which is equal to the length // in this case) //******************************************************* // PCINT checks for the maxlength field being -1 // and throws a UNDEFSTRING error, if not //******************************************************* PVLM : with STK [ TOP - 1 ] do begin if VPA = RGS then begin GENRX ( XLH , RGADR , 2 , RGADR , 0 ) ; RGWORK := RGADR end (* then *) else begin GETADR2 ( STK [ TOP - 1 ] , Q1 , P1 , B1 ) ; GENLA_LR ( 14 , Q1 , B1 , P1 ) ; FREEREG ( STK [ TOP - 1 ] ) ; GENRX ( XLH , 14 , 2 , 14 , 0 ) ; RGWORK := 14 ; end (* else *) ; DTYPE := INT ; PLEN := 4 ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := RGWORK ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; end (* with *) ; //******************************************************* // varchar repeat: repeat string is implemented as // P-Code, because this is needed to build new // Strings on the stack (string of n blanks, for // example) - at least with the P-Code interpreters //******************************************************* PVRP : begin //****************************************************** // get constant length of top stack element // or load length into rgwork //****************************************************** with STK [ TOP - 1 ] do if not VRBL then COUNT := FPA . DSPLMT else begin LOAD ( STK [ TOP - 1 ] ) ; RGWORK := NXTRG ; COUNT := - 1 ; end (* else *) ; //****************************************************** // now pop stack to get string parameter // length of result depends heavily on // type of string parameter //****************************************************** TOP := TOP - 1 ; with STK [ TOP - 1 ] do if DTYPE = CHRC then begin if COUNT >= 0 then NEWLEN := COUNT else NEWLEN := - 1 ; end (* then *) else if DTYPE = CARR then begin if COUNT >= 0 then NEWLEN := COUNT * PLEN else begin NEWLEN := - 1 ; end (* else *) end (* then *) else NEWLEN := - 1 ; //****************************************************** // result string will be in string workarea // rgwork1 will point to result string //****************************************************** with STK [ TOP - 1 ] do if DTYPE = CHRC then begin //****************************************************** // generate code for single character case //****************************************************** FINDRP ; P1 := NXTRG ; B1 := NXTRG + 1 ; GENRX ( XL , P1 , STRCURR , 12 , 0 ) ; if NEWLEN >= 0 then begin LITVALUE := NEWLEN * 65536 + NEWLEN ; GENRXLIT ( XL , 14 , LITVALUE , 1 ) ; end (* then *) else begin GENRR ( XLR , 14 , RGWORK ) ; GENRS ( XSLL , 14 , 0 , 16 , 0 ) ; GENRR ( XAR , 14 , RGWORK ) ; end (* else *) ; GENRX ( XST , 14 , 0 , P1 , 0 ) ; GENLA_LR ( P1 , 4 , P1 , 0 ) ; if NEWLEN < 0 then GENRR ( XLR , B1 , RGWORK ) else begin LITVALUE := NEWLEN ; GENRXLIT ( XL , B1 , LITVALUE , 1 ) ; end (* else *) ; FINDRP ; P2 := NXTRG ; B2 := NXTRG + 1 ; GENRR ( XXR , P2 , P2 ) ; if VRBL then begin FPA := MEMADR ; MEMADR := ZEROBL ; VRBL := FALSE ; GETADR2 ( STK [ TOP - 1 ] , QX , PX , BX ) ; GENRX ( XIC , B2 , QX , PX , BX ) ; end (* then *) else GENLA_LR ( B2 , FPA . DSPLMT , 0 , 0 ) ; GENRS ( XSLL , B2 , 0 , 24 , 0 ) ; GENRR ( XMVCL , P1 , P2 ) ; AVAIL [ B1 ] := TRUE ; AVAIL [ P2 ] := TRUE ; AVAIL [ B2 ] := TRUE ; AVAIL [ RGWORK ] := TRUE ; FINDRG ; RGWORK1 := NXTRG ; GENRX ( XL , RGWORK1 , STRCURR , 12 , 0 ) ; GENRX ( XST , P1 , STRCURR , 12 , 0 ) ; AVAIL [ P1 ] := TRUE ; end (* then *) else if DTYPE = CARR then begin //****************************************************** // generate code for character array case // p1 = source address of char array // p2 = target address // q2 = count //****************************************************** FINDRG ; P1 := NXTRG ; if VPA = RGS then begin GENRR ( XLR , P1 , RGADR ) ; AVAIL [ RGADR ] := TRUE ; end (* then *) else begin GETADR2 ( STK [ TOP - 1 ] , QX , PX , BX ) ; GENLA_LR ( P1 , QX , 0 , 0 ) ; if FALSE then WRITELN ( TRACEF , 'repl lit. adr. 13 - index = ' , SCNSTNO : 1 , ' pc = ' , PCOUNTER - 1 : 1 ) ; LITTBL [ SCNSTNO ] . LNK := PCOUNTER - 1 ; CODE . H [ PCOUNTER - 1 ] := TO_HINT ( QX ) ; end (* else *) ; FINDRG ; P2 := NXTRG ; GENRX ( XL , P2 , STRCURR , 12 , 0 ) ; FINDRG ; Q2 := NXTRG ; if COUNT < 0 then GENRR ( XLR , Q2 , RGWORK ) else begin LITVALUE := COUNT ; GENRXLIT ( XL , Q2 , LITVALUE , 0 ) ; end (* else *) ; GENRR ( XLR , 14 , Q2 ) ; GENRXLIT ( XMH , 14 , PLEN , - 1 ) ; GENRX ( XSTH , 14 , 0 , P2 , 0 ) ; GENRX ( XSTH , 14 , 2 , P2 , 0 ) ; GENLA_LR ( P2 , 4 , P2 , 0 ) ; GENSS ( XMVC , PLEN , 0 , P2 , 0 , P1 ) ; GENLA_LR ( P2 , PLEN , P2 , 0 ) ; GENRELRX ( XBCT , Q2 , - 5 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ Q2 ] := TRUE ; AVAIL [ RGWORK ] := TRUE ; FINDRG ; RGWORK1 := NXTRG ; GENRX ( XL , RGWORK1 , STRCURR , 12 , 0 ) ; GENRX ( XST , P2 , STRCURR , 12 , 0 ) ; AVAIL [ P2 ] := TRUE ; end (* then *) else begin //****************************************************** // generate code for varchar case // p1 = source address of varchar // q1 = length of source = length of target // p2 = target address // q2 = length of target //****************************************************** FINDRP ; P1 := NXTRG ; Q1 := NXTRG + 1 ; if VPA = RGS then begin GENRR ( XLR , P1 , RGADR ) ; AVAIL [ RGADR ] := TRUE ; end (* then *) else begin GETADR2 ( STK [ TOP - 1 ] , QX , PX , BX ) ; GENLA_LR ( P1 , QX , BX , PX ) ; end (* else *) ; FINDRP ; P2 := NXTRG ; Q2 := NXTRG + 1 ; GENRX ( XL , P2 , STRCURR , 12 , 0 ) ; if COUNT >= 0 then begin FINDRG ; RGWORK := NXTRG ; LITVALUE := COUNT ; GENRXLIT ( XL , RGWORK , LITVALUE , 0 ) ; end (* then *) ; GENRR ( XLR , 14 , RGWORK ) ; GENRX ( XLH , Q2 , 2 , P1 , 0 ) ; GENRR ( XLR , Q1 , Q2 ) ; GENRX ( XMH , 14 , 2 , P1 , 0 ) ; GENRX ( XSTH , 14 , 0 , P2 , 0 ) ; GENRX ( XSTH , 14 , 2 , P2 , 0 ) ; GENLA_LR ( P2 , 4 , P2 , 0 ) ; GENRX ( XLH , 14 , 0 , P1 , 0 ) ; GENLA_LR ( P1 , 4 , P1 , 0 ) ; GENRR ( XLTR , 14 , 14 ) ; GENRELRX ( XBC , GEQCND , 4 ) ; GENRX ( XL , P1 , 0 , P1 , 0 ) ; //****************************************************** // length fields are set correctly // p1 = source of char string // p2 = target of char string // q1 = length of char string // q2 = length of char string // rgwork = count // CSPACTIVE [trg15] ... indicate loss of reg trg15 //****************************************************** CSPACTIVE [ TRG15 ] := FALSE ; GENRR ( XLR , 14 , Q1 ) ; GENRR ( XLR , 15 , P1 ) ; GENRR ( XMVCL , P2 , P1 ) ; GENRR ( XLR , Q1 , 14 ) ; GENRR ( XLR , Q2 , 14 ) ; GENRR ( XLR , P1 , 15 ) ; GENRELRX ( XBCT , RGWORK , - 4 ) ; AVAIL [ P1 ] := TRUE ; AVAIL [ Q1 ] := TRUE ; AVAIL [ Q2 ] := TRUE ; AVAIL [ RGWORK ] := TRUE ; FINDRG ; RGWORK1 := NXTRG ; GENRX ( XL , RGWORK1 , STRCURR , 12 , 0 ) ; GENRX ( XST , P2 , STRCURR , 12 , 0 ) ; AVAIL [ P2 ] := TRUE ; end (* else *) ; //****************************************************** // setup topmost stack element for result string //****************************************************** with STK [ TOP - 1 ] do begin DTYPE := VARC ; PLEN := - 1 ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := RGWORK1 ; FPA . LVL := 0 ; FPA . DSPLMT := 0 ; MEMADR . LVL := 0 ; MEMADR . DSPLMT := 0 ; if FALSE then begin WRITELN ( TRACEF , 'after handling vrp - linecnt = ' , LINECNT : 1 ) ; DUMPSTKELEM ( 'Top - 1' , STK [ TOP - 1 ] ) ; WRITE ( TRACEF , 'rgadr = ' , RGADR ) ; end (* then *) ; end (* with *) ; end (* tag/ca *) ; end (* case *) end (* STRINGOPS *) ; procedure BOPERATION_COMPARE ; //**************************************************************** // BINARY OPERATIONS - Comparison //**************************************************************** label 10 , 20 ; var L , R : DATUM ; //************************************************** // l,r = left and right operand // lop,rop = stack index of left and right operand // lr = left/right interchange flag //************************************************** LOP , ROP : STKPTR ; LR : BOOLEAN ; Q1 : ADRRNG ; P1 , B1 : LVLRNG ; begin (* BOPERATION_COMPARE *) if FALSE then begin WRITELN ( TRACEF , 'start boperation_compare, linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'opcode = ' , OPCODE ) ; WRITELN ( TRACEF , 'opndtype = ' , OPNDTYPE ) ; DUMPSTKELEM ( 'top ' , STK [ TOP ] ) ; DUMPSTKELEM ( 'top - 1 ' , STK [ TOP - 1 ] ) ; end (* then *) ; //***************************************************** // Opcodes are PEQU , PNEQ , PGRT , PLEQ , PLES , PGEQ //***************************************************** L := STK [ TOP - 1 ] ; R := STK [ TOP ] ; //******************************************* // if type = SET, call SETCOMPARE and leave //******************************************* if OPNDTYPE = PSET then begin SETCOMPARE ( L , R ) ; STK [ TOP - 1 ] := L ; return end (* then *) ; //***************************************************** // if type = varying string, call STRINGCOMPARE // and leave //***************************************************** if OPNDTYPE = VARC then begin STRINGCOMPARE ( L , R ) ; STK [ TOP - 1 ] := L ; return end (* then *) ; //***************************************************** // if type = character array, call COMPARE_CARR // and leave //***************************************************** if OPNDTYPE = CARR then begin COMPARE_CARR ( L , R , Q , P , COMPTYPE ) ; CSPACTIVE [ TRG1 ] := FALSE ; BRCND := BRMSK [ OPCODE ] ; STK [ TOP - 1 ] := L ; return end (* then *) ; //************************************************ // DETERMINE WHICH OPERAND SHOULD BE USED // AS LEFT HAND OPERAND ... //************************************************ LR := ( STK [ TOP - 1 ] . VRBL and STK [ TOP ] . DRCT ) or ( not STK [ TOP - 1 ] . DRCT ) or ( not STK [ TOP ] . VRBL ) ; 10 : if LR then begin LOP := TOP - 1 ; ROP := TOP end (* then *) else begin LOP := TOP ; ROP := TOP - 1 end (* else *) ; L := STK [ LOP ] ; R := STK [ ROP ] ; if FALSE then begin WRITELN ( TRACEF , 'boperation_compare after LR computing, linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'opcode = ' , OPCODE ) ; WRITELN ( TRACEF , 'lr = ' , LR ) ; DUMPSTKELEM ( 'left ' , L ) ; DUMPSTKELEM ( 'Right' , R ) ; end (* then *) ; //***************************************************** // change OPCODE depending on LR flag //***************************************************** if not LR then OPCODE := INVBRM [ OPCODE ] ; //***************************************************** // other operand types //***************************************************** case OPNDTYPE of ADR , INT , HINT : with R do begin LOAD ( L ) ; if VRBL then begin GETOPERAND ( R , Q1 , P1 , B1 ) ; if ( not DRCT ) or ( VPA = MEM ) then if DTYPE = HINT then GENRX ( XCH , L . RGADR , Q1 , B1 , P1 ) else GENRX ( XC , L . RGADR , Q1 , B1 , P1 ) else begin GENRR ( XCR , L . RGADR , RGADR ) ; AVAIL [ RGADR ] := TRUE end (* else *) end (* then *) else //*************************** // if NOT VRBL (I.E. CONST) //*************************** begin if FPA . DSPLMT = 1 then if OPCODE = PLES then (**********************************) (* COMPARISON AGAINST 0 IS BETTER *) (**********************************) begin FPA . DSPLMT := 0 ; OPCODE := PLEQ end (* then *) else if OPCODE = PGEQ then begin FPA . DSPLMT := 0 ; OPCODE := PGRT end (* then *) ; if FPA . DSPLMT = 0 then GENRR ( XLTR , L . RGADR , L . RGADR ) else if ( OPNDTYPE = ADR ) then begin //****************************************************** // CONSTANT OF TYPE ADR = NIL ! // FOLLOWING VALID ONLY IF $D- IS USED //****************************************************** GENRR ( XLTR , L . RGADR , L . RGADR ) ; //****************************************************** // opc is pequ or pneq // this logic applies imo // because nil = -1 //****************************************************** if OPCODE = PEQU then OPCODE := PLES else OPCODE := PGEQ ; end (* then *) else GENRXLIT ( XC , L . RGADR , FPA . DSPLMT , 0 ) ; end (* else *) ; AVAIL [ L . RGADR ] := TRUE ; end (* with *) ; BOOL , CHRC : with R do 20 : if L . VRBL then if ( L . VPA = RGS ) and L . DRCT then begin if VRBL then if ( VPA = RGS ) and DRCT then begin GENRR ( XCR , L . RGADR , RGADR ) ; AVAIL [ RGADR ] := TRUE ; end (* then *) else begin GETQB ( R , Q1 , B1 , 0 ) ; Q := XCLI * SL24 + B1 * SL12 + Q1 ; GENRXLIT_EXTENDED ( XEX , L . RGADR , Q , 0 , XCLI ) ; OPCODE := INVBRM [ OPCODE ] ; end (* else *) else if FPA . DSPLMT = 0 then GENRR ( XLTR , L . RGADR , L . RGADR ) else begin LOAD ( R ) ; goto 20 end (* else *) ; AVAIL [ L . RGADR ] := TRUE ; end (* then *) else (******************) (* L IS IN MEMORY *) (******************) if VRBL then begin CLEAR_REG := FALSE ; LOAD ( STK [ ROP ] ) ; CLEAR_REG := TRUE ; LR := not LR ; if FALSE then WRITELN ( TRACEF , 'start boperation_compare switch LR, linecnt = ' , LINECNT : 1 ) ; goto 10 ; end (* then *) else begin GETQB ( L , Q1 , B1 , 0 ) ; GENSI ( XCLI , Q1 , B1 , FPA . DSPLMT ) ; end (* else *) else (*******************) (* L IS A CONSTANT *) (*******************) if VRBL then begin LR := not LR ; if FALSE then WRITELN ( TRACEF , 'start boperation_compare switch LR, linecnt = ' , LINECNT : 1 ) ; goto 10 end (* then *) else begin LOAD ( STK [ ROP ] ) ; if FALSE then WRITELN ( TRACEF , 'start boperation_compare switch LR, linecnt = ' , LINECNT : 1 ) ; goto 10 end (* else *) ; REEL : with R do begin LOAD ( L ) ; if VRBL then begin GETOPERAND ( R , Q1 , P1 , B1 ) ; if ( VPA = RGS ) and DRCT then begin GENRR ( XCDR , L . RGADR , R . RGADR ) ; AVAILFP [ RGADR ] := TRUE end (* then *) else (*************************) (* VPA = MEM OR NOT DRCT *) (*************************) GENRX ( XCD , L . RGADR , Q1 , B1 , P1 ) end (* then *) else (************) (* CONSTANT *) (************) if RCNST = 0.0 then GENRR ( XLTDR , L . RGADR , L . RGADR ) else GENRXDLIT ( XCD , L . RGADR , RCNST ) ; AVAILFP [ L . RGADR ] := TRUE ; end (* with *) ; end (* case *) ; BRCND := BRMSK [ OPCODE ] ; STK [ TOP - 1 ] := L ; end (* BOPERATION_COMPARE *) ; procedure BOPERATION ; //**************************************************************** // BINARY OPERATIONS //**************************************************************** label 30 ; var L , R : DATUM ; X : DATUM ; (*************************) (*LEFT AND RIGHT OPERANDS*) (*************************) LOP , ROP : STKPTR ; (****************************************) (*STACK INDEX OF LEFT AND RIGHT OPERANDS*) (****************************************) OP1 , OP2 : BYTE ; LR : BOOLEAN ; (*****************************) (*LEFT/RIGHT INTERCHANGE FLAG*) (*****************************) Q1 : ADRRNG ; P1 , B1 : LVLRNG ; begin (* BOPERATION *) (**************************************************) (* DETERMINE WHICH OPERAND SHOULD BE USED *) (* AS LEFT HAND OPERAND ... *) (**************************************************) if FALSE then WRITELN ( TRACEF , 'start boperation, linecnt = ' , LINECNT : 1 ) ; LR := ( OPCODE in [ PSBA , PSBR , PDVR , PDVI , PMOD , PDIF , PINN ] ) or ( STK [ TOP - 1 ] . VRBL and STK [ TOP ] . DRCT ) or ( not STK [ TOP - 1 ] . DRCT ) or ( not STK [ TOP ] . VRBL ) ; if LR then begin LOP := TOP - 1 ; ROP := TOP end (* then *) else begin LOP := TOP ; ROP := TOP - 1 end (* else *) ; L := STK [ LOP ] ; R := STK [ ROP ] ; if FALSE then begin WRITELN ( TRACEF , 'boperation after LR computing, linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'lr = ' , LR ) ; DUMPSTKELEM ( 'left ' , L ) ; DUMPSTKELEM ( 'Right' , R ) ; end (* then *) ; case OPCODE of PADI , PSBI : begin if not L . DRCT then LOAD ( L ) ; if R . DRCT then if OPCODE = PADI then begin L . FPA . DSPLMT := L . FPA . DSPLMT + R . FPA . DSPLMT ; R . FPA . DSPLMT := 0 end (* then *) else begin L . FPA . DSPLMT := L . FPA . DSPLMT - R . FPA . DSPLMT ; R . FPA . DSPLMT := 0 end (* else *) ; (*************************************************************) (*CONST<OPR>CONST AND VRBL<OPR>CONST CASES ARE COMPLETED NOW *) (*************************************************************) OP1 := XAR ; OP2 := XA ; if OPCODE = PSBI then begin OP1 := XSR ; OP2 := XS end (* then *) ; if R . VRBL then begin Q := L . FPA . DSPLMT ; L . FPA . DSPLMT := 0 ; (**********) (*SAVE FPA*) (**********) LOAD ( L ) ; if R . DTYPE <> INT then if R . DTYPE = HINT then OP2 := OP2 - 16 (**********************************) (* SWITCH TO HALFWORD INSTRUCTION *) (**********************************) else LOAD ( R ) ; if R . DRCT then if R . VPA = RGS then begin GENRR ( OP1 , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE end (* then *) else (*********) (*VPA=MEM*) (*********) begin Q1 := R . MEMADR . DSPLMT ; P1 := R . MEMADR . LVL ; BASE ( Q1 , P1 , B1 ) ; GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) ; end (* else *) else (************) (*NOT R.DRCT*) (************) begin GETOPERAND ( R , Q1 , P1 , B1 ) ; GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) ; end (* else *) ; L . FPA . DSPLMT := Q ; (*************) (*RESTORE FPA*) (*************) end (* then *) ; if not LR and ( OPCODE = PSBI ) then (***********************************) (*THIS DOES NOT SEEM TO BE COMPLETE*) (***********************************) begin Q := - L . FPA . DSPLMT ; L . FPA . DSPLMT := 0 ; if L . VRBL then begin LOAD ( L ) ; GENRR ( XLCR , L . RGADR , L . RGADR ) ; end (* then *) ; L . FPA . DSPLMT := Q ; end (* then *) ; end (* tag/ca *) ; (****************************************************) (* neu 09.2016 : addiere int zu adresse / oppolzer *) (* chg 11.2017 : error, when adr is second operand *) (****************************************************) PADA : begin //****************************************************** // if type of right operand = adr // exchange operands //****************************************************** if R . DTYPE = ADR then begin X := R ; R := L ; L := X ; end (* then *) ; if FALSE then begin WRITELN ( TRACEF , 'pada0: l.dtype = ' , L . DTYPE ) ; WRITELN ( TRACEF , 'pada0: r.dtype = ' , R . DTYPE ) ; WRITELN ( TRACEF , 'pada0: l.drct = ' , L . DRCT ) ; WRITELN ( TRACEF , 'pada0: r.drct = ' , R . DRCT ) ; WRITELN ( TRACEF , 'pada0: l.displ = ' , L . FPA . DSPLMT ) ; WRITELN ( TRACEF , 'pada0: r.displ = ' , R . FPA . DSPLMT ) ; end (* then *) ; if not L . DRCT then LOAD ( L ) ; if R . DRCT then begin L . FPA . DSPLMT := L . FPA . DSPLMT + R . FPA . DSPLMT ; R . FPA . DSPLMT := 0 end (* then *) ; OP1 := XAR ; OP2 := XA ; if R . VRBL then begin //****************************************************** // Q := L . FPA . DSPLMT ; // L . FPA . DSPLMT := 0 ; //****************************************************** LOAD ( L ) ; if R . DTYPE <> INT then if R . DTYPE = HINT then OP2 := OP2 - 16 else LOAD ( R ) ; if R . DRCT then if R . VPA = RGS then begin GENRR ( OP1 , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE end (* then *) else begin Q1 := R . MEMADR . DSPLMT ; P1 := R . MEMADR . LVL ; BASE ( Q1 , P1 , B1 ) ; GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) ; end (* else *) else begin GETOPERAND ( R , Q1 , P1 , B1 ) ; GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) ; end (* else *) ; L . FPA . DSPLMT := Q ; end (* then *) ; end (* tag/ca *) ; (****************************************************) (* neu 09.2019 : subtrahiere 2 adressen / oppolzer *) (****************************************************) PSBA : begin LOAD ( L ) ; OP1 := XSR ; OP2 := XS ; Q := L . FPA . DSPLMT ; L . FPA . DSPLMT := 0 ; LOAD ( R ) ; if R . DRCT then if R . VPA = RGS then begin GENRR ( OP1 , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE end (* then *) else begin Q1 := R . MEMADR . DSPLMT ; P1 := R . MEMADR . LVL ; BASE ( Q1 , P1 , B1 ) ; GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) ; end (* else *) else begin GETOPERAND ( R , Q1 , P1 , B1 ) ; GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) ; end (* else *) ; L . FPA . DSPLMT := Q ; end (* tag/ca *) ; (****************************************************) (* hier weiter alt - mpi *) (****************************************************) PMPI : begin if R . VRBL then begin if R . DTYPE = HINT then begin if ( not R . DRCT ) or ( R . VPA = MEM ) then begin LOAD ( L ) ; GETOPERAND ( R , Q1 , P1 , B1 ) ; GENRX ( XMH , L . RGADR , Q1 , P1 , B1 ) ; goto 30 ; end (* then *) ; end (* then *) ; MDTAG := PMPI ; LOAD ( L ) ; MDTAG := PBGN ; if R . DTYPE <> INT then LOAD ( R ) else GETOPERAND ( R , Q1 , P1 , B1 ) ; if ( not R . DRCT ) or ( R . VPA = MEM ) then GENRX ( XM , L . RGADR , Q1 , P1 , B1 ) else begin GENRR ( XMR , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE ; end (* else *) end (* then *) else (************) (*NOT R.VRBL*) (************) begin Q := 0 ; if ( L . DRCT ) then begin Q := L . FPA . DSPLMT * R . FPA . DSPLMT ; L . FPA . DSPLMT := 0 end (* then *) else LOAD ( L ) ; if L . VRBL then begin if ( R . FPA . DSPLMT >= - 32768 ) and ( R . FPA . DSPLMT <= 32767 ) then R . DTYPE := HINT ; P := POWER2 ( R . FPA . DSPLMT ) ; if ( P < 0 ) and ( R . DTYPE <> HINT ) then MDTAG := PMPI ; LOAD ( L ) ; MDTAG := PBGN ; L . FPA . DSPLMT := Q ; if P < 0 then if R . DTYPE <> HINT then GENRXLIT ( XM , L . RGADR , R . FPA . DSPLMT , 0 ) else begin GENRXLIT ( XMH , L . RGADR , R . FPA . DSPLMT , - 1 ) ; goto 30 ; end (* else *) else begin if P > 1 then GENRS ( XSLL , L . RGADR , 0 , P , 0 ) else if P > 0 then GENRR ( XAR , L . RGADR , L . RGADR ) ; goto 30 ; end (* else *) ; end (* then *) ; L . FPA . DSPLMT := Q ; end (* else *) ; if L . VRBL then AVAIL [ L . RGADR ] := TRUE ; L . RGADR := L . RGADR + 1 ; 30 : end (* tag/ca *) ; PDVI , PMOD : if not L . VRBL and not R . VRBL then (*****************) (* BOTH CONSTANTS*) (*****************) if R . FPA . DSPLMT = 0 then ERROR ( 300 ) (*******************) (* DIVISION BY ZERO*) (*******************) else if OPCODE = PDVI then L . FPA . DSPLMT := L . FPA . DSPLMT DIV R . FPA . DSPLMT else L . FPA . DSPLMT := L . FPA . DSPLMT MOD R . FPA . DSPLMT else (*********************) (* MORE COMMON CASES *) (*********************) begin MDTAG := PDVI ; LOAD ( L ) ; MDTAG := PBGN ; if R . VRBL then begin if R . DTYPE <> INT then LOAD ( R ) else GETOPERAND ( R , Q1 , P1 , B1 ) ; if not R . DRCT or ( R . VPA = MEM ) then GENRX ( XD , L . RGADR , Q1 , B1 , P1 ) else begin GENRR ( XDR , L . RGADR , R . RGADR ) ; AVAIL [ R . RGADR ] := TRUE end (* else *) end (* then *) else (*********) (*^R.VRBL*) (*********) GENRXLIT ( XD , L . RGADR , R . FPA . DSPLMT , 0 ) ; if OPCODE = PDVI then begin AVAIL [ L . RGADR ] := TRUE ; L . RGADR := L . RGADR + 1 end (* then *) else AVAIL [ L . RGADR + 1 ] := TRUE ; end (* else *) ; PAND , PIOR , PXOR : with R do begin OP1 := XNR ; if OPCODE = PIOR then OP1 := XORX else if OPCODE = PXOR then OP1 := XXR ; LOAD ( L ) ; LOAD ( R ) ; (*****************************************************) (* THIS CAN BE IMPROVED BY USING THE CONDITION CODE *) (* AS THE TOP ELEMENT *) (*****************************************************) GENRR ( OP1 , L . RGADR , RGADR ) ; AVAIL [ RGADR ] := TRUE ; end (* with *) ; PADR , PSBR : begin OP1 := XADR ; OP2 := XAD ; if OPCODE = PSBR then begin OP1 := XSDR ; OP2 := XSD end (* then *) ; LOAD ( L ) ; if R . VRBL then begin GETOPERAND ( R , Q1 , P1 , B1 ) ; if ( R . VPA = RGS ) and R . DRCT then begin GENRR ( OP1 , L . RGADR , R . RGADR ) ; AVAILFP [ R . RGADR ] := TRUE end (* then *) else (*************************) (* VPA = MEM OR NOT DRCT *) (*************************) GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) end (* then *) else (************) (* CONSTANT *) (************) GENRXDLIT ( OP2 , L . RGADR , R . RCNST ) end (* tag/ca *) ; PDVR , PMPR : begin LOAD ( L ) ; OP1 := XDDR ; OP2 := XDD ; if OPCODE = PMPR then begin OP1 := XMDR ; OP2 := XMD end (* then *) ; if R . VRBL then begin GETOPERAND ( R , Q1 , P1 , B1 ) ; if ( R . VPA = RGS ) and R . DRCT then begin GENRR ( OP1 , L . RGADR , R . RGADR ) ; AVAILFP [ R . RGADR ] := TRUE end (* then *) else (***************************) (* R.VPA = MEM OR NOT DRCT *) (***************************) GENRX ( OP2 , L . RGADR , Q1 , B1 , P1 ) end (* then *) else (**************) (* CONSTANT *) (**************) GENRXDLIT ( OP2 , L . RGADR , R . RCNST ) end (* tag/ca *) ; end (* case *) ; STK [ TOP - 1 ] := L ; end (* BOPERATION *) ; procedure CHECK_CHAR_LITERAL ; //***************************************************** // look if literal is already in pool // a literal qualifies, if // 1) it has type C // 2) it has a length >= the length of the new one // 3) it starts or ends with the same characters // as the new one //***************************************************** begin (* CHECK_CHAR_LITERAL *) LITOK := 0 ; for I := 1 to NXTLIT do with LITTBL [ I ] do if LTYPE = 'C' then if LENGTH >= SLNGTH then begin if MEMCMPX ( ADDR ( SVAL ) , ADDR ( IDP_POOL . C [ XIDP ] ) , SLNGTH ) = 0 then begin XOFFS := 0 ; LITOK := I ; break end (* then *) ; if LENGTH > SLNGTH then begin XOFFS := LENGTH - SLNGTH ; if MEMCMPX ( ADDR ( SVAL ) , ADDR ( IDP_POOL . C [ XIDP + XOFFS ] ) , SLNGTH ) = 0 then begin LITOK := I ; break end (* then *) ; end (* then *) end (* then *) ; //***************************************************** // if so, reuse; if not, add // reuse means: add entry in littbl, but don't add // literal to literal pool (reuse literal there) //***************************************************** if LITOK > 0 then begin TAG := 'use' ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := - TOP - 1 ; LITTBL [ NXTLIT ] . LTYPE := 'C' ; LITTBL [ NXTLIT ] . LENGTH := SLNGTH ; LITTBL [ NXTLIT ] . XIDP := LITTBL [ LITOK ] . XIDP + XOFFS ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'reuse lit.: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'reuse lit.: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'reuse lit.: lnk/pc = ' , - TOP - 1 ) ; WRITELN ( TRACEF , 'reuse lit.: ltype = ' , 'C' ) ; WRITELN ( TRACEF , 'reuse lit.: length = ' , SLNGTH ) ; WRITELN ( TRACEF , 'reuse lit.: xidp = ' , LITTBL [ NXTLIT ] . XIDP ) ; WRITELN ( TRACEF , 'reuse lit.: opt = ' , FALSE ) ; end (* then *) ; LITOK := NXTLIT ; end (* then *) else begin //***************************************************** // if new literal is stored // and nxtch lower than gaps // invalidate gaps //***************************************************** if LX . NXTCH <= LX . HW_GAP * 2 then begin LX . HW_GAP := - 1 ; LX . RHCONF := - 1 ; LX . IHCONF := - 1 end (* then *) ; if LX . NXTCH <= LX . INT_GAP * 4 then begin LX . INT_GAP := - 1 ; LX . RICONF := - 1 end (* then *) ; TAG := 'add' ; NXTLIT := NXTLIT + 1 ; LITTBL [ NXTLIT ] . XLINECNT := LINECNT ; LITTBL [ NXTLIT ] . LNK := - TOP - 1 ; LITTBL [ NXTLIT ] . LTYPE := 'C' ; LITTBL [ NXTLIT ] . LENGTH := SLNGTH ; LITTBL [ NXTLIT ] . XIDP := LX . NXTCH ; LITTBL [ NXTLIT ] . OPTIMIZED := FALSE ; if FALSE then begin WRITELN ( TRACEF , '----------------------------------' ) ; WRITELN ( TRACEF , 'add liter.: linecnt = ' , LINECNT ) ; WRITELN ( TRACEF , 'add liter.: index = ' , NXTLIT ) ; WRITELN ( TRACEF , 'add liter.: lnk/pc = ' , - TOP - 1 ) ; WRITELN ( TRACEF , 'add liter.: ltype = ' , 'C' ) ; WRITELN ( TRACEF , 'add liter.: length = ' , SLNGTH ) ; WRITELN ( TRACEF , 'add liter.: xidp = ' , LX . NXTCH ) ; WRITELN ( TRACEF , 'add liter.: opt = ' , FALSE ) ; end (* then *) ; LITOK := NXTLIT ; MEMCPY ( ADDR ( IDP_POOL . C [ LX . NXTCH ] ) , ADDR ( SVAL [ 1 ] ) , SLNGTH ) ; //***************************************************** // increment lx.nxtch // and adjust lx.nxtdbl // and set new gaps, if possible //***************************************************** LX . NXTCH := LX . NXTCH + SLNGTH ; LX . NXTDBL := LX . NXTCH DIV 8 ; I := LX . NXTDBL * 8 - LX . NXTCH ; if I < 0 then begin LX . NXTDBL := LX . NXTDBL + 1 ; I := I + 8 ; end (* then *) ; NXTINT := LX . NXTDBL * 2 ; if I >= 4 then begin I := I - 4 ; if LX . INT_GAP < 0 then begin LX . INT_GAP := NXTINT - 1 ; NXTINT := LX . INT_GAP ; LX . RICONF := LX . NXTDBL - 1 ; end (* then *) ; end (* then *) ; if I >= 2 then if LX . HW_GAP < 0 then begin LX . HW_GAP := 2 * NXTINT - 1 ; LX . RHCONF := LX . NXTDBL - 1 ; LX . IHCONF := NXTINT - 1 ; end (* then *) ; end (* else *) ; //***************************************************** // show entry info in literal pool //***************************************************** if FALSE then WRITELN ( TRACEF , TAG , ' literal nr. ' , LITOK : 1 , ' sval = ' , SVAL : SLNGTH ) ; end (* CHECK_CHAR_LITERAL *) ; begin (* ASMNXTINST *) if OPCODE in [ PXBG , PXEN ] then return ; if OLDOPCODE = PUJP then if not CASE_FLAG then (************************************) (* IGNORE INACCESSIBLE INSTRUCTIONS *) (************************************) if not ( OPCODE in [ PXLB , PEND , PCST , PLAB , PLOC , PDEF , PRET , PSTP , PENT , PCTS ] ) then return ; (********************************) (* XLATE COND CODE TO BOOL. VAL *) (********************************) if BRCND >= 0 then if not ( OPCODE in [ PFJP , PNOT , PLOC ] ) then with STK [ TOP - 1 ] do begin (****************************) (* JUST NEGATE TOP OF STACK *) (****************************) if NEG_CND then begin LOAD ( STK [ TOP - 1 ] ) ; if OPCODE = PAND then GENRR ( XBCTR , RGADR , 0 ) else GENRXLIT ( XX , RGADR , 1 , 0 ) ; end (* then *) (*************************************) (* OTHERWISE TRANSLATE CC TO BOOLEAN *) (*************************************) else begin FINDRG ; GENLA_LR ( NXTRG , 1 , 0 , 0 ) ; (*************) (*ASSUME TRUE*) (*************) GENRELRX ( XBC , BRCND , 3 ) ; (****************) (* BC BRCND,*+3 *) (****************) GENRR ( XSR , NXTRG , NXTRG ) ; (*********************************) (* THEN CHANGE TO FALSE IF NEEDED*) (*********************************) LAST_CC . LAST_PC := 0 ; (****************************) (* THIS C.C. HAS NO MEANING *) (****************************) DTYPE := BOOL ; VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; RGADR := NXTRG ; FPA := ZEROBL ; end (* else *) ; BRCND := - 1 ; NEG_CND := FALSE ; (*******************************) (* RESET C.C. FLAG TO INACTIVE *) (*******************************) end (* with *) ; if not CASE_FLAG then if ( NXTLIT >= LITDANGER ) or ( LX . NXTDBL >= DBLDANGER ) then begin (******************************) (* EMPTY THE LITERAL POOL NOW *) (******************************) GENRX ( XBC , ANYCND , 0 , 0 , 0 ) ; I := PCOUNTER - 1 ; DUMP_LITERALS ; CODE . H [ I ] := TO_HINT ( BASE_DSPLMT ( PCOUNTER ) ) ; end (* then *) ; /********************************/ /* verarbeitung abh. vom opcode */ /********************************/ if FALSE then begin WRITELN ( TRACEF ) ; WRITELN ( TRACEF ) ; WRITELN ( TRACEF , 'linecnt = ' , LINECNT : 1 ) ; WRITELN ( TRACEF , 'stack vor pcode = ' , PTBL [ OPCODE ] ) ; DUMPSTK ( 1 , TOP - 1 ) end (* then *) ; case OPCODE of PLOD : with STK [ TOP ] do begin if OPNDTYPE in [ ADR , INT , PSET ] then begin if ( Q MOD INTSIZE ) <> 0 then ERROR ( 611 ) ; end (* then *) else if OPNDTYPE = REEL then begin if ( Q MOD REALSIZE ) <> 0 then ERROR ( 612 ) ; end (* then *) else if OPNDTYPE = HINT then begin if ODD ( Q ) then ERROR ( 610 ) end (* then *) ; DTYPE := OPNDTYPE ; VRBL := TRUE ; DRCT := TRUE ; FPA := ZEROBL ; VPA := MEM ; MEMADR . LVL := P ; MEMADR . DSPLMT := Q ; with LAST_STR do if LAST_PC = PCOUNTER then (********************************) (* TRY TO OPTIMIZE STR/LOD PAIR *) (********************************) if MEMADR = STOPND then if OPNDTYPE = STDT then (******************************) (* IN CASE OF VARIANT RECORDS *) (******************************) begin VPA := RGS ; RGADR := STRGX ; if OPNDTYPE <> REEL then begin if not AVAIL [ RGADR ] then begin FINDRG ; GENRR ( XLR , NXTRG , RGADR ) ; RGADR := NXTRG ; end (* then *) ; AVAIL [ RGADR ] := FALSE ; end (* then *) else begin if not AVAILFP [ RGADR ] then begin FINDFP ; GENRR ( XLDR , NXTRG , RGADR ) ; RGADR := NXTRG ; end (* then *) ; AVAILFP [ RGADR ] := FALSE ; end (* else *) ; end (* then *) ; PROCNAME := ' ' ; TOP := TOP + 1 ; end (* with *) ; PSTR : begin if OPNDTYPE <> NON then begin TOP := TOP - 1 ; if OPNDTYPE in [ ADR , INT , PSET ] then begin if ( Q MOD INTSIZE ) <> 0 then ERROR ( 611 ) ; end (* then *) else if OPNDTYPE = REEL then begin if ( Q MOD REALSIZE ) <> 0 then ERROR ( 612 ) ; end (* then *) else if OPNDTYPE = HINT then begin if ODD ( Q ) then ERROR ( 610 ) ; end (* then *) ; with LAST_STR do (***********************************) (* SAVE INFO ABOUT STORED VARIABLE *) (***********************************) begin STOPND . LVL := P ; STOPND . DSPLMT := Q ; STDT := OPNDTYPE ; STORE ( TOP , FALSE ) ; if OPNDTYPE <= CHRC then LAST_PC := 0 else LAST_PC := PCOUNTER ; STRGX := STK [ TOP ] . RGADR ; end (* with *) end (* then *) end (* tag/ca *) ; PSTO : begin STORE ( TOP - 1 , TRUE ) ; (**********) (*INDIRECT*) (**********) TOP := TOP - 2 end (* tag/ca *) ; PLDA : with STK [ TOP ] do begin STK [ TOP ] := DATNULL ; DTYPE := ADR ; VRBL := FALSE ; DRCT := TRUE ; FPA . LVL := P ; FPA . DSPLMT := Q ; PROCNAME := ' ' ; TOP := TOP + 1 ; if FALSE then begin WRITELN ( TRACEF , 'DUMPSTK nach LDA' ) ; DUMPSTK ( TOP - 1 , TOP - 1 ) end (* then *) ; end (* with *) ; PLDC : with STK [ TOP ] do begin STK [ TOP ] := DATNULL ; DTYPE := OPNDTYPE ; VRBL := FALSE ; FPA := ZEROBL ; DRCT := TRUE ; VPA := NEITHER ; case OPNDTYPE of ADR : FPA . DSPLMT := - 1 ; // LDC NIL BOOL , CHRC , HINT , INT : FPA . DSPLMT := IVAL ; REEL : RCNST := RVAL ; PSET : ERROR ( 616 ) ; end (* case *) ; PROCNAME := ' ' ; TOP := TOP + 1 ; end (* with *) ; PIND : with STK [ TOP - 1 ] do begin if DTYPE <> ADR then ERROR ( 602 ) ; if VRBL then begin if not DRCT then LOAD ( STK [ TOP - 1 ] ) ; FPA . DSPLMT := FPA . DSPLMT + Q ; DRCT := FALSE ; end (* then *) else begin MEMADR := FPA ; MEMADR . DSPLMT := MEMADR . DSPLMT + Q ; FPA := ZEROBL ; VRBL := TRUE ; VPA := MEM ; DRCT := TRUE ; end (* else *) ; DTYPE := OPNDTYPE ; end (* with *) ; PLCA : with STK [ TOP ] do begin STK [ TOP ] := DATNULL ; DTYPE := ADR ; PROCNAME := ' ' ; case OPNDTYPE of //************************************************************ // load address of set constant //************************************************************ PSET : begin VRBL := FALSE ; DRCT := TRUE ; VPA := NEITHER ; PLEN := PSLNGTH ; if PLEN > 0 then begin NEW ( PCNST ) ; PCNST -> := PSVAL end (* then *) else PCNST := NIL ; DTYPE := PSET ; end (* tag/ca *) ; //************************************************************ // load address of procedure //************************************************************ PROC : begin VRBL := TRUE ; DRCT := TRUE ; VPA := RGS ; FINDRG ; RGADR := NXTRG ; PROCNAME := LBL2 . NAM ; if FALSE then begin WRITELN ( 'PLCA mit Procname = ' , PROCNAME ) ; WRITELN ( 'und gleich LA dazu' ) end (* then *) ; GENRXLAB ( XL , RGADR , LBL2 , - 3 ) ; end (* tag/ca *) ; //************************************************************ // load address of constant string //************************************************************ CARR : begin CHECK_CHAR_LITERAL ; //***************************************************** // REF. TO EXP. STACK //***************************************************** SCNSTNO := LITOK ; FPA . LVL := - 1 ; FPA . DSPLMT := LITTBL [ LITOK ] . XIDP ; VRBL := FALSE ; DRCT := TRUE ; if FALSE then begin WRITELN ( TRACEF , 'DUMPSTK nach LCA x' ) ; DUMPSTK ( TOP , TOP ) end (* then *) ; end (* tag/ca *) ; otherwise ERROR ( 601 ) end (* case *) ; TOP := TOP + 1 ; end (* with *) ; PIXA : begin TOP := TOP - 1 ; with STK [ TOP ] do begin if not DRCT then LOAD ( STK [ TOP ] ) ; if not ( DTYPE in [ ADR , HINT , INT , BOOL , CHRC ] ) then ERROR ( 601 ) ; FPA . DSPLMT := FPA . DSPLMT * Q ; if VRBL then begin if VPA = MEM then begin FINDRG ; P1 := MEMADR . LVL ; Q1 := MEMADR . DSPLMT ; BASE ( Q1 , P1 , B1 ) ; if DTYPE in [ CHRC , BOOL ] then begin GENRR ( XSR , NXTRG , NXTRG ) ; GENRX ( XIC , NXTRG , Q1 , B1 , P1 ) ; end (* then *) else if DTYPE = HINT then GENRX ( XLH , NXTRG , Q1 , B1 , P1 ) else (*********) (*INT,ADR*) (*********) GENRX ( XL , NXTRG , Q1 , B1 , P1 ) ; VPA := RGS ; RGADR := NXTRG ; end (* then *) ; (***********************) (* VPA IS IN A REG. NOW*) (***********************) if Q > HALFINT then ERROR ( 504 ) ; (*****************************) (* TOO LARGE FOR A HALF WORD *) (*****************************) Q2 := POWER2 ( Q ) ; if Q2 = 1 then GENRR ( XAR , RGADR , RGADR ) else if Q2 > 0 then GENRS ( XSLA , RGADR , 0 , Q2 , 0 ) else if Q2 < 0 then GENRXLIT ( XMH , RGADR , Q , - 2 ) ; (********) (*=H'Q' *) (********) end (* then *) ; (*************************************) (* NOW ADD THE TOP TO THE SECOND TOP *) (*************************************) with STK [ TOP - 1 ] do begin if not VRBL then if FPA . LVL < 0 then (*****************************************) (*I.E. INDEXING THROUGH A CONSTANT STRING*) (*****************************************) LOAD ( STK [ TOP - 1 ] ) ; if not DRCT then LOAD ( STK [ TOP - 1 ] ) ; end (* with *) ; STK [ TOP - 1 ] . FPA . DSPLMT := STK [ TOP - 1 ] . FPA . DSPLMT + FPA . DSPLMT ; FPA . DSPLMT := 0 ; if VRBL and STK [ TOP - 1 ] . VRBL then if VPA = RGS then if STK [ TOP - 1 ] . VPA = RGS then (********************************************) (* BOTH OPERANDWS IN REGS *) (* free reg with higher number - opp / 2016 *) (********************************************) (* klappt nicht ... *) (********************************************) begin GENRR ( XAR , STK [ TOP - 1 ] . RGADR , RGADR ) ; AVAIL [ RGADR ] := TRUE ; if FALSE then begin RGADR1 := STK [ TOP - 1 ] . RGADR ; RGADR2 := RGADR ; if RGADR1 < RGADR2 then begin GENRR ( XAR , RGADR1 , RGADR2 ) ; AVAIL [ RGADR2 ] := TRUE end (* then *) else begin GENRR ( XAR , RGADR2 , RGADR1 ) ; AVAIL [ RGADR1 ] := TRUE end (* else *) end (* then *) end (* then *) else (**********************************) (*TOP IN REG., 2_ND TOP IN MEMORY.*) (**********************************) begin Q1 := STK [ TOP - 1 ] . MEMADR . DSPLMT ; P1 := STK [ TOP - 1 ] . MEMADR . LVL ; BASE ( Q1 , P1 , B1 ) ; GENRX ( XA , RGADR , Q1 , B1 , P1 ) ; STK [ TOP - 1 ] . VPA := RGS ; STK [ TOP - 1 ] . RGADR := RGADR ; end (* else *) else (***********) (*VPA = MEM*) (***********) begin if STK [ TOP - 1 ] . VPA <> RGS then LOAD ( STK [ TOP - 1 ] ) ; Q1 := MEMADR . DSPLMT ; P1 := MEMADR . LVL ; BASE ( Q1 , P1 , B1 ) ; GENRX ( XA , STK [ TOP - 1 ] . RGADR , Q1 , B1 , P1 ) ; end (* else *) else (*********************************) (*NOT (VRBL AND STK[TOP-1].VRBL) *) (*********************************) if VRBL then begin FPA . LVL := STK [ TOP - 1 ] . FPA . LVL ; FPA . DSPLMT := STK [ TOP - 1 ] . FPA . DSPLMT ; DTYPE := ADR ; STK [ TOP - 1 ] := STK [ TOP ] ; end (* then *) end (* with *) ; end (* tag/ca *) ; PPAK : begin TOP := TOP - 2 ; PACK_UNPACK ( STK [ TOP ] , STK [ TOP + 1 ] ) ; end (* tag/ca *) ; PMOV : begin TOP := TOP - 2 ; if Q > 0 then begin // FORWARD MOVE SOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , OPCODE , Q ) end (* then *) else begin // BACKWARD MOVE Q := ABS ( Q ) ; SOPERATION ( STK [ TOP + 1 ] , STK [ TOP ] , OPCODE , Q ) ; end (* else *) ; end (* tag/ca *) ; PMV1 : begin OPCODE := PMOV ; TOP := TOP - 2 ; if Q > 0 then begin // FORWARD MOVE SOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , OPCODE , Q ) end (* then *) else begin // BACKWARD MOVE Q := ABS ( Q ) ; SOPERATION ( STK [ TOP + 1 ] , STK [ TOP ] , OPCODE , Q ) ; end (* else *) ; TOP := TOP + 1 ; end (* tag/ca *) ; PDBG : ; PMFI : begin if Q > 0 then begin TOP := TOP - 2 ; MFIOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , Q ) end (* then *) else begin Q := ABS ( Q ) ; TOP := TOP - 1 ; MFIOPERATION ( STK [ TOP - 2 ] , STK [ TOP ] , Q ) end (* else *) ; end (* tag/ca *) ; PMZE : begin TOP := TOP - 1 ; MZEOPERATION ( STK [ TOP ] , Q ) ; end (* tag/ca *) ; PMCP : begin TOP := TOP - 3 ; MCPOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , STK [ TOP + 2 ] ) ; end (* tag/ca *) ; PMSE : begin TOP := TOP - 3 ; MSEOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , STK [ TOP + 2 ] , Q ) ; end (* tag/ca *) ; PMCC : begin TOP := TOP - 2 ; MCCOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , Q ) ; TOP := TOP + 1 ; end (* tag/ca *) ; PMCV : begin TOP := TOP - 3 ; MCVOPERATION ( STK [ TOP ] , STK [ TOP + 1 ] , STK [ TOP + 2 ] ) ; TOP := TOP + 1 ; end (* tag/ca *) ; (*****************************) (* CONTROL/BRANCH OPERATIONS *) (*****************************) PUJP , PFJP , PXJP , PPOP , PCUP , PENT , PLOC , PXLB , PUXJ , PMST , PRET , PCSP , PSTP , PLAB , PDEF , PDFC , PCST , PEND : COPERATION ; PCHK : CHKOPERATION ; (********************) (* UNARY OPERATIONS *) (********************) PABI , PABR , PNGI , PNGR , PINC , PDEC , PNOT , PODD , PCHR , PORD , PFLO , PFLT , PNEW , PSAV , PRST , PSQI , PSQR , PCTS , PCTI , PXPO : UOPERATION ; (*********************) (* BINARY OPERATIONS *) (*********************) PADI , PSBI , PMPI , PDVI , PMOD , PAND , PIOR , PADR , PSBR , PMPR , PDVR , PADA , PSBA , PXOR : begin TOP := TOP - 1 ; BOPERATION end (* tag/ca *) ; PEQU , PNEQ , PLES , PLEQ , PGRT , PGEQ : begin TOP := TOP - 1 ; BOPERATION_COMPARE ; end (* tag/ca *) ; (******************) (* SET OPERATIONS *) (******************) PINN , PINT , PUNI , PDIF , PASE , PASR : begin TOP := TOP - 1 ; BSETOPS end (* tag/ca *) ; PSCL , PCRD , PSMV , PSLD : CSETOPS ; //************************************************************ // vstring instructions //************************************************************ PVPU , PVPO : STRINGOPS ; PVLD , PVST : STRINGOPS ; PVC1 , PVCC , PVLM , PVIX , PVRP : STRINGOPS ; PVC2 , PVMV , PVSM : STRINGOPS ; PBGN : ; // do nothing on BGN otherwise // otherwise show error ERROR_SYMB ( 620 , PTBL [ OPCODE ] ) end (* case *) ; if FALSE then begin WRITELN ( TRACEF , 'stack nach pcode = ' , PTBL [ OPCODE ] ) ; DUMPSTK ( 1 , TOP - 1 ) ; WRITELN ( TRACEF , '--------------------------------------' , '--------------------------------------' ) ; end (* then *) ; OLDOPCODE := OPCODE ; end (* ASMNXTINST *) ; procedure SETUP ; (*********************************************) (* INITIALIZE GLOBAL VARIABLE/SET FLAGS ETC. *) (*********************************************) var I : INTEGER ; begin (* SETUP *) GS . IN_PROCBODY := FALSE ; GS . FILL_LINEPTR := FALSE ; GS . MOD1DEFSTEP := - 1 ; GS . MOD2DEFSTEP := - 1 ; GS . XBG_XEN_SUPPRESSED := - 1 ; EMPTY := ' ' ; BRMSK [ PEQU ] := 8 ; BRMSK [ PNEQ ] := 7 ; BRMSK [ PGEQ ] := 11 ; BRMSK [ PGRT ] := 2 ; BRMSK [ PLEQ ] := 13 ; BRMSK [ PLES ] := 4 ; INVBRM [ PEQU ] := PEQU ; INVBRM [ PNEQ ] := PNEQ ; INVBRM [ PGEQ ] := PLEQ ; INVBRM [ PGRT ] := PLES ; INVBRM [ PLEQ ] := PGEQ ; INVBRM [ PLES ] := PGRT ; for I := 0 to HTSIZE do HTBL [ I ] . NAME := EMPTY ; OP_SP := TRUE ; for OPCODE := PCTS to PRED ( UNDEF_OP ) do begin P_OPCODE := PTBL [ OPCODE ] ; ENTERLOOKUP end (* for *) ; OP_SP := FALSE ; for CSP := PCTR to PRED ( UNDEF_CSP ) do begin P_OPCODE := CSPTBL [ CSP ] ; ENTERLOOKUP end (* for *) ; OP_SP := TRUE ; (******************************) (*TO PREPARE FOR OPCODE LOOKUP*) (******************************) for NXTRG := 0 to RGCNT do AVAIL [ NXTRG ] := TRUE ; for NXTRG := 0 to FPCNT do AVAILFP [ NXTRG ] := TRUE ; //**************************************** // set typecode depending on type letter // no numbers !! //**************************************** for CH := 'A' to 'Z' do TYPCDE [ CH ] := NON ; TYPCDE [ 'A' ] := ADR ; TYPCDE [ 'B' ] := BOOL ; TYPCDE [ 'C' ] := CHRC ; TYPCDE [ 'I' ] := INT ; TYPCDE [ 'H' ] := HINT ; TYPCDE [ 'M' ] := CARR ; TYPCDE [ 'S' ] := PSET ; TYPCDE [ 'P' ] := PROC ; TYPCDE [ 'R' ] := REEL ; TYPCDE [ 'N' ] := ADR ; TYPCDE [ 'J' ] := INX ; TYPCDE [ 'V' ] := VARC ; TOP := 1 ; CURLVL := 1 ; BRCND := - 1 ; NEG_CND := FALSE ; TRACE := FALSE ; OLDOPCODE := PBGN ; CSPACTIVE [ TRG1 ] := FALSE ; MDTAG := PBGN ; TXRG := TRG14 ; MUSIC := FALSE ; ZEROBL . LVL := 0 ; ZEROBL . DSPLMT := 0 ; ERRORCNT := 0 ; S370CNT := 0 ; LCAFTSAREA := LCAFTMST ; SAVEFPRS := TRUE ; CLEAR_REG := TRUE ; TOTALBYTES := 0 ; CASE_FLAG := FALSE ; CASE_FLAG_NEW := FALSE ; FILECNT := 0 ; CKMODE := FALSE ; ASM := FALSE ; CST_ASMVERB := FALSE ; DEBUG := TRUE ; FLOW_TRACE := FALSE ; NXTLIT := 0 ; LX . NXTDBL := 0 ; LAST_CC . LAST_PC := 0 ; TXR_CONTENTS . VALID := FALSE ; LAST_MVC . LAST_PC := 0 ; LAST_STR . LAST_PC := 0 ; LAST_STR . STOPND := ZEROBL ; OPT_FLG := TRUE ; HEXCHARS := '0123456789ABCDEF' ; TESTCNT := 0 ; PDEF_CNT := 0 ; CSPACTIVE [ 0 ] := FALSE ; CSPACTIVE [ 1 ] := FALSE ; CSPACTIVE [ 2 ] := FALSE ; CSPACTIVE [ 3 ] := FALSE ; CSPACTIVE [ 4 ] := FALSE ; CSPACTIVE [ 5 ] := FALSE ; CSPACTIVE [ 6 ] := FALSE ; CSPACTIVE [ 7 ] := FALSE ; CSPACTIVE [ 8 ] := FALSE ; CSPACTIVE [ 9 ] := FALSE ; CSPACTIVE [ 10 ] := FALSE ; CSPACTIVE [ 11 ] := FALSE ; CSPACTIVE [ 12 ] := FALSE ; CSPACTIVE [ 13 ] := FALSE ; CSPACTIVE [ 14 ] := FALSE ; CSPACTIVE [ 15 ] := FALSE ; FILADR_LOADED := FALSE ; OLDCSP := PSIO ; PROCOFFSET_OLD := 0 ; PCOUNTER := 0 ; TOS_COUNT := 0 ; end (* SETUP *) ; procedure CHK_INCLUDE ; var INCLUDECMD : CHAR ( 100 ) ; INCLFILE : CHAR ( 8 ) ; begin (* CHK_INCLUDE *) //************************************************** // check for %INCLUDE // if so, change input file from PCODE to PCODEx //************************************************** if PCODE_FILENO = 0 then begin if PCODE -> = '%' then begin READLN ( PCODE , INCLUDECMD ) ; if LEFT ( INCLUDECMD , 9 ) <> '%INCLUDE ' then ERROR ( 710 ) else begin INCLFILE := SUBSTR ( INCLUDECMD , 10 , 8 ) ; if LEFT ( INCLFILE , 5 ) <> 'pcode' then ERROR ( 711 ) ; case INCLFILE [ 6 ] of '1' : begin RESET ( PCODE1 ) ; PCODE_FILENO := 1 ; PCODEP := ADDR ( PCODE1 ) ; end (* tag/ca *) ; '2' : begin RESET ( PCODE2 ) ; PCODE_FILENO := 2 ; PCODEP := ADDR ( PCODE2 ) ; end (* tag/ca *) ; '3' : begin RESET ( PCODE3 ) ; PCODE_FILENO := 3 ; PCODEP := ADDR ( PCODE3 ) ; end (* tag/ca *) ; otherwise ERROR ( 712 ) end (* case *) end (* else *) end (* then *) end (* then *) ; end (* CHK_INCLUDE *) ; begin (* HAUPTPROGRAMM *) RESET ( PCODE ) ; FIRST_LIST002 := TRUE ; INIT := TRUE ; SETUP ; INIT := FALSE ; (************) (*INITIALIZE*) (************) if OSPARM <> NIL then with OSPARM -> do if PLENGTH >= 2 then for Q := 1 to PLENGTH - 1 do if ( PSTRING [ Q ] = 'T' ) and ( PSTRING [ Q + 1 ] = 'R' ) then TRACE := TRUE else if ( PSTRING [ Q ] = 'C' ) and ( PSTRING [ Q + 1 ] = 'K' ) then CKMODE := TRUE else if ( PSTRING [ Q ] = 'M' ) and ( PSTRING [ Q + 1 ] = 'U' ) then MUSIC := TRUE ; TIMER := CLOCK ( 0 ) ; WRITELN ( OUTPUT , '****' : 7 , ' STANFORD PASCAL POST-PROCESSOR, OPPOLZER VERSION OF ' , VERSION ) ; if not MUSIC then WRITELN ( OUTPUT ) ; //****************************************************************** // read pcode file first time to gather procedure information //****************************************************************** PIANKER := NIL ; XXIANKER := NIL ; PCODE_FILENO := 0 ; PCODEP := ADDR ( PCODE ) ; repeat CHK_INCLUDE ; EOF_PCODE := READNXTINST ( PCODEP -> , 1 ) ; if EOF_PCODE and ( PCODE_FILENO > 0 ) then begin PCODE_FILENO := 0 ; PCODEP := ADDR ( PCODE ) ; end (* then *) until OPCODE = PSTP ; if FALSE then begin PIAKT := PIANKER ; while PIAKT <> NIL do begin WRITELN ( TRACEF , 'information in procedure info chain' ) ; WRITELN ( TRACEF , '-----------------------------------' ) ; WRITELN ( TRACEF , 'CURPNAME...: ' , PIAKT -> . CURPNAME ) ; WRITELN ( TRACEF , 'CURPNO.....: ' , PIAKT -> . CURPNO ) ; WRITELN ( TRACEF , 'OPNDTYPE...: ' , PIAKT -> . OPNDTYPE ) ; WRITELN ( TRACEF , 'SEGSZE.....: ' , PIAKT -> . SEGSZE . NAM ) ; WRITELN ( TRACEF , 'SAVERGS....: ' , PIAKT -> . SAVERGS ) ; WRITELN ( TRACEF , 'ASM........: ' , PIAKT -> . ASM ) ; WRITELN ( TRACEF , 'ASMVERB....: ' , PIAKT -> . ASMVERB ) ; WRITELN ( TRACEF , 'GET_STAT...: ' , PIAKT -> . GET_STAT ) ; WRITELN ( TRACEF , 'DEBUG_LEV..: ' , PIAKT -> . DEBUG_LEV ) ; WRITELN ( TRACEF , 'STATNAME...: ' , PIAKT -> . STATNAME ) ; WRITELN ( TRACEF , 'SOURCENAME.: ' , PIAKT -> . SOURCENAME ) ; WRITELN ( TRACEF , 'FLOW_TRACE.: ' , PIAKT -> . FLOW_TRACE ) ; WRITELN ( TRACEF , 'CALL_HIGHER: ' , PIAKT -> . CALL_HIGHER ) ; WRITELN ( TRACEF , 'LARGE_PROC.: ' , PIAKT -> . LARGE_PROC ) ; WRITELN ( TRACEF , 'code_size..: ' , PIAKT -> . CODE_SIZE ) ; WRITELN ( TRACEF , 'DATA_SIZE..: ' , PIAKT -> . DATA_SIZE ) ; WRITELN ( TRACEF , 'scratchpos.: ' , PIAKT -> . SCRATCHPOS ) ; PIAKT := PIAKT -> . NEXT end (* while *) end (* then *) ; PIAKT := NIL ; //****************************************************************** // read pcode file second time to process p-codes // curpno must be set to minus 1 again, // otherwise the first LOC instruction will go wild ... // mark (heapmark) must be delayed after the first read loop :-) //****************************************************************** MARK ( HEAPMARK ) ; RESET ( PCODE ) ; repeat CHK_INCLUDE ; EOF_PCODE := READNXTINST ( PCODEP -> , 2 ) ; ASMNXTINST ; if TRACE then DUMPSTK ( 1 , TOP - 1 ) ; if EOF_PCODE and ( PCODE_FILENO > 0 ) then begin PCODE_FILENO := 0 ; PCODEP := ADDR ( PCODE ) ; end (* then *) until OPCODE = PSTP ; //****************************************************************** // check timer //****************************************************************** TIMER := CLOCK ( 0 ) - TIMER ; WRITE ( OUTPUT , '****' : 7 ) ; if ERRORCNT > 0 then WRITE ( OUTPUT , ERRORCNT : 8 ) else WRITE ( OUTPUT , 'NO' : 8 ) ; WRITELN ( OUTPUT , ' ASSEMBLY ERROR(S) DETECTED.' ) ; WRITELN ( OUTPUT , '****' : 7 , TOTALBYTES : 8 , ' BYTES OF CODE GENERATED,' , TIMER * 0.001 : 7 : 2 , ' SECONDS IN POST_PROCESSING.' ) ; if S370CNT > 0 then if FALSE then WRITELN ( OUTPUT , '****' : 7 , S370CNT : 8 , ' "370"-ONLY INSTRUCTION(S) ISSUED.' ) ; EXIT ( ERRORCNT ) ; end (* HAUPTPROGRAMM *) .
unit okEditors; interface uses SysUtils, Classes, Controls, cxControls, cxContainer, cxEdit, cxTextEdit, ExtCtrls, StdCtrls, Windows, Messages; const OK_DEF_CHANGE_DELAY = 500; WM_LAYOUTCHANGED = WM_USER + 17; type TokTextEdit = class(TcxTextEdit) private FTimer : TTimer; FOnDelayedChange: TNotifyEvent; FChangeDelay: Cardinal; FLng: TLabel; FShowLang: Boolean; procedure SetChangeDelay(const Value: Cardinal); procedure DoTimer(Sender : TObject); procedure WMLayoutChanged(var M: TMessage); message WM_LAYOUTCHANGED; procedure AdjustControls; procedure SetShowLang(const Value: Boolean); protected procedure ChangeHandler(Sender: TObject); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property ChangeDelay: Cardinal read FChangeDelay write SetChangeDelay default OK_DEF_CHANGE_DELAY; property OnDelayedChange: TNotifyEvent read FOnDelayedChange write FOnDelayedChange; property ShowLang: Boolean read FShowLang write setShowLang; end; //=============================================================================== //=============================================================================== //=============================================================================== implementation uses Graphics; //============================================================================================== function keyboardIndicator: String; begin case GetKeyboardLayout(0) mod $100 of $36: Result := 'AF'; $1c: Result := 'AL'; $01: Result := 'AR'; $2d: Result := 'BA'; $23: Result := 'BE'; $02: Result := 'BU'; $03: Result := 'CA'; $04: Result := 'CH'; $1a: Result := 'CR'; $05: Result := 'CZ'; $06: Result := 'DA'; $13: Result := 'DU'; $09: Result := 'EN'; $25: Result := 'ES'; $38: Result := 'FA'; $29: Result := 'FA'; $0b: Result := 'FI'; $0c: Result := 'FR'; $07: Result := 'GE'; $08: Result := 'GR'; $0d: Result := 'HE'; $0e: Result := 'HU'; $0f: Result := 'IC'; $21: Result := 'IN'; $10: Result := 'IT'; $11: Result := 'JA'; $12: Result := 'KO'; $26: Result := 'LA'; $27: Result := 'LI'; $14: Result := 'NO'; $15: Result := 'PO'; $16: Result := 'PO'; $18: Result := 'RO'; $19: Result := 'RU'; $1b: Result := 'SL'; $24: Result := 'SL'; $0a: Result := 'SP'; $1d: Result := 'SW'; $1e: Result := 'TH'; $1f: Result := 'TU'; $22: Result := 'UK'; $2a: Result := 'VI'; //$422: Result := 'UA'; //$419: Result := 'RU'; //$409: Result := 'EN'; else Result := '??'; end; end; { TokTextEdit } //=============================================================================== procedure TokTextEdit.ChangeHandler(Sender: TObject); begin inherited; if (FTimer.Interval > 0) and Assigned(FOnDelayedChange) then begin FTimer.Enabled := False; FTimer.Enabled := True; end else DoTimer(Sender); end; //=============================================================================== constructor TokTextEdit.Create(AOwner: TComponent); begin inherited; FTimer := TTimer.Create(nil); with FTimer do begin Enabled := False; Interval := OK_DEF_CHANGE_DELAY; OnTimer := DoTimer; end; FChangeDelay := OK_DEF_CHANGE_DELAY; FLng := TLabel.Create(Self); with FLng do begin Font.Style := [fsBold]; //DisabledDraw := ddUser; //DisabledColor := clBtnShadow; Parent := Self; Caption := keyboardIndicator; end; FShowLang := True; setShowLang(False); end; //=============================================================================== destructor TokTextEdit.Destroy; begin FTimer.Free; FLng.Destroy; inherited; end; //=============================================================================== procedure TokTextEdit.AdjustControls; begin FLng.Top := 0; FLng.Left := 0; inherited; end; //=============================================================================== procedure TokTextEdit.DoTimer(Sender: TObject); begin FTimer.Enabled := False; if Assigned(FOnDelayedChange) then FOnDelayedChange(Sender); end; //=============================================================================== procedure TokTextEdit.SetChangeDelay(const Value: Cardinal); begin FChangeDelay := Value; FTimer.Interval := Value; end; //=============================================================================== procedure TokTextEdit.SetShowLang(const Value: Boolean); begin if FShowLang = Value then Exit; FShowLang := Value; FLng.Visible := FShowLang; AdjustControls; end; //=============================================================================== procedure TokTextEdit.WMLayoutChanged(var M: TMessage); begin FLng.Caption := keyboardIndicator; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: TSnmpCli class encapsulate the SNMP client paradigm Creation: March 2011 Version: 1.01 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2011 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> The Initial Developer of the Original Code is Lukas Gebauer. This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: May 11, 2012 V1.01 Arno - Unit did not compile with Ansi Delphi |==============================================================================| | Copyright (c)1999-2007, Lukas Gebauer | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are met: | | | | Redistributions of source code must retain the above copyright notice, this | | list of conditions and the following disclaimer. | | | | Redistributions in binary form must reproduce the above copyright notice, | | this list of conditions and the following disclaimer in the documentation | | and/or other materials provided with the distribution. | | | | Neither the name of Lukas Gebauer nor the names of its contributors may | | be used to endorse or promote products derived from this software without | | specific prior written permission. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR | | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH | | DAMAGE. | |==============================================================================| * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$Q-} {$H+} unit OverbyteIcsSnmpMsgs; interface uses Windows, Classes, SysUtils, OverbyteIcsMD5, OverbyteIcsSHA1, OverbyteIcsAsn1Utils; const SnmpMsgsVersion = 101; CopyRight : String = ' AnmpMsgs (c) 2011 Francois Piette V1.01 '; const cSnmpProtocol = '161'; cSnmpTrapProtocol = '162'; SNMP_V1 = 0; SNMP_V2C = 1; SNMP_V3 = 3; //PDU type PDUGetRequest = $A0; PDUGetNextRequest = $A1; PDUGetResponse = $A2; PDUSetRequest = $A3; PDUTrap = $A4; //Obsolete //for SNMPv2 PDUGetBulkRequest = $A5; PDUInformRequest = $A6; PDUTrapV2 = $A7; PDUReport = $A8; //errors ENoError = 0; ETooBig = 1; ENoSuchName = 2; EBadValue = 3; EReadOnly = 4; EGenErr = 5; //errors SNMPv2 ENoAccess = 6; EWrongType = 7; EWrongLength = 8; EWrongEncoding = 9; EWrongValue = 10; ENoCreation = 11; EInconsistentValue = 12; EResourceUnavailable = 13; ECommitFailed = 14; EUndoFailed = 15; EAuthorizationError = 16; ENotWritable = 17; EInconsistentName = 18; SnmpErrorStrings : array [ENoError..EInconsistentName] of String = ( // EnoError 'No error occurred', // ETooBig 'The size of the Response-PDU would be too large to transport', // ENoSuchName 'The name of a requested object was not found', // EBadValue 'A value in the request didn''t match the structure that the ' + 'recipient of the request had for the object', // EReadOnly 'An attempt was made to set a variable that has an Access value ' + 'indicating that it is read-only', // EGenErr 'An error occurred other than one indicated by a more specific error code', // ENoAccess 'Access was denied to the object for security reasons', // EWrongType 'The object type in a variable binding is incorrect for the object', // EWrongLength 'A variable binding specifies a length incorrect for the object', // EWrongEncoding 'A variable binding specifies an encoding incorrect for the object', // EWrongValue 'The value given in a variable binding is not possible for the object', // ENoCreation 'A specified variable does not exist and cannot be created', // EInconsistentValue 'A variable binding specifies a value that could be held by the ' + 'variable but cannot be assigned to it at this time', // EResourceUnavailable 'An attempt to set a variable required a resource that is not available', // ECommitFailed 'An attempt to set a particular variable failed', // EUndoFailed 'An attempt to set a particular variable as part of a group of ' + 'variables failed, and the attempt to then undo the setting of ' + 'other variables was not successful', // EAuthorizationError 'A problem occurred in authorization', // ENotWritable 'The variable cannot be written or created', // EInconsistentName 'The name in a variable binding specifies a variable that does not exist'); type {:@abstract(Possible values for SNMPv3 flags.) This flags specify level of authorization and encryption.} TV3Flags = ( NoAuthNoPriv, AuthNoPriv, AuthPriv); {:@abstract(Type of SNMPv3 authorization)} TV3Auth = ( AuthMD5, AuthSHA1); {:@abstract(Data object with one record of MIB OID and corresponding values.)} TSNMPMib = class(TObject) protected FOID: AnsiString; FValue: AnsiString; FValueType: Integer; public {:OID number in string format.} property OID: AnsiString read FOID write FOID; {:Value of OID object in string format.} property Value: AnsiString read FValue write FValue; {:Define type of Value. Supported values are defined in @link(asn1util). For queries use ASN1_NULL, becouse you don't know type in response!} property ValueType: Integer read FValueType write FValueType; end; {:@abstract(It holding all information for SNMPv3 agent synchronization) Used internally.} TV3Sync = record EngineID: AnsiString; EngineBoots: integer; EngineTime: integer; EngineStamp: Cardinal; end; {:@abstract(Data object abstracts SNMP data packet)} TSNMPRec = class(TObject) protected FVersion: Integer; FPDUType: Integer; FID: Integer; FErrorStatus: Integer; FErrorIndex: Integer; FCommunity: AnsiString; FSNMPMibList: TList; FMaxSize: Integer; FFlags: TV3Flags; FFlagReportable: Boolean; FContextEngineID: AnsiString; FContextName: AnsiString; FAuthMode: TV3Auth; FAuthEngineID: AnsiString; FAuthEngineBoots: integer; FAuthEngineTime: integer; FAuthEngineTimeStamp: cardinal; FUserName: AnsiString; FPassword: AnsiString; FAuthKey: AnsiString; FPrivKey: AnsiString; FOldTrapEnterprise: AnsiString; FOldTrapHost: AnsiString; FOldTrapGen: Integer; FOldTrapSpec: Integer; FOldTrapTimeTicks: Integer; function Pass2Key(const Value: AnsiString): AnsiString; public constructor Create; destructor Destroy; override; {:Decode SNMP packet in buffer to object properties.} function DecodeBuf(const Buffer: AnsiString): Boolean; {:Encode obeject properties to SNMP packet.} function EncodeBuf: AnsiString; {:Clears all object properties to default values.} procedure Clear; {:Add entry to @link(SNMPMibList). For queries use value as empty string, and ValueType as ASN1_NULL.} procedure MIBAdd(const MIB, Value: AnsiString; ValueType: Integer); {:Delete entry from @link(SNMPMibList).} procedure MIBDelete(Index: Integer); {:Search @link(SNMPMibList) list for MIB and return correspond value.} function MIBGet(const MIB: AnsiString): AnsiString; {:return number of entries in MIB array.} function MIBCount: integer; {:Return MIB information from given row of MIB array.} function MIBByIndex(Index: Integer): TSNMPMib; {:List of @link(TSNMPMib) objects.} property SNMPMibList: TList read FSNMPMibList; public {:Version of SNMP packet. Default value is 0 (SNMP ver. 1). You can use value 1 for SNMPv2c or value 3 for SNMPv3.} property Version: Integer read FVersion write FVersion; {:Community string for autorize access to SNMP server. (Case sensitive!) Community string is not used in SNMPv3! Use @link(Username) and @link(password) instead!} property Community: AnsiString read FCommunity write FCommunity; {:Define type of SNMP operation.} property PDUType: Integer read FPDUType write FPDUType; {:Contains ID number. Not need to use.} property ID: Integer read FID write FID; {:When packet is reply, contains error code. Supported values are defined by E* constants.} property ErrorStatus: Integer read FErrorStatus write FErrorStatus; {:Point to error position in reply packet. Not usefull for users. It only good for debugging!} property ErrorIndex: Integer read FErrorIndex write FErrorIndex; {:special value for GetBulkRequest of SNMPv2 and v3.} property NonRepeaters: Integer read FErrorStatus write FErrorStatus; {:special value for GetBulkRequest of SNMPv2 and v3.} property MaxRepetitions: Integer read FErrorIndex write FErrorIndex; {:Maximum message size in bytes for SNMPv3. For sending is default 1472 bytes.} property MaxSize: Integer read FMaxSize write FMaxSize; {:Specify if message is authorised or encrypted. Used only in SNMPv3, and encryption is not yet supported!} property Flags: TV3Flags read FFlags write FFlags; {:For SNMPv3.... If is @true, SNMP agent must send reply (at least with some error).} property FlagReportable: Boolean read FFlagReportable write FFlagReportable; {:For SNMPv3. If not specified, is used value from @link(AuthEngineID)} property ContextEngineID: AnsiString read FContextEngineID write FContextEngineID; {:For SNMPv3.} property ContextName: AnsiString read FContextName write FContextName; {:For SNMPv3. Specify Authorization mode. (specify used hash for authorization)} property AuthMode: TV3Auth read FAuthMode write FAuthMode; {:value used by SNMPv3 authorisation for synchronization with SNMP agent.} property AuthEngineID: AnsiString read FAuthEngineID write FAuthEngineID; {:value used by SNMPv3 authorisation for synchronization with SNMP agent.} property AuthEngineBoots: Integer read FAuthEngineBoots write FAuthEngineBoots; {:value used by SNMPv3 authorisation for synchronization with SNMP agent.} property AuthEngineTime: Integer read FAuthEngineTime write FAuthEngineTime; {:value used by SNMPv3 authorisation for synchronization with SNMP agent.} property AuthEngineTimeStamp: Cardinal read FAuthEngineTimeStamp Write FAuthEngineTimeStamp; {:SNMPv3 authorization username} property UserName: AnsiString read FUserName write FUserName; {:SNMPv3 authorization password} property Password: AnsiString read FPassword write FPassword; {:For SNMPv3. Computed Athorization key from @link(password).} property AuthKey: AnsiString read FAuthKey write FAuthKey; {:For SNMPv3. Encryption key for message encryption. Not yet used!} property PrivKey: AnsiString read FPrivKey write FPrivKey; {:MIB value to identify the object that sent the TRAPv1.} property OldTrapEnterprise: AnsiString read FOldTrapEnterprise write FOldTrapEnterprise; {:Address of TRAPv1 sender (IP address).} property OldTrapHost: AnsiString read FOldTrapHost write FOldTrapHost; {:Generic TRAPv1 identification.} property OldTrapGen: Integer read FOldTrapGen write FOldTrapGen; {:Specific TRAPv1 identification.} property OldTrapSpec: Integer read FOldTrapSpec write FOldTrapSpec; {:Number of 1/100th of seconds since last reboot or power up. (for TRAPv1)} property OldTrapTimeTicks: Integer read FOldTrapTimeTicks write FOldTrapTimeTicks; end; function SnmpErrorToString(ErrCode : Integer) : String; implementation {==============================================================================} constructor TSNMPRec.Create; begin inherited Create; FSNMPMibList := TList.Create; Clear; FID := 1; FMaxSize := 1472; end; destructor TSNMPRec.Destroy; var i: Integer; begin for i := 0 to FSNMPMibList.Count - 1 do TSNMPMib(FSNMPMibList[i]).Free; FSNMPMibList.Clear; FSNMPMibList.Free; inherited Destroy; end; {==============================================================================} // Extractect from synacode, ported to ICS-MD5 {:Returns a binary string with a RSA-MD5 hashing of string what is constructed by repeating "value" until length is "Len".} function MD5LongHash(const Value: AnsiString; Len: integer): AnsiString; var cnt, rest: integer; l: integer; n: integer; MDContext: TMD5Context; MD5Digest : TMD5Digest; I : Integer; begin l := length(Value); cnt := Len div l; rest := Len mod l; MD5DigestInit(MD5Digest); MD5Init(MDContext); for n := 1 to cnt do MD5UpdateBuffer(MDContext, Value); if rest > 0 then MD5UpdateBuffer(MDContext, Copy(Value, 1, rest)); MD5Final(MD5Digest, MDContext); MD5DigestToHex(MD5Digest); SetLength(Result, SizeOf(MD5Digest)); for i := 0 to SizeOf(MD5Digest) - 1 do Result := Result + AnsiChar(MD5Digest[i]); end; {==============================================================================} // Extractect from synacode, ported to ICS-SHA1 {:Returns a binary string with a SHA-1 hashing of string what is constructed by repeating "value" until length is "Len".} function SHA1LongHash(const Value: AnsiString; Len: integer): AnsiString; var cnt, rest: integer; l: integer; n: integer; SHAContext: SHA1Context; digest : SHA1Digest; I : Integer; begin l := length(Value); cnt := Len div l; rest := Len mod l; SHA1Reset(SHAContext); for n := 1 to cnt do SHA1Input(SHAContext, PAnsiChar(Value), Length(Value)); if rest > 0 then SHA1Input(SHAContext, PAnsiChar(Copy(Value, 1, rest)), rest); SHA1Result(SHAContext, digest); SetLength( Result, sizeof(digest) ); for I := 1 to sizeof(digest) do Result[I] := AnsiChar(digest[I - 1]); end; {==============================================================================} function TSNMPRec.Pass2Key(const Value: AnsiString): AnsiString; var key: AnsiString; begin case FAuthMode of AuthMD5: begin key := MD5LongHash(Value, 1048576); Result := StrMD5(key + FAuthEngineID + key); // Not sure it must be hex ! end; AuthSHA1: begin key := SHA1LongHash(Value, 1048576); Result := SHA1ofStr(key + FAuthEngineID + key); end; else Result := ''; end; end; // Extracted from Synautil {:Return current value of system timer with precizion 1 millisecond. Good for measure time difference.} function GetTick: LongWord; var tick, freq: TLargeInteger; begin if Windows.QueryPerformanceFrequency(freq) then begin Windows.QueryPerformanceCounter(tick); Result := Trunc((tick / freq) * 1000) and High(LongWord) end else Result := Windows.GetTickCount; end; // Extracted from Synautil {:Return difference between two timestamps. It working fine only for differences smaller then maxint. (difference must be smaller then 24 days.)} function TickDelta(TickOld, TickNew: LongWord): LongWord; begin //if DWord is signed type (older Deplhi), // then it not work properly on differencies larger then maxint! Result := 0; if TickOld <> TickNew then begin if TickNew < TickOld then begin TickNew := TickNew + LongWord(MaxInt) + 1; TickOld := TickOld + LongWord(MaxInt) + 1; end; Result := TickNew - TickOld; if TickNew < TickOld then if Result > 0 then Result := 0 - Result; end; end; {==============================================================================} function TSNMPRec.DecodeBuf(const Buffer: AnsiString): Boolean; var Pos: Integer; EndPos: Integer; sm, sv: AnsiString; Svt: Integer; s: AnsiString; Spos: integer; x: Byte; begin Clear; Result := False; if Length(Buffer) < 2 then Exit; if (Ord(Buffer[1]) and $20) = 0 then Exit; Pos := 2; EndPos := ASNDecLen(Pos, Buffer); if Length(Buffer) < (EndPos + 2) then Exit; Self.FVersion := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); if FVersion = 3 then begin ASNItem(Pos, Buffer, Svt); //header data seq ASNItem(Pos, Buffer, Svt); //ID FMaxSize := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); s := ASNItem(Pos, Buffer, Svt); x := 0; if s <> '' then x := Ord(s[1]); FFlagReportable := (x and 4) > 0; x := x and 3; case x of 1: FFlags := AuthNoPriv; 3: FFlags := AuthPriv; else FFlags := NoAuthNoPriv; end; x := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); s := ASNItem(Pos, Buffer, Svt); //SecurityParameters //if SecurityModel is USM, then try to decode SecurityParameters if (x = 3) and (s <> '') then begin spos := 1; ASNItem(SPos, s, Svt); FAuthEngineID := ASNItem(SPos, s, Svt); FAuthEngineBoots := StrToIntDef(String(ASNItem(SPos, s, Svt)), 0); FAuthEngineTime := StrToIntDef(String(ASNItem(SPos, s, Svt)), 0); FAuthEngineTimeStamp := GetTick; FUserName := ASNItem(SPos, s, Svt); FAuthKey := ASNItem(SPos, s, Svt); FPrivKey := ASNItem(SPos, s, Svt); end; //scopedPDU s := ASNItem(Pos, Buffer, Svt); if Svt = ASN1_OCTSTR then begin //decrypt! end; FContextEngineID := ASNItem(Pos, Buffer, Svt); FContextName := ASNItem(Pos, Buffer, Svt); end else begin //old packet Self.FCommunity := ASNItem(Pos, Buffer, Svt); end; ASNItem(Pos, Buffer, Svt); Self.FPDUType := Svt; if Self.FPDUType = PDUTrap then begin FOldTrapEnterprise := ASNItem(Pos, Buffer, Svt); FOldTrapHost := ASNItem(Pos, Buffer, Svt); FOldTrapGen := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); FOldTrapSpec := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); FOldTrapTimeTicks := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); end else begin Self.FID := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); Self.FErrorStatus := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); Self.FErrorIndex := StrToIntDef(String(ASNItem(Pos, Buffer, Svt)), 0); end; ASNItem(Pos, Buffer, Svt); while Pos < EndPos do begin ASNItem(Pos, Buffer, Svt); Sm := ASNItem(Pos, Buffer, Svt); Sv := ASNItem(Pos, Buffer, Svt); Self.MIBAdd(sm, sv, Svt); end; Result := True; end; {==============================================================================} // Extracted from Synautil {:Returns a portion of the "Value" string located to the left of the "Delimiter" string. If a delimiter is not found, results is original string.} function SeparateLeft(const Value, Delimiter: string): string; var x: Integer; begin x := Pos(Delimiter, Value); if x < 1 then Result := Value else Result := Copy(Value, 1, x - 1); end; {==============================================================================} // Extracted from Synautil {:Returns the portion of the "Value" string located to the right of the "Delimiter" string. If a delimiter is not found, results is original string.} function SeparateRight(const Value, Delimiter: string): string; var x: Integer; begin x := Pos(Delimiter, Value); if x > 0 then x := x + Length(Delimiter) - 1; Result := Copy(Value, x + 1, Length(Value) - x); end; {==============================================================================} // Extracted from Synautil {:Like TrimLeft, but remove only spaces, not control characters!} function TrimSPLeft(const S: string): string; var I, L: Integer; begin Result := ''; if S = '' then Exit; L := Length(S); I := 1; while (I <= L) and (S[I] = ' ') do Inc(I); Result := Copy(S, I, Maxint); end; {==============================================================================} // Extracted from Synautil {:Like TrimRight, but remove only spaces, not control characters!} function TrimSPRight(const S: string): string; var I: Integer; begin Result := ''; if S = '' then Exit; I := Length(S); while (I > 0) and (S[I] = ' ') do Dec(I); Result := Copy(S, 1, I); end; {==============================================================================} // Extracted from Synautil {:Like Trim, but remove only spaces, not control characters!} function TrimSP(const S: string): string; begin Result := TrimSPLeft(s); Result := TrimSPRight(Result); end; {==============================================================================} // Extracted from Synautil function FetchBin(var Value: string; const Delimiter: string): string; var s: string; begin Result := SeparateLeft(Value, Delimiter); s := SeparateRight(Value, Delimiter); if s = Value then Value := '' else Value := s; end; {==============================================================================} // Extracted from Synautil function Fetch(var Value: string; const Delimiter: string): string; begin Result := FetchBin(Value, Delimiter); Result := TrimSP(Result); Value := TrimSP(Value); end; {==============================================================================} // Extracted from synaip function IPToID(Host: string): Ansistring; {$IFDEF UNICODE} overload; {$ENDIF} var s: string; i, x: Integer; begin Result := ''; for x := 0 to 3 do begin s := Fetch(Host, '.'); i := StrToIntDef(s, 0); Result := Result + AnsiChar(Chr(i)); end; end; {$IFDEF UNICODE} function IPToID(Host: AnsiString): Ansistring; overload; begin Result := IPToId(String(Host)); end; {$ENDIF} {==============================================================================} function My_HMAC_MD5(Text, Key: AnsiString): AnsiString; var Digest: TMD5Digest; I : Integer; begin HMAC_MD5(PAnsiChar(Text)^, Length(Text), PAnsiChar(Key)^, Length(Key), Digest); SetLength(Result, SizeOf(Digest)); for I := 0 to SizeOf(Digest) - 1 do Result[I + 1] := AnsiChar(Digest[I]); end; {==============================================================================} function My_HMAC_SHA1(Text, Key: AnsiString): AnsiString; var Digest: SHA1Digest; I : Integer; begin HMAC_SHA1(PAnsiChar(Text)^, Length(Text), PAnsiChar(Key)^, Length(Key), Digest); SetLength(Result, SizeOf(Digest)); for I := 0 to SizeOf(Digest) - 1 do Result[I + 1] := AnsiChar(Digest[I]); end; {==============================================================================} function TSNMPRec.EncodeBuf: AnsiString; var s: AnsiString; SNMPMib: TSNMPMib; n: Integer; pdu, head, auth, authbeg: AnsiString; x: Byte; begin pdu := ''; for n := 0 to FSNMPMibList.Count - 1 do begin SNMPMib := TSNMPMib(FSNMPMibList[n]); case SNMPMib.ValueType of ASN1_INT: s := ASNObject(MibToID(SNMPMib.OID), ASN1_OBJID) + ASNObject(ASNEncInt(StrToIntDef(String(SNMPMib.Value), 0)), SNMPMib.ValueType); ASN1_COUNTER, ASN1_GAUGE, ASN1_TIMETICKS: s := ASNObject(MibToID(SNMPMib.OID), ASN1_OBJID) + ASNObject(ASNEncUInt(StrToIntDef(String(SNMPMib.Value), 0)), SNMPMib.ValueType); ASN1_OBJID: s := ASNObject(MibToID(SNMPMib.OID), ASN1_OBJID) + ASNObject(MibToID(SNMPMib.Value), SNMPMib.ValueType); ASN1_IPADDR: s := ASNObject(MibToID(SNMPMib.OID), ASN1_OBJID) + ASNObject(IPToID(SNMPMib.Value), SNMPMib.ValueType); ASN1_NULL: s := ASNObject(MibToID(SNMPMib.OID), ASN1_OBJID) + ASNObject('', ASN1_NULL); else s := ASNObject(MibToID(SNMPMib.OID), ASN1_OBJID) + ASNObject(SNMPMib.Value, SNMPMib.ValueType); end; pdu := pdu + ASNObject(s, ASN1_SEQ); end; pdu := ASNObject(pdu, ASN1_SEQ); if Self.FPDUType = PDUTrap then pdu := ASNObject(MibToID(FOldTrapEnterprise), ASN1_OBJID) + ASNObject(IPToID(FOldTrapHost), ASN1_IPADDR) + ASNObject(ASNEncInt(FOldTrapGen), ASN1_INT) + ASNObject(ASNEncInt(FOldTrapSpec), ASN1_INT) + ASNObject(ASNEncUInt(FOldTrapTimeTicks), ASN1_TIMETICKS) + pdu else pdu := ASNObject(ASNEncInt(Self.FID), ASN1_INT) + ASNObject(ASNEncInt(Self.FErrorStatus), ASN1_INT) + ASNObject(ASNEncInt(Self.FErrorIndex), ASN1_INT) + pdu; pdu := ASNObject(pdu, Self.FPDUType); if FVersion = 3 then begin if FContextEngineID = '' then FContextEngineID := FAuthEngineID; //complete PDUv3... pdu := ASNObject(FContextEngineID, ASN1_OCTSTR) + ASNObject(FContextName, ASN1_OCTSTR) + pdu; //maybe encrypt pdu... in future pdu := ASNObject(pdu, ASN1_SEQ); //prepare flags case FFlags of AuthNoPriv: x := 1; AuthPriv: x := 3; else x := 0; end; if FFlagReportable then x := x or 4; head := ASNObject(ASNEncInt(Self.FVersion), ASN1_INT); s := ASNObject(ASNEncInt(FID), ASN1_INT) + ASNObject(ASNEncInt(FMaxSize), ASN1_INT) + ASNObject(AnsiChar(x), ASN1_OCTSTR) //encode security model USM + ASNObject(ASNEncInt(3), ASN1_INT); head := head + ASNObject(s, ASN1_SEQ); //compute engine time difference x := TickDelta(FAuthEngineTimeStamp, GetTick) div 1000; authbeg := ASNObject(FAuthEngineID, ASN1_OCTSTR) + ASNObject(ASNEncInt(FAuthEngineBoots), ASN1_INT) + ASNObject(ASNEncInt(FAuthEngineTime + x), ASN1_INT) + ASNObject(FUserName, ASN1_OCTSTR); case FFlags of AuthNoPriv, AuthPriv: begin s := authbeg + ASNObject(StringOfChar(AnsiChar(#0), 12), ASN1_OCTSTR) + ASNObject(FPrivKey, ASN1_OCTSTR); s := ASNObject(s, ASN1_SEQ); s := head + ASNObject(s, ASN1_OCTSTR); s := ASNObject(s + pdu, ASN1_SEQ); //in s is entire packet without auth info... case FAuthMode of AuthMD5: begin s := My_HMAC_MD5(s, Pass2Key(FPassword) + StringOfChar(AnsiChar(#0), 48)); //strip to HMAC-MD5-96 delete(s, 13, 4); end; AuthSHA1: begin s := My_HMAC_SHA1(s, Pass2Key(FPassword) + StringOfChar(AnsiChar(#0), 44)); //strip to HMAC-SHA-96 delete(s, 13, 8); end; else s := ''; end; FAuthKey := s; end; end; auth := authbeg + ASNObject(FAuthKey, ASN1_OCTSTR) + ASNObject(FPrivKey, ASN1_OCTSTR); auth := ASNObject(auth, ASN1_SEQ); head := head + ASNObject(auth, ASN1_OCTSTR); Result := ASNObject(head + pdu, ASN1_SEQ); end else begin head := ASNObject(ASNEncInt(Self.FVersion), ASN1_INT) + ASNObject(Self.FCommunity, ASN1_OCTSTR); Result := ASNObject(head + pdu, ASN1_SEQ); end; // inc(self.FID); // F.Piette: Bug: encoding should not change the fields end; procedure TSNMPRec.Clear; var i: Integer; begin FVersion := SNMP_V1; FCommunity := 'public'; FUserName := ''; FPassword := ''; FPDUType := 0; FErrorStatus := 0; FErrorIndex := 0; for i := 0 to FSNMPMibList.Count - 1 do TSNMPMib(FSNMPMibList[i]).Free; FSNMPMibList.Clear; FOldTrapEnterprise := ''; FOldTrapHost := ''; FOldTrapGen := 0; FOldTrapSpec := 0; FOldTrapTimeTicks := 0; FFlags := NoAuthNoPriv; FFlagReportable := false; FContextEngineID := ''; FContextName := ''; FAuthMode := AuthMD5; FAuthEngineID := ''; FAuthEngineBoots := 0; FAuthEngineTime := 0; FAuthEngineTimeStamp := 0; FAuthKey := ''; FPrivKey := ''; end; {==============================================================================} procedure TSNMPRec.MIBAdd(const MIB, Value: AnsiString; ValueType: Integer); var SNMPMib: TSNMPMib; begin SNMPMib := TSNMPMib.Create; SNMPMib.OID := MIB; SNMPMib.Value := Value; SNMPMib.ValueType := ValueType; FSNMPMibList.Add(SNMPMib); end; {==============================================================================} procedure TSNMPRec.MIBDelete(Index: Integer); begin if (Index >= 0) and (Index < MIBCount) then begin TSNMPMib(FSNMPMibList[Index]).Free; FSNMPMibList.Delete(Index); end; end; {==============================================================================} function TSNMPRec.MIBCount: integer; begin Result := FSNMPMibList.Count; end; {==============================================================================} function TSNMPRec.MIBByIndex(Index: Integer): TSNMPMib; begin Result := nil; if (Index >= 0) and (Index < MIBCount) then Result := TSNMPMib(FSNMPMibList[Index]); end; {==============================================================================} function TSNMPRec.MIBGet(const MIB: AnsiString): AnsiString; var i: Integer; begin Result := ''; for i := 0 to MIBCount - 1 do begin if ((TSNMPMib(FSNMPMibList[i])).OID = MIB) then begin Result := (TSNMPMib(FSNMPMibList[i])).Value; Break; end; end; end; {==============================================================================} // Extracted from synautil {:If string is binary string (contains non-printable characters), then is returned true.} function IsBinaryString(const Value: string): Boolean; var n: integer; begin Result := False; for n := 1 to Length(Value) do {$IFDEF UNICODE} if CharInSet(Value[n], [#0..#8, #10..#31]) then {$ELSE} if Value[n] in [#0..#8, #10..#31] then {$ENDIF} //ignore null-terminated strings if not ((n = Length(value)) and (Value[n] = #0)) then begin Result := True; Break; end; end; {==============================================================================} // Extracted from synautil {:Returns a string with hexadecimal digits representing the corresponding values of the bytes found in "Value" string.} function StrToHex(const Value: Ansistring): string; var n: Integer; begin Result := ''; for n := 1 to Length(Value) do Result := Result + IntToHex(Byte(Value[n]), 2); Result := LowerCase(Result); end; {==============================================================================} function SnmpErrorToString(ErrCode : Integer) : String; begin if (ErrCode >= Low(SnmpErrorStrings)) or (ErrCode <= High(SnmpErrorStrings)) then Result := SnmpErrorStrings[Errcode] else Result := 'SNMP error #' + IntToStr(ErrCode); end; {==============================================================================} end.
unit Cviceni; (* Trida TCviceni *) interface uses SysUtils, Classes, Graphics, Controls, StdCtrls, Windows, Messages, Variants, Forms, Dialogs, ComCtrls, Buttons, ExtCtrls, MyUtils; type TCviceni = class (TPanel) private FNazev,FLabel1,FLabel2:TLabel; FMinut,FKomentar:TEdit; FDelka:Integer; procedure onMinutExit(Sender: TObject); procedure setDelka(Value:Integer); procedure setDelkaStr(Value:String); function getNazev():String; function getDelkaStr():String; public procedure setNazev(Value:String); virtual; procedure VykresliPopis(Cvs:TCanvas; sirka,vyska:integer; var now_y:integer); virtual; constructor Create(AOwner: TComponent); override; property Nazev:String read getNazev write setNazev; property NazevLabel:TLabel read FNazev write FNazev; property Delka:Integer read FDelka write setDelka; property DelkaStr:String read getDelkaStr write setDelkaStr; property Label1:TLabel read FLabel1 write FLabel1; property Label2:TLabel read FLabel2 write FLabel2; property Minut:TEdit read FMinut write FMinut; property Komentar:TEdit read FKomentar write FKomentar; end; implementation (* procedure TCviceni.VykresliPopis FUNKCE: Do zadaneho Canvasu vypise udaje o cviceni... ARGUMENTY: Cvs - Canvas do ktereho se ma kreslit sirka - sirka plochy do ktere se kresli vyska - vyska plochy do ktere se kresli now_y - souradnice 'y' v plose kam se kresli (na jaky radek) *) procedure TCviceni.VykresliPopis(Cvs:TCanvas; sirka,vyska:integer; var now_y:integer); var dilek_x,dilek_y,now_x:integer; begin if (Delka>0) or (Komentar.Text<>'') then with Cvs do begin dilek_x:=round(Sirka/190); dilek_y:=round(Vyska/265); now_x:=dilek_x*5; Font.Height:=dilek_y*(-3); //vypise pocet minut a nazev cviceni Font.Style:=[fsBold]; TextOut(now_x,now_y,DelkaStr+' min'); now_x:=now_x+TextWidth('000 min')+dilek_x*5; TextOut(now_x,now_y,Nazev); now_x:=now_x+TextWidth(Nazev)+dilek_x*5; //vypise komentar/popis cviceni Font.Style:=[]; VypisTextDoObrazku(Cvs,now_x,sirka-dilek_x*5,now_y,Komentar.Text); now_y:=now_y+TextHeight('M')+dilek_y; end; end; procedure TCviceni.setNazev(Value:String); begin FNazev.Caption:=Value; end; function TCviceni.getNazev():String; begin Result:=FNazev.Caption; end; function TCviceni.getDelkaStr():String; begin Result:=IntToStr(FDelka); end; procedure TCviceni.setDelka(Value:Integer); begin FDelka:=Value; Minut.Text:=IntToStr(Value); end; procedure TCviceni.setDelkaStr(Value:String); begin FDelka:=StrToInt(Value); Minut.Text:=Value; end; procedure TCviceni.onMinutExit(Sender: TObject); begin Minut.Text:=ZpracujNaCislo(Minut.Text); DelkaStr:=Minut.Text; end; constructor TCviceni.Create(AOwner: TComponent); begin inherited; Width:=541; Height:=23; Left:=2; BevelInner:=bvNone; BevelOuter:=bvNone; Font.Style:=[]; //vytvoreni polozek NazevLabel:=TLabel.Create(nil); Label1:=TLabel.Create(nil); Label2:=TLabel.Create(nil); Minut:=TEdit.Create(nil); Komentar:=TEdit.Create(nil); //zobrazeni polozek NazevLabel.Parent:=self; Label1.Parent:=self; Label2.Parent:=self; Minut.Parent:=self; Komentar.Parent:=self; //umisteni polozek vodorovne NazevLabel.Left:=16; Label1.Left:=196; Label2.Left:=264; Minut.Left:=168; Komentar.Left:=320; //umisteni polozek svisle NazevLabel.Top:=4; Label1.Top:=4; Label2.Top:=4; Minut.Top:=1; Komentar.Top:=1; //velikost TEditu Minut.Width:=25; Minut.Height:=21; Komentar.Width:=200; Komentar.Height:=21; //zadani zakladnich textu NazevLabel.Caption:='Název cvičení:'; Label1.Caption:='minut'; Label2.Caption:='Komentář:'; Minut.Text:='0'; Komentar.Text:=''; Delka:=0; //fonty textu NazevLabel.Font.Style:=[]; Label1.Font.Style:=[]; Label2.Font.Style:=[]; Minut.Font.Style:=[fsBold]; Komentar.Font.Style:=[]; //nastaveni akci Minut.OnExit:=onMinutExit; end; end.
unit TTSPasswordOptionsTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSPasswordOptionsRecord = record PExpireDays: Integer; PHistorySize: Integer; PMinDaysUsage: Integer; PMinLength: Integer; PMinChangedChars: Integer; PMaxLoginAttempts: Integer; PNameInPassword: String[3]; PAutoReset: String[3]; PAutoResetPeriod: Integer; PAutoResetUnit: String[1]; PCriteriaCount: Integer; PCriteria: Integer; PLastUpdate: TDateTime; PUserName: String[10]; PEncryptionVersion: Integer; End; TTTSPasswordOptionsBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSPasswordOptionsRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSPasswordOptions = (TTSPasswordOptionsPrimaryKey); TTTSPasswordOptionsTable = class( TDBISAMTableAU ) private FDFExpireDays: TIntegerField; FDFHistorySize: TIntegerField; FDFMinDaysUsage: TIntegerField; FDFMinLength: TIntegerField; FDFMinChangedChars: TIntegerField; FDFMaxLoginAttempts: TIntegerField; FDFNameInPassword: TStringField; FDFAutoReset: TStringField; FDFAutoResetPeriod: TIntegerField; FDFAutoResetUnit: TStringField; FDFCriteriaCount: TIntegerField; FDFCriteria: TIntegerField; FDFLastUpdate: TDateTimeField; FDFUserName: TStringField; FDFEncryptionVersion: TIntegerField; procedure SetPExpireDays(const Value: Integer); function GetPExpireDays:Integer; procedure SetPHistorySize(const Value: Integer); function GetPHistorySize:Integer; procedure SetPMinDaysUsage(const Value: Integer); function GetPMinDaysUsage:Integer; procedure SetPMinLength(const Value: Integer); function GetPMinLength:Integer; procedure SetPMinChangedChars(const Value: Integer); function GetPMinChangedChars:Integer; procedure SetPMaxLoginAttempts(const Value: Integer); function GetPMaxLoginAttempts:Integer; procedure SetPNameInPassword(const Value: String); function GetPNameInPassword:String; procedure SetPAutoReset(const Value: String); function GetPAutoReset:String; procedure SetPAutoResetPeriod(const Value: Integer); function GetPAutoResetPeriod:Integer; procedure SetPAutoResetUnit(const Value: String); function GetPAutoResetUnit:String; procedure SetPCriteriaCount(const Value: Integer); function GetPCriteriaCount:Integer; procedure SetPCriteria(const Value: Integer); function GetPCriteria:Integer; procedure SetPLastUpdate(const Value: TDateTime); function GetPLastUpdate:TDateTime; procedure SetPUserName(const Value: String); function GetPUserName:String; procedure SetPEncryptionVersion(const Value: Integer); function GetPEncryptionVersion:Integer; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSPasswordOptions); function GetEnumIndex: TEITTSPasswordOptions; 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:TTTSPasswordOptionsRecord; procedure StoreDataBuffer(ABuffer:TTTSPasswordOptionsRecord); property DFExpireDays: TIntegerField read FDFExpireDays; property DFHistorySize: TIntegerField read FDFHistorySize; property DFMinDaysUsage: TIntegerField read FDFMinDaysUsage; property DFMinLength: TIntegerField read FDFMinLength; property DFMinChangedChars: TIntegerField read FDFMinChangedChars; property DFMaxLoginAttempts: TIntegerField read FDFMaxLoginAttempts; property DFNameInPassword: TStringField read FDFNameInPassword; property DFAutoReset: TStringField read FDFAutoReset; property DFAutoResetPeriod: TIntegerField read FDFAutoResetPeriod; property DFAutoResetUnit: TStringField read FDFAutoResetUnit; property DFCriteriaCount: TIntegerField read FDFCriteriaCount; property DFCriteria: TIntegerField read FDFCriteria; property DFLastUpdate: TDateTimeField read FDFLastUpdate; property DFUserName: TStringField read FDFUserName; property DFEncryptionVersion: TIntegerField read FDFEncryptionVersion; property PExpireDays: Integer read GetPExpireDays write SetPExpireDays; property PHistorySize: Integer read GetPHistorySize write SetPHistorySize; property PMinDaysUsage: Integer read GetPMinDaysUsage write SetPMinDaysUsage; property PMinLength: Integer read GetPMinLength write SetPMinLength; property PMinChangedChars: Integer read GetPMinChangedChars write SetPMinChangedChars; property PMaxLoginAttempts: Integer read GetPMaxLoginAttempts write SetPMaxLoginAttempts; property PNameInPassword: String read GetPNameInPassword write SetPNameInPassword; property PAutoReset: String read GetPAutoReset write SetPAutoReset; property PAutoResetPeriod: Integer read GetPAutoResetPeriod write SetPAutoResetPeriod; property PAutoResetUnit: String read GetPAutoResetUnit write SetPAutoResetUnit; property PCriteriaCount: Integer read GetPCriteriaCount write SetPCriteriaCount; property PCriteria: Integer read GetPCriteria write SetPCriteria; property PLastUpdate: TDateTime read GetPLastUpdate write SetPLastUpdate; property PUserName: String read GetPUserName write SetPUserName; property PEncryptionVersion: Integer read GetPEncryptionVersion write SetPEncryptionVersion; published property Active write SetActive; property EnumIndex: TEITTSPasswordOptions read GetEnumIndex write SetEnumIndex; end; { TTTSPasswordOptionsTable } procedure Register; implementation function TTTSPasswordOptionsTable.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 { TTTSPasswordOptionsTable.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; { TTTSPasswordOptionsTable.GenerateNewFieldName } function TTTSPasswordOptionsTable.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; { TTTSPasswordOptionsTable.CreateField } procedure TTTSPasswordOptionsTable.CreateFields; begin FDFExpireDays := CreateField( 'ExpireDays' ) as TIntegerField; FDFHistorySize := CreateField( 'HistorySize' ) as TIntegerField; FDFMinDaysUsage := CreateField( 'MinDaysUsage' ) as TIntegerField; FDFMinLength := CreateField( 'MinLength' ) as TIntegerField; FDFMinChangedChars := CreateField( 'MinChangedChars' ) as TIntegerField; FDFMaxLoginAttempts := CreateField( 'MaxLoginAttempts' ) as TIntegerField; FDFNameInPassword := CreateField( 'NameInPassword' ) as TStringField; FDFAutoReset := CreateField( 'AutoReset' ) as TStringField; FDFAutoResetPeriod := CreateField( 'AutoResetPeriod' ) as TIntegerField; FDFAutoResetUnit := CreateField( 'AutoResetUnit' ) as TStringField; FDFCriteriaCount := CreateField( 'CriteriaCount' ) as TIntegerField; FDFCriteria := CreateField( 'Criteria' ) as TIntegerField; FDFLastUpdate := CreateField( 'LastUpdate' ) as TDateTimeField; FDFUserName := CreateField( 'UserName' ) as TStringField; FDFEncryptionVersion := CreateField( 'EncryptionVersion' ) as TIntegerField; end; { TTTSPasswordOptionsTable.CreateFields } procedure TTTSPasswordOptionsTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSPasswordOptionsTable.SetActive } procedure TTTSPasswordOptionsTable.SetPExpireDays(const Value: Integer); begin DFExpireDays.Value := Value; end; function TTTSPasswordOptionsTable.GetPExpireDays:Integer; begin result := DFExpireDays.Value; end; procedure TTTSPasswordOptionsTable.SetPHistorySize(const Value: Integer); begin DFHistorySize.Value := Value; end; function TTTSPasswordOptionsTable.GetPHistorySize:Integer; begin result := DFHistorySize.Value; end; procedure TTTSPasswordOptionsTable.SetPMinLength(const Value: Integer); begin DFMinLength.Value := Value; end; procedure TTTSPasswordOptionsTable.SetPMinDaysUsage(const Value: Integer); begin DFMinDaysUsage.Value := Value; end; function TTTSPasswordOptionsTable.GetPMinDaysUsage:Integer; begin result := DFMinDaysUsage.Value; end; function TTTSPasswordOptionsTable.GetPMinLength:Integer; begin result := DFMinLength.Value; end; procedure TTTSPasswordOptionsTable.SetPMinChangedChars(const Value: Integer); begin DFMinChangedChars.Value := Value; end; function TTTSPasswordOptionsTable.GetPMinChangedChars:Integer; begin result := DFMinChangedChars.Value; end; procedure TTTSPasswordOptionsTable.SetPMaxLoginAttempts(const Value: Integer); begin DFMaxLoginAttempts.Value := Value; end; function TTTSPasswordOptionsTable.GetPMaxLoginAttempts:Integer; begin result := DFMaxLoginAttempts.Value; end; procedure TTTSPasswordOptionsTable.SetPNameInPassword(const Value: String); begin DFNameInPassword.Value := Value; end; function TTTSPasswordOptionsTable.GetPNameInPassword:String; begin result := DFNameInPassword.Value; end; procedure TTTSPasswordOptionsTable.SetPAutoReset(const Value: String); begin DFAutoReset.Value := Value; end; function TTTSPasswordOptionsTable.GetPAutoReset:String; begin result := DFAutoReset.Value; end; procedure TTTSPasswordOptionsTable.SetPAutoResetPeriod(const Value: Integer); begin DFAutoResetPeriod.Value := Value; end; function TTTSPasswordOptionsTable.GetPAutoResetPeriod:Integer; begin result := DFAutoResetPeriod.Value; end; procedure TTTSPasswordOptionsTable.SetPAutoResetUnit(const Value: String); begin DFAutoResetUnit.Value := Value; end; function TTTSPasswordOptionsTable.GetPAutoResetUnit:String; begin result := DFAutoResetUnit.Value; end; procedure TTTSPasswordOptionsTable.SetPCriteriaCount(const Value: Integer); begin DFCriteriaCount.Value := Value; end; function TTTSPasswordOptionsTable.GetPCriteriaCount:Integer; begin result := DFCriteriaCount.Value; end; procedure TTTSPasswordOptionsTable.SetPCriteria(const Value: Integer); begin DFCriteria.Value := Value; end; function TTTSPasswordOptionsTable.GetPCriteria:Integer; begin result := DFCriteria.Value; end; procedure TTTSPasswordOptionsTable.SetPLastUpdate(const Value: TDateTime); begin DFLastUpdate.Value := Value; end; function TTTSPasswordOptionsTable.GetPLastUpdate:TDateTime; begin result := DFLastUpdate.Value; end; procedure TTTSPasswordOptionsTable.SetPUserName(const Value: String); begin DFUserName.Value := Value; end; function TTTSPasswordOptionsTable.GetPUserName:String; begin result := DFUserName.Value; end; procedure TTTSPasswordOptionsTable.SetPEncryptionVersion(const Value: Integer); begin DFEncryptionVersion.Value := Value; end; function TTTSPasswordOptionsTable.GetPEncryptionVersion:Integer; begin result := DFEncryptionVersion.Value; end; procedure TTTSPasswordOptionsTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('ExpireDays, Integer, 0, N'); Add('HistorySize, Integer, 0, N'); Add('MinDaysUsage, Integer, 0, N'); Add('MinLength, Integer, 0, N'); Add('MinChangedChars, Integer, 0, N'); Add('MaxLoginAttempts, Integer, 0, N'); Add('NameInPassword, String, 3, N'); Add('AutoReset, String, 3, N'); Add('AutoResetPeriod, Integer, 0, N'); Add('AutoResetUnit, String, 1, N'); Add('CriteriaCount, Integer, 0, N'); Add('Criteria, Integer, 0, N'); Add('LastUpdate, TDateTime, 0, N'); Add('UserName, String, 10, N'); Add('EncryptionVersion, Integer, 0, N'); end; end; procedure TTTSPasswordOptionsTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, UserName, Y, Y, N, N'); // Add('ByRights, UserGroup;UserName, N, N, N, N'); // Add('ByLenderGroup, LenderGroup;UserName, N, N, N, N'); end; end; procedure TTTSPasswordOptionsTable.SetEnumIndex(Value: TEITTSPasswordOptions); begin case Value of TTSPasswordOptionsPrimaryKey : IndexName := ''; // TTSUSERByRights : IndexName := 'ByRights'; // TTSUSERByLenderGroup : IndexName := 'ByLenderGroup'; end; end; function TTTSPasswordOptionsTable.GetDataBuffer:TTTSPasswordOptionsRecord; var buf: TTTSPasswordOptionsRecord; begin fillchar(buf, sizeof(buf), 0); buf.PExpireDays := DFExpireDays.Value; buf.PHistorySize := DFHistorySize.Value; buf.PMinDaysUsage := DFMinDaysUsage.Value; buf.PMinLength := DFMinLength.Value; buf.PMinChangedChars := DFMinChangedChars.Value; buf.PMaxLoginAttempts := DFMaxLoginAttempts.Value; buf.PNameInPassword := DFNameInPassword.Value; buf.PAutoReset := DFAutoReset.Value; buf.PAutoResetPeriod := DFAutoResetPeriod.Value; buf.PAutoResetUnit := DFAutoResetUnit.Value; buf.PCriteriaCount := DFCriteriaCount.Value; buf.PCriteria := DFCriteria.Value; buf.PLastUpdate := DFLastUpdate.Value; buf.PUserName := DFUserName.Value; buf.PEncryptionVersion := DFEncryptionVersion.Value; result := buf; end; procedure TTTSPasswordOptionsTable.StoreDataBuffer(ABuffer:TTTSPasswordOptionsRecord); begin DFExpireDays.Value := ABuffer.PExpireDays; DFHistorySize.Value := ABuffer.PHistorySize; DFMinDaysUsage.Value := ABuffer.PMinDaysUsage; DFMinLength.Value := ABuffer.PMinLength; DFMinChangedChars.Value := ABuffer.PMinChangedChars; DFMaxLoginAttempts.Value := ABuffer.PMaxLoginAttempts; DFNameInPassword.Value := ABuffer.PNameInPassword; DFAutoReset.Value := ABuffer.PAutoReset; DFAutoResetPeriod.Value := ABuffer.PAutoResetPeriod; DFAutoResetUnit.Value := ABuffer.PAutoResetUnit; DFCriteriaCount.Value := ABuffer.PCriteriaCount; DFCriteria.Value := ABuffer.PCriteria; DFLastUpdate.Value := ABuffer.PLastUpdate; DFUserName.Value := ABuffer.PUserName; DFEncryptionVersion.Value := ABuffer.PEncryptionVersion; end; function TTTSPasswordOptionsTable.GetEnumIndex: TEITTSPasswordOptions; var iname : string; begin result := TTSPasswordOptionsPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSPasswordOptionsPrimaryKey; // if iname = 'BYRIGHTS' then result := TTSUSERByRights; // if iname = 'BYLENDERGROUP' then result := TTSUSERByLenderGroup; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSPasswordOptionsTable, TTTSPasswordOptionsBuffer ] ); end; { Register } function TTTSPasswordOptionsBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..15] of string = ('EXPIREDAYS','HISTORYSIZE','MINDAYSUSAGE','MINLENGTH','MINCHANGEDCHARS','MAXLOGINATTEMPTS' ,'NAMEINPASSWORD','AUTORESET','AUTORESETPERIOD','AUTORESETUNIT','CRITERIACOUNT' ,'CRITERIA','LASTUPDATE','USERNAME','ENCRYPTIONVERSION' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 15) and (flist[x] <> s) do inc(x); if x <= 15 then result := x else result := 0; end; function TTTSPasswordOptionsBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftInteger; 2 : result := ftInteger; 3 : result := ftInteger; 4 : result := ftInteger; 5 : result := ftInteger; 6 : result := ftInteger; 7 : result := ftString; 8 : result := ftString; 9 : result := ftInteger; 10 : result := ftString; 11 : result := ftInteger; 12 : result := ftInteger; 13 : result := ftDateTime; 14 : result := ftString; 15 : result := ftInteger; end; end; function TTTSPasswordOptionsBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PExpireDays; 2 : result := @Data.PHistorySize; 3 : result := @Data.PMinDaysUsage; 4 : result := @Data.PMinLength; 5 : result := @Data.PMinChangedChars; 6 : result := @Data.PMaxLoginAttempts; 7 : result := @Data.PNameInPassword; 8 : result := @Data.PAutoReset; 9 : result := @Data.PAutoResetPeriod; 10 : result := @Data.PAutoResetUnit; 11 : result := @Data.PCriteriaCount; 12 : result := @Data.PCriteria; 13 : result := @Data.PLastUpdate; 14 : result := @Data.PUserName; 15 : result := @Data.PEncryptionVersion; end; end; end.
unit ParseGen_Lex; interface type symbol = (noSy, termSy, nonTermSy, isSy, identSy, equalSy, leftCurlSy, rightCurlSy, plusSy, mulSy, divSy, minusSy, leftParSy, rightParSy, dotSy, arrowLeftSy, arrowRightSy, leftOptSy, rightOptSy, leftIterSy, rightIterSy, leftSqBrSy, rightSqBrSy, barSy, orSy, ltSy, gtSy, numberSy, eofSy ); var sy : symbol; stringVal : string; numberVal : integer; identStr: string; procedure initLex(inFileName : string); procedure newSy; implementation const EOF_CH = chr(26); TAB_CH = chr(9); var inFile : text; line : string; linePos : integer; ch : char; procedure newCh; FORWARD; procedure initLex(inFileName : string); begin assign(inFile, inFileName); reset(inFile); line := ''; linePos := 0; newCh; end; procedure newSy; var isNonTerminal : boolean; begin while (ch = ' ') or (ch = TAB_CH) do newCh; case ch of '=': begin sy := isSy; newCh; end; '.': begin sy := dotSy; newCh; end; '{': begin sy := leftOptSy; newCh; end; '}': begin sy := rightOptSy; newCh; end; '<': begin sy := arrowLeftSy; newCh; end; '>': begin sy := arrowRightSy;newCh; end; '|': begin sy := orSy; newCh; end; EOF_CH: begin sy := eofSy; end; (* don't get a newCh because eof *) 'a'..'z','A'..'Z': begin identStr := ch; isNonTerminal := TRUE; if(ord(ch) >= ord('a')) and (ord(ch) <= ord('z')) then (* is lowercase *) isNonTerminal := FALSE; newCh; while ch in ['a'..'z','A'..'Z','0'..'9'] do begin identStr := identStr + ch; newCh; end; identStr := upCase(identStr); if identStr = 'IDENT' then sy := identSy else if identStr = 'EQUAL' then sy := equalSy else if identStr = 'LT' then sy := ltSy else if identStr = 'GT' then sy := gtSy else if identStr = 'LEFTPAR' then sy := leftParSy else if identStr = 'RIGHTPAR' then sy := rightParSy else if identStr = 'BAR' then sy := barSy else if identStr = 'LEFTOPT' then sy := leftOptSy else if identStr = 'RIGHTOPT' then sy := rightOptSy else if identStr = 'LEFTITER' then sy := leftIterSy else if identStr = 'RIGHTITER' then sy := rightIterSy else if identStr = 'LEFTBRACKET' then sy := leftSqBrSy else if identStr = 'RIGHTBRACKET' then sy := rightSqBrSy else if identStr = 'PLUS' then sy := plusSy else if identStr = 'MINUS' then sy := minusSy else if identStr = 'TIMES' then sy := mulSy else if identStr = 'DIV' then sy := divSy else if identStr = 'NUMBER' then sy := numberSy else begin if(isNonTerminal) then sy := identSy else sy := identSy; stringVal := lowerCase(identStr); end; end; else begin sy := noSy; end; end; writeln(sy); end; procedure newCh; begin inc(linePos); if linePos > length(line) then begin if not eof(inFile) then begin readLn(inFile, line); linePos := 0; ch := ' '; end else begin ch := EOF_CH; line := ''; linePos := 0; close(inFile); end; end else begin ch := line[linePos]; end; (* else *) end; begin end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Inicializar; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, IniFiles; type TfrmInicializa = class(TForm) grpDatos: TGroupBox; chkComprobantes: TCheckBox; chkProveedores: TCheckBox; chkUsuarios: TCheckBox; chkTiposPago: TCheckBox; chkAreasVenta: TCheckBox; chkDescuentos: TCheckBox; chkVentas: TCheckBox; chkDepartamentos: TCheckBox; chkCompras: TCheckBox; chkClientes: TCheckBox; chkCategorias: TCheckBox; chkExistencias: TCheckBox; chkArticulos: TCheckBox; chkVentasPendientes: TCheckBox; chkCortes: TCheckBox; chkRetiros: TCheckBox; btnAceptar: TBitBtn; btnCancelar: TBitBtn; chkEmpresa: TCheckBox; chkCajas: TCheckBox; chkTicket: TCheckBox; txtDiaIni: TEdit; txtMesIni: TEdit; txtAnioIni: TEdit; lblDiagDia1: TLabel; lblDiagMes1: TLabel; txtDiaFin: TEdit; txtMesFin: TEdit; txtAnioFin: TEdit; lblDiagDia2: TLabel; lblDiagMes2: TLabel; lblAl: TLabel; chkXCobrar: TCheckBox; chkXPagar: TCheckBox; chkInventario: TCheckBox; procedure btnAceptarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure chkVentasClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtAnioIniExit(Sender: TObject); procedure txtAnioFinExit(Sender: TObject); procedure txtDiaIniExit(Sender: TObject); private procedure IniArticulos; procedure IniExistencias; procedure IniCategorias; procedure IniClientes; procedure IniCompras; procedure IniDepartamentos; procedure IniProveedores; procedure IniUsuarios; procedure IniAreasVenta; procedure IniDescuentos; procedure IniVentas; procedure IniVentasPendientes; procedure RecuperaConfig; procedure IniComprobantes; procedure IniRetiros; procedure IniTiposPago; procedure IniCortes; procedure IniEmpresa; procedure IniCajas; procedure IniTicket; procedure IniXCobrar; procedure IniXPagar; function VerificaDatos:boolean; function VerificaFechas(sFecha : string):boolean; procedure Rellena(Sender: TObject); procedure IniInventario; public end; var frmInicializa: TfrmInicializa; implementation uses dm; {$R *.xfm} procedure TfrmInicializa.btnAceptarClick(Sender: TObject); begin if(VerificaDatos) then if(Application.MessageBox('Advertencia: esta operación es irreversible, ¿Deseas continuar?','Inicializar',[smbOK]+[smbCancel],smsWarning) = smbOK) then begin if(chkAreAsVenta.Checked) then IniAreasVenta; if(chkArticulos.Checked) then IniArticulos; if(chkExistencias.Checked) then IniExistencias; if(chkCajas.Checked) then IniCajas; if(chkCategorias.Checked) then IniCategorias; if(chkClientes.Checked) then IniClientes; if(chkCompras.Checked) then IniCompras; if(chkComprobantes.Checked) then IniComprobantes; if(chkCortes.Checked) then IniCortes; if(chkDescuentos.Checked) then IniDescuentos; if(chkDepartamentos.Checked) then IniDepartamentos; if(chkEmpresa.Checked) then IniEmpresa; if(chkProveedores.Checked) then IniProveedores; if(chkRetiros.Checked) then IniRetiros; if(chkUsuarios.Checked) then IniUsuarios; if(chkTicket.Checked) then IniTicket; if(chkTiposPago.Checked) then IniTiposPago; if(chkVentas.Checked) then IniVentas; if(chkVentasPendientes.Checked) then IniVentaspendientes; if(chkXCobrar.Checked) then IniXCobrar; if(chkXPagar.Checked) then IniXPagar; if(chkInventario.Checked) then IniInventario; Application.MessageBox('Finalizó la operación','Inicializar'); end; end; procedure TfrmInicializa.IniArticulos; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM articulos'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniExistencias; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('UPDATE articulos SET existencia = 0'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniInventario; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM inventario'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniCajas; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM cajas'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniCategorias; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM categorias'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniClientes; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM clientes'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniCompras; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM compras'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniComprobantes; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM comprobantes'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniDepartamentos; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM departamentos'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniEmpresa; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM empresa'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniRetiros; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM retiros'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniTiposPago; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM tipopago'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniProveedores; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM proveedores'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniUsuarios; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM usuarios'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniAreasVenta; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM areasventa'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniDescuentos; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM descuentos'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniVentas; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM ventas WHERE fecha >= ''' + txtMesIni.Text + '/' + txtDiaIni.Text + '/' + txtAnioIni.Text + ''''); SQL.Add('AND fecha <= ''' + txtMesFin.Text + '/' + txtDiaFin.Text + '/' + txtAnioFin.Text + ''''); ExecSQL; Close; end; end; procedure TfrmInicializa.IniTicket; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM ticket'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniVentasPendientes; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM ventasareas'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniCortes; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM cortes'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniXCobrar; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM xcobrar'); ExecSQL; Close; end; end; procedure TfrmInicializa.IniXPagar; begin with dmDatos.qryModifica do begin Close; SQL.Clear; SQL.Add('DELETE FROM xpagar'); ExecSQL; Close; end; end; procedure TfrmInicializa.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('Inicializa', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Inicializa', 'Posx', IntToStr(Left)); Free; end; end; procedure TfrmInicializa.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Inicializa', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Inicializa', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; Free; end; end; procedure TfrmInicializa.FormCreate(Sender: TObject); begin RecuperaConfig; end; procedure TfrmInicializa.chkVentasClick(Sender: TObject); begin if(chkVentas.Checked) then begin lblDiagDia1.Visible := true; lblDiagMes1.Visible := true; lblDiagDia2.Visible := true; lblDiagMes2.Visible := true; lblAl.Visible := true; txtDiaIni.Visible := true; txtMesIni.Visible := true; txtAnioIni.Visible := true; txtDiaFin.Visible := true; txtMesFin.Visible := true; txtAnioFin.Visible := true; txtDiaIni.SetFocus; end else begin lblDiagDia1.Visible := false; lblDiagMes1.Visible := false; lblDiagDia2.Visible := false; lblDiagMes2.Visible := false; lblAl.Visible := false; txtDiaIni.Visible := false; txtMesIni.Visible := false; txtAnioIni.Visible := false; txtDiaFin.Visible := false; txtMesFin.Visible := false; txtAnioFin.Visible := false; end; end; procedure TfrmInicializa.FormShow(Sender: TObject); begin chkVentasClick(Sender); end; function TfrmInicializa.VerificaDatos:boolean; var dteFechaIni, dteFechaFin : TDateTime; begin Result := true; if(chkVentas.Checked) then begin if (not VerificaFechas(txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text)) then begin Application.MessageBox('Introduce un fecha inicial válida para las ventas','Error',[smbOK],smsCritical); txtDiaIni.SetFocus; Result := false; end else if (not VerificaFechas(txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text)) then begin Application.MessageBox('Introduce un fecha final válida para las ventas','Error',[smbOK],smsCritical); txtDiaFin.SetFocus; Result := false; end; if(Result) then begin dteFechaIni := StrToDate(txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text); dteFechaFin := StrToDate(txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text); if(dteFechaIni > dteFechaFin) then begin Application.MessageBox('La fecha final debe ser mayor o igual que la fecha inicial','Error',[smbOK],smsCritical); txtDiaIni.SetFocus; Result := false; end; end; end; end; function TfrmInicializa.VerificaFechas(sFecha : string):boolean; var dteFecha : TDateTime; begin Result:=true; if(not TryStrToDate(sFecha,dteFecha)) then Result:=false; end; procedure TfrmInicializa.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmInicializa.txtAnioIniExit(Sender: TObject); begin txtAnioIni.Text := Trim(txtAnioIni.Text); if(Length(txtAnioIni.Text) < 4) and (Length(txtAnioIni.Text) > 0) then txtAnioIni.Text := IntToStr(StrToInt(txtAnioIni.Text) + 2000); end; procedure TfrmInicializa.txtAnioFinExit(Sender: TObject); begin txtAnioFin.Text := Trim(txtAnioFin.Text); if(Length(txtAnioFin.Text) < 4) and (Length(txtAnioFin.Text) > 0) then txtAnioFin.Text := IntToStr(StrToInt(txtAnioFin.Text) + 2000); end; procedure TfrmInicializa.txtDiaIniExit(Sender: TObject); begin Rellena(Sender) end; procedure TfrmInicializa.Rellena(Sender: TObject); var i : integer; begin for i := Length((Sender as TEdit).Text) to (Sender as TEdit).MaxLength - 1 do (Sender as TEdit).Text := '0' + (Sender as TEdit).Text; end; end.
{ seldsfrm unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit seldsfrm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons, ComponentEditors, DB, ButtonPanel; type { TSelectDataSetForm } TSelectDataSetForm = class(TForm) ButtonPanel1: TButtonPanel; CheckBox1: TCheckBox; Label1: TLabel; DataSetList: TListBox; procedure CheckBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ListBox1DblClick(Sender: TObject); procedure ListBox1KeyPress(Sender: TObject; var Key: char); private FDesigner: TComponentEditorDesigner; FExclude: string; procedure FillDataSetList(ExcludeDataSet: TDataSet); procedure AddDataSet(const S: string); public { public declarations } end; { TMemDataSetEditor } TMemDataSetEditor = class(TComponentEditor) private DefaultEditor: TBaseComponentEditor; function UniqueName(Field: TField): string; procedure BorrowStructure; protected function CopyStructure(Source, Dest: TDataSet): Boolean; virtual; public constructor Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); override; destructor Destroy; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; function SelectDataSet(ADesigner: TComponentEditorDesigner; const ACaption: string; ExcludeDataSet: TDataSet): TDataSet; var SelectDataSetForm: TSelectDataSetForm; implementation uses rxmemds, rxdconst; {$R *.lfm} function SelectDataSet(ADesigner: TComponentEditorDesigner; const ACaption: string; ExcludeDataSet: TDataSet): TDataSet; begin Result := nil; with TSelectDataSetForm.Create(Application) do try if ACaption <> '' then Caption := ACaption; FDesigner := ADesigner; FillDataSetList(ExcludeDataSet); if ShowModal = mrOk then if DataSetList.ItemIndex >= 0 then begin with DataSetList do Result := FDesigner.Form.FindComponent(Items[ItemIndex]) as TDataSet; end; finally Free; end; end; { TSelectDataSetForm } procedure TSelectDataSetForm.CheckBox1Change(Sender: TObject); begin Label1.Enabled:=not CheckBox1.Checked; DataSetList.Enabled:=not CheckBox1.Checked; end; procedure TSelectDataSetForm.FormCreate(Sender: TObject); begin Caption:=sRxSelectDatasetStruct; CheckBox1.Caption:=sRxCopyOnlyMetadata; Label1.Caption:=sRxSourceDataset; end; procedure TSelectDataSetForm.ListBox1DblClick(Sender: TObject); begin if DataSetList.ItemIndex >= 0 then ModalResult := mrOk; end; procedure TSelectDataSetForm.ListBox1KeyPress(Sender: TObject; var Key: char); begin if (Key = #13) and (DataSetList.ItemIndex >= 0) then ModalResult := mrOk; end; procedure TSelectDataSetForm.FillDataSetList(ExcludeDataSet: TDataSet); var I: Integer; Component: TComponent; begin DataSetList.Items.BeginUpdate; try DataSetList.Clear; FExclude := ''; if ExcludeDataSet <> nil then FExclude := ExcludeDataSet.Name; for I := 0 to FDesigner.Form.ComponentCount - 1 do begin Component := FDesigner.Form.Components[I]; if (Component is TDataSet) and (Component <> ExcludeDataSet) then AddDataSet(Component.Name); end; with DataSetList do begin if Items.Count > 0 then ItemIndex := 0; Enabled := Items.Count > 0; ButtonPanel1.OKButton.Enabled:= (ItemIndex >= 0); end; finally DataSetList.Items.EndUpdate; end; end; procedure TSelectDataSetForm.AddDataSet(const S: string); begin if (S <> '') and (S <> FExclude) then DataSetList.Items.Add(S); end; { TMemDataSetEditor } function TMemDataSetEditor.UniqueName(Field: TField): string; const AlphaNumeric = ['A'..'Z', 'a'..'z', '_'] + ['0'..'9']; var Temp: string; Comp: TComponent; I: Integer; begin Result := ''; if (Field <> nil) then begin Temp := Field.FieldName; for I := Length(Temp) downto 1 do if not (Temp[I] in AlphaNumeric) then System.Delete(Temp, I, 1); if (Temp = '') or not IsValidIdent(Temp) then begin Temp := Field.ClassName; if (UpCase(Temp[1]) = 'T') and (Length(Temp) > 1) then System.Delete(Temp, 1, 1); end; end else Exit; Temp := Component.Name + Temp; I := 0; repeat Result := Temp; if I > 0 then Result := Result + IntToStr(I); Comp := Designer.Form.FindComponent(Result); Inc(I); until (Comp = nil) or (Comp = Field); end; procedure TMemDataSetEditor.BorrowStructure; var DataSet: TDataSet; I: Integer; Caption: string; begin Caption := Component.Name; if (Component.Owner <> nil) and (Component.Owner.Name <> '') then Caption := Format('%s.%s', [Component.Owner.Name, Caption]); DataSet := SelectDataSet(Designer, Caption, TDataSet(Component)); if DataSet <> nil then begin // StartWait; try if not CopyStructure(DataSet, Component as TDataSet) then Exit; with TDataSet(Component) do begin for I := 0 to FieldCount - 1 do if Fields[I].Name = '' then Fields[I].Name := UniqueName(Fields[I]); end; Modified; finally // StopWait; end; Designer.Modified; end; end; function TMemDataSetEditor.CopyStructure(Source, Dest: TDataSet): Boolean; begin Result := Dest is TRxMemoryData; if Result then TRxMemoryData(Dest).CopyStructure(Source); end; type PClass = ^TClass; constructor TMemDataSetEditor.Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); var CompClass: TClass; begin inherited Create(AComponent, ADesigner); CompClass := PClass(Acomponent)^; try PClass(AComponent)^ := TDataSet; DefaultEditor := GetComponentEditor(AComponent, ADesigner); finally PClass(AComponent)^ := CompClass; end; end; destructor TMemDataSetEditor.Destroy; begin DefaultEditor.Free; inherited Destroy; end; procedure TMemDataSetEditor.ExecuteVerb(Index: Integer); begin if Index < DefaultEditor.GetVerbCount then DefaultEditor.ExecuteVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:BorrowStructure; end; end; end; function TMemDataSetEditor.GetVerb(Index: Integer): string; begin if Index < DefaultEditor.GetVerbCount then Result := DefaultEditor.GetVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:Result:=sRxBorrowStructure; end; end; end; function TMemDataSetEditor.GetVerbCount: Integer; begin Result:=DefaultEditor.GetVerbCount + 1; end; end.
unit BuildFacilitiesTask; interface uses Classes, Tasks, Kernel, Tutorial, CacheAgent, FacIds, BackupInterfaces; const stgZero = 0; stgConnect = 1; stgWait = 2; const ciConnected = 0; ciDisconnected = 1; type TFacilityChoiceMethod = (fcmFirst, fcmCheaper, fcmRandom); type TMetaBuildFacilitiesTask = class(TMetaTask) public constructor Create(anId, aName, aDesc, aSuperTaskId : string; aPeriod : integer; aTaskClass : CTask); overload; constructor Create(srcTaskId, newId, newSuperTaskId : string); overload; destructor Destroy; override; private fBlockClass : string; fFacId : TFacId; fTypicalFacs : TStringList; fEqivIds : PFacIdArray; fEqivCount : integer; fChoiceMethod : TFacilityChoiceMethod; fFacCount : integer; public function IsEquivalent(Id : TFacId) : boolean; procedure EquivalentIds(Ids : array of TFacId); private procedure GetTypicalFacilities; function GetTypicalFac(cluster : string) : TMetaFacility; procedure SetChoiceMethod(aMethod : TFacilityChoiceMethod); public property BlockClass : string read fBlockClass write fBlockClass; property FacId : integer read fFacId write fFacId; property FacCount : integer read fFacCount write fFacCount; property ChoiceMethod : TFacilityChoiceMethod read fChoiceMethod write SetChoiceMethod; property TypicalFac[cluster : string] : TMetaFacility read GetTypicalFac; end; TCnntInfo = byte; TFacilityArray = array[0..10] of TFacility; PFacilityArray = ^TFacilityArray; TCnntInfoArray = array[0..10] of TCnntInfo; PCnntInfoArray = ^TCnntInfoArray; TBuildFacilitiesTask = class(TAtomicTask) public constructor Create(aMetaTask : TMetaTask; aSuperTask : TSuperTask; aContext : ITaskContext); override; destructor Destroy; override; protected fMetaFacility : TMetaFacility; fReqCount : byte; fCount : byte; fEnded : byte; fFacs : PFacilityArray; fCnntInfo : PCnntInfoArray; public function GetProgress : integer; override; procedure StoreToCache(Prefix : string; Cache : TObjectCache); override; procedure LoadFromBackup(Reader : IBackupReader); override; procedure StoreToBackup (Writer : IBackupWriter); override; function AllConnected : boolean; protected procedure FacilityRemoved(Fac : TFacility); virtual; public function Execute : TTaskResult; override; private procedure MsgNewBlock(var Msg : TMsgNewBlock); message msgKernel_NewBlock; procedure MsgDelFacility(var Msg : TMsgFacilityDeleted); message msgKernel_FacilityDeleted; procedure SetReqCount(count : byte); protected property ReqCount : byte read fReqCount write SetReqCount; protected function GetTargetBlock : string; virtual; procedure AddFacility(Fac : TFacility; Connected : boolean); function FacilityIndex(Fac : TFacility) : integer; function DelFacility(Fac : TFacility) : boolean; procedure FacilityBuilt(Fac : TFacility); virtual; protected property Facs : PFacilityArray read fFacs; end; procedure RegisterBackup; implementation uses SysUtils, TaskUtils, Collection, Population, ModelServerCache, ClassStorage, ClassStorageInt, StdFluids, MathUtils, Languages; // TMetaBuildFacilitiesTask constructor TMetaBuildFacilitiesTask.Create(anId, aName, aDesc, aSuperTaskId : string; aPeriod : integer; aTaskClass : CTask); begin inherited; fTypicalFacs := TStringList.Create; end; constructor TMetaBuildFacilitiesTask.Create(srcTaskId, newId, newSuperTaskId : string); begin inherited Create(srcTaskId, newId, newSuperTaskId); fBlockClass := TMetaBuildFacilitiesTask(Source).BlockClass; fFacId := TMetaBuildFacilitiesTask(Source).FacId; fFacCount := 1; fTypicalFacs := TStringList.Create; fTypicalFacs.Assign(TMetaBuildFacilitiesTask(Source).fTypicalFacs); fEqivCount := TMetaBuildFacilitiesTask(Source).fEqivCount; if fEqivCount > 0 then begin ReallocMem(fEqivIds, fEqivCount*sizeof(fEqivIds[0])); System.move(TMetaBuildFacilitiesTask(Source).fEqivIds, fEqivIds, fEqivCount*sizeof(fEqivIds[0])); end else fEqivIds := nil; fChoiceMethod := TMetaBuildFacilitiesTask(Source).fChoiceMethod; end; destructor TMetaBuildFacilitiesTask.Destroy; var i : integer; begin for i := 0 to pred(fTypicalFacs.Count) do fTypicalFacs.Objects[i].Free; fTypicalFacs.Free; if fEqivIds <> nil then FreeMem(fEqivIds); inherited; end; function TMetaBuildFacilitiesTask.IsEquivalent(Id : TFacId) : boolean; var i : integer; begin if Id = fFacId then result := true else begin i := 0; while (i < fEqivCount) and (fEqivIds[i] <> Id) do inc(i); result := i < fEqivCount; end; end; procedure TMetaBuildFacilitiesTask.EquivalentIds(Ids : array of TFacId); begin fEqivCount := FacIds.NewFacIds(fEqivIds, Ids); end; procedure TMetaBuildFacilitiesTask.GetTypicalFacilities; var CltCnt : integer; FacCnt : integer; i : integer; c : integer; Fac : TMetaFacility; ClsStg : TClassStorage; idx : integer; Facs : TCollection; begin fTypicalFacs.Clear; // Add the cluster to the list ClsStg := ClassStorage.TheClassStorage; CltCnt := ClsStg.ClassCount[tidClassFamily_Clusters]; for c := 0 to pred(CltCnt) do fTypicalFacs.AddObject(TCluster(ClsStg.ClassByIdx[tidClassFamily_Clusters, c]).Id, nil); // Add the meta facilities to the list FacCnt := ClsStg.ClassCount[tidClassFamily_Facilities]; i := 0; while i < FacCnt do begin Fac := TMetaFacility(ClsStg.ClassByIdx[tidClassFamily_Facilities, i]); if IsEquivalent(Fac.FacId) then begin idx := fTypicalFacs.IndexOf(Fac.ClusterName); if (idx <> -1) then if fTypicalFacs.Objects[idx] = nil then begin Facs := TCollection.Create(0, rkUse); fTypicalFacs.Objects[idx] := Facs; Facs.Insert(Fac); end else begin Facs := TCollection(fTypicalFacs.Objects[idx]); case fChoiceMethod of fcmCheaper : if TMetaFacility(Facs[0]).Price > Fac.Price then Facs[0] := Fac; fcmRandom : Facs.Insert(Fac); end; end; end; inc(i); end; end; procedure TMetaBuildFacilitiesTask.SetChoiceMethod(aMethod : TFacilityChoiceMethod); begin fChoiceMethod := aMethod; GetTypicalFacilities; end; function TMetaBuildFacilitiesTask.GetTypicalFac(cluster : string) : TMetaFacility; var idx : integer; Facs : TCollection; begin if fTypicalFacs <> nil then begin idx := fTypicalFacs.IndexOf(cluster); if idx <> -1 then begin Facs := TCollection(fTypicalFacs.Objects[idx]); if (Facs <> nil) and (Facs.Count > 0) then case fChoiceMethod of fcmFirst, fcmCheaper : result := TMetaFacility(Facs[0]); fcmRandom : result := TMetaFacility(Facs[random(Facs.Count)]); else result := nil; end else result := nil; end else result := nil; end else result := nil; end; // TBuildFacilitiesTask constructor TBuildFacilitiesTask.Create(aMetaTask : TMetaTask; aSuperTask : TSuperTask; aContext : ITaskContext); var Company : TCompany; begin inherited Create(aMetaTask, aSuperTask, aContext); ReqCount := TMetaBuildFacilitiesTask(MetaTask).FacCount; Company := TCompany(Context.getContext(tcIdx_Company)); fMetaFacility := TMetaBuildFacilitiesTask(MetaTask).TypicalFac[Company.Cluster.Id]; end; destructor TBuildFacilitiesTask.Destroy; begin if fFacs <> nil then FreeMem(fFacs); if fCnntInfo <> nil then FreeMem(fCnntInfo); inherited; end; function TBuildFacilitiesTask.GetProgress : integer; begin if fReqCount = 0 then result := round(100*fEnded/fReqCount) else result := 100; end; procedure TBuildFacilitiesTask.StoreToCache(Prefix : string; Cache : TObjectCache); procedure CacheNotConnectedFacs; var i : integer; iStr : string; cnt : integer; begin cnt := 0; if fFacs <> nil then for i := 0 to pred(fCount) do if fCnntInfo[i] = ciDisconnected then try try iStr := IntToStr(cnt); Cache.WriteString(Prefix + 'toCnnName' + iStr, fFacs[i].Name); Cache.WriteString(Prefix + 'toCnnX' + iStr, IntToStr(fFacs[i].xPos)); Cache.WriteString(Prefix + 'toCnnY' + iStr, IntToStr(fFacs[i].yPos)); finally inc(cnt); end; except end; Cache.WriteInteger(Prefix + 'toCnnCount', cnt); end; begin inherited; if fMetaFacility <> nil then begin Cache.WriteInteger(Prefix + 'FacId', fMetaFacility.FacId); Cache.WriteInteger(Prefix + 'FacVisualId', fMetaFacility.VisualClass + fMetaFacility.TypicalStage.Index); Cache.WriteString(Prefix + 'FacName', fMetaFacility.Name); StoreMultiStringToCache( Prefix + 'FacName', fMetaFacility.Name_MLS, Cache ); Cache.WriteString(Prefix + 'FacKindName', fMetaFacility.Kind.Name); Cache.WriteString(Prefix + 'FacKindId', fMetaFacility.Kind.Id); Cache.WriteString(Prefix + 'FacPlural', fMetaFacility.PluralName); Cache.WriteInteger(Prefix + 'FacZone', fMetaFacility.ZoneType); Cache.WriteInteger(Prefix + 'ReqCount', fReqCount); Cache.WriteInteger(Prefix + 'Count', fCount); end; if fFacs <> nil then CacheNotConnectedFacs; end; procedure TBuildFacilitiesTask.LoadFromBackup(Reader : IBackupReader); var i : integer; aux : string; begin inherited; aux := Reader.ReadString('FacId', ''); if aux <> '' then fMetaFacility := TMetaFacility(TheClassStorage.ClassById[tidClassFamily_Facilities, aux]) else fMetaFacility := nil; ReqCount := Reader.ReadInteger('ReqCount', 1); fCount := Reader.ReadInteger('Count', 0); fEnded := Reader.ReadInteger('Ended', 0); for i := 0 to pred(fReqCount) do begin aux := IntToStr(i); Reader.ReadObject('toConn' + aux, fFacs[i], nil); fCnntInfo[i] := byte(Reader.ReadByte('cnntInfo' + aux, ciConnected)); end; end; procedure TBuildFacilitiesTask.StoreToBackup (Writer : IBackupWriter); var i : integer; iStr : string; begin inherited; Writer.WriteString('FacId', fMetaFacility.Id); Writer.WriteInteger('ReqCount', fReqCount); Writer.WriteInteger('Count', fCount); Writer.WriteInteger('Ended', fEnded); for i := 0 to pred(fReqCount) do begin iStr := IntToStr(i); Writer.WriteObjectRef('toConn' + iStr, fFacs[i]); Writer.WriteByte('cnntInfo' + iStr, fCnntInfo[i]); end; end; function TBuildFacilitiesTask.AllConnected : boolean; var i : integer; begin i := 0; while (i < fReqCount) and ((fCnntInfo[i] = ciConnected) or TaskUtils.ConstructionConnected(fFacs[i].CurrBlock)) do begin fCnntInfo[i] := ciConnected; inc(i); end; result := i = fReqCount; end; procedure TBuildFacilitiesTask.FacilityRemoved(Fac : TFacility); begin end; function TBuildFacilitiesTask.Execute : TTaskResult; begin if fEnded < fReqCount then begin if (Stage = stgConnect) and (fCount = fReqCount) and AllConnected then begin if MetaTask.StageCount >= stgWait then begin Stage := stgWait; UpdateObjectCache(Context.getContext(tcIdx_Tycoon), -1, -1); end; end; result := trContinue; end else result := trFinished; end; procedure TBuildFacilitiesTask.MsgNewBlock(var Msg : TMsgNewBlock); var Company : TCompany; function SomeOneToConnect : boolean; var i : integer; begin i := 0; while (i < fReqCount) and (fCnntInfo[i] = ciConnected) do inc(i); result := i < fReqCount; end; begin Company := TCompany(Context.getContext(tcIdx_Company)); if (Msg.Block <> nil) and (Msg.Block.Facility.MetaFacility.FacId = fMetaFacility.FacId) and (Msg.Block.Facility.Company = Company) then if Msg.Block.ClassName = tidConstBlockClassName then begin if fCount < fReqCount // :P Stupid Bug! then begin AddFacility(Msg.Block.Facility, TaskUtils.ConstructionConnected(Msg.Block)); if fCount = fReqCount then begin if SomeOneToConnect then begin Stage := stgConnect; NotifyTycoon(''); end else if MetaTask.StageCount >= stgWait then begin Stage := stgWait; UpdateObjectCache(Context.getContext(tcIdx_Tycoon), -1, -1); end; end; end; end else if (fEnded < fReqCount) and (Msg.Block.ClassName = GetTargetBlock) then begin inc(fEnded); FacilityBuilt(Msg.Block.Facility); if fEnded < fReqCount then NotifyTycoon(''); end; end; procedure TBuildFacilitiesTask.MsgDelFacility(var Msg : TMsgFacilityDeleted); var Company : TCompany; begin Company := TCompany(Context.getContext(tcIdx_Company)); if (Msg.Facility <> nil) and (Msg.Facility.MetaFacility.FacId = fMetaFacility.FacId) and (Msg.Facility.Company = Company) then begin if DelFacility(Msg.Facility) then begin if (fEnded > 0) and (Msg.Facility.CurrBlock.ClassName = GetTargetBlock) then dec(fEnded); Stage := 0; NotifyTycoon(''); FacilityRemoved(Msg.Facility); end; end; end; procedure TBuildFacilitiesTask.SetReqCount(count : byte); begin if fFacs <> nil then FreeMem(fFacs); if fCnntInfo <> nil then FreeMem(fCnntInfo); fReqCount := count; if count > 0 then begin GetMem(fFacs, count*sizeof(fFacs[0])); FillChar(fFacs^, count*sizeof(fFacs[0]), 0); GetMem(fCnntInfo, count*sizeof(fCnntInfo[0])); FillChar(fCnntInfo^, count*sizeof(fCnntInfo[0]), ciConnected); end else begin fFacs := nil; fCnntInfo := nil; end; end; function TBuildFacilitiesTask.GetTargetBlock : string; begin result := TMetaBuildFacilitiesTask(MetaTask).BlockClass; end; procedure TBuildFacilitiesTask.AddFacility(Fac : TFacility; Connected : boolean); begin if Connected then fCnntInfo[fCount] := ciConnected else fCnntInfo[fCount] := ciDisconnected; fFacs[fCount] := Fac; inc(fCount); end; function TBuildFacilitiesTask.FacilityIndex(Fac : TFacility) : integer; begin result := pred(fCount); while (result >= 0) and (fFacs[result] <> Fac) do dec(result); end; function TBuildFacilitiesTask.DelFacility(Fac : TFacility) : boolean; var idx : integer; cnt : integer; begin idx := FacilityIndex(Fac); if idx >= 0 then begin cnt := fCount - Idx - 1; if cnt > 0 then begin move(fFacs[idx + 1], fFacs[idx], cnt*sizeof(fFacs[0])); move(fCnntInfo[idx + 1], fCnntInfo[idx], cnt*sizeof(fCnntInfo[0])); end; dec(fCount); result := true; end else result := false; end; procedure TBuildFacilitiesTask.FacilityBuilt(Fac : TFacility); begin end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TBuildFacilitiesTask ); end; end.
unit G2Mobile.Model.Clientes; interface uses FMX.ListView, uDmDados, uRESTDWPoolerDB, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, FMX.Objects, G2Mobile.Controller.Clientes, FMX.Graphics; type TModelClientes = class(TInterfacedObject, iModelClientes) private public constructor create; destructor destroy; override; class function new: iModelClientes; function BuscaClientesServidor(Super, cod_vend: Integer; ADataSet: TFDMemTable): iModelClientes; function PopulaClientesSqLite(ADataSet: TFDMemTable): iModelClientes; function LimpaTabelaClientes: iModelClientes; function PopulaListView(value: TListView; positivo, negativo: TImage; Pesq: String): iModelClientes; function PopulaCampos(value: Integer; AList: TStringList): iModelClientes; function BuscarCliente(value: Integer): String; function RetornaLimite(value: Integer): String; function ValidaCliente(value: Integer): Integer; end; implementation { TModelClientes } uses uFrmUtilFormate, System.UITypes, Form_Mensagem; class function TModelClientes.new: iModelClientes; begin result := self.create; end; constructor TModelClientes.create; begin end; destructor TModelClientes.destroy; begin inherited; end; function TModelClientes.LimpaTabelaClientes: iModelClientes; var qry: TFDQuery; begin result := self; try qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; qry.Active := false; qry.SQL.Clear; qry.ExecSQL('DELETE FROM CLIENTE') finally FreeAndNil(qry); end; end; function TModelClientes.BuscaClientesServidor(Super, cod_vend: Integer; ADataSet: TFDMemTable): iModelClientes; var rdwSQLTemp: TRESTDWClientSQL; begin result := self; try rdwSQLTemp := TRESTDWClientSQL.create(nil); rdwSQLTemp.DataBase := DmDados.RESTDWDataBase1; rdwSQLTemp.BinaryRequest := True; rdwSQLTemp.FormatOptions.MaxStringSize := 10000; rdwSQLTemp.Active := false; rdwSQLTemp.SQL.Clear; rdwSQLTemp.SQL.Add (' select t.cod_pessoa, t.nome_razao, t.nome_fant, t.comissao, t.endereco, t.bairro, c.municipio, t.telefone, ' + ' t.cpf_cnpj, t.email, ISNULL(t.cod_vend, 0) as cod_vend, ISNULL(t.cod_doc, 0) as cod_doc, t.situacao, t.dt_visitar, ' + ' case when isnull(t1.vlr_crd, 0) < (isnull(t2.sld_chq,0) + isnull(t3.sld_dev, 0)) then 0 else 1 end as credito, ' + ' case when min_dta is not null then 0 else 1 end as atraso, ' + ' isnull(t1.vlr_crd, 0) as crd_permitido, ' + ' isnull(t2.sld_chq,0) + isnull(t3.sld_dev, 0) as Vlr_Pagar, ' + ' isnull(t1.vlr_crd, 0) - (isnull(t2.sld_chq,0) + isnull(t3.sld_dev, 0)) as cdr_disponivel ' + ' from t_pessoa t ' + ' left outer join t_cidade c on (t.cod_cidade = c.cod_cidade) ' + ' left outer join (select tc.cod_cliente, tc.credito as vlr_crd from t_credito tc where ' + ' tc.cod = (select max(cod) from t_credito where cod_cliente = tc.cod_cliente)) t1 on (t.cod_pessoa = t1.cod_cliente) ' + ' left outer join (select cod_cliente, sum(valor) as sld_chq from v_cheques_receb where status = 0 group by cod_cliente) t2 on (t.cod_pessoa = t2.cod_cliente) ' + ' left outer join (select cod_cliente, sum(sld_dev) as sld_dev from v_contas_receb where status = ''A'' group by cod_cliente) t3 on (t.cod_pessoa = t3.cod_cliente) ' + ' left outer join ( select cod_cliente, min(data_venc) as min_dta from t_contas_receb where status = ''A'' and ' + ' (select dateadd(day, dias_carencia, data_venc) from t_config where dias_carencia is not null) <= getdate() ' + ' group by cod_cliente ) t4 on (t.cod_pessoa = t4.cod_cliente) '); if (Super = 1) or (cod_vend = 0) then begin rdwSQLTemp.SQL.Add('where t.situacao = 1 and cliente = 1'); end else begin rdwSQLTemp.SQL.Add('where t.cod_vend = :cod and t.situacao = 1 and cliente = 1'); rdwSQLTemp.ParamByName('cod').value := cod_vend; end; rdwSQLTemp.Active := True; rdwSQLTemp.RecordCount; ADataSet.CopyDataSet(rdwSQLTemp, [coStructure, coRestart, coAppend]); finally FreeAndNil(rdwSQLTemp); end; end; function TModelClientes.BuscarCliente(value: Integer): String; var qry: TFDQuery; begin try qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; qry.Active := false; qry.SQL.Clear; qry.SQL.Add('SELECT NOME_FANT FROM CLIENTE WHERE COD_PESSOA = :COD_PESSOA'); qry.ParamByName('COD_PESSOA').AsInteger := value; qry.Open; if qry.RecordCount = 0 then result := EmptyStr else result := qry.FieldByName('NOME_FANT').AsString; finally FreeAndNil(qry); end; end; function TModelClientes.PopulaClientesSqLite(ADataSet: TFDMemTable): iModelClientes; var i : Integer; qry: TFDQuery; begin result := self; qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; ADataSet.First; try qry.Active := false; for i := 0 to ADataSet.RecordCount - 1 do begin qry.SQL.Clear; qry.SQL.Add ('INSERT INTO CLIENTE (COD_PESSOA, NOME_RAZAO, NOME_FANT, ENDERECO, BAIRRO, MUNICIPIO, TELEFONE, CPF_CNPJ, EMAIL, COD_VEND, ' + ' CREDITO, ATRASO, COD_DOC, DT_VISITAR, CRD_PERMITIDO, VLR_PAGAR, CDR_DISPONIVEL, COMISSAO) ' + ' VALUES ' + ' (:COD_PESSOA, :NOME_RAZAO, :NOME_FANT, :ENDERECO, :BAIRRO, :MUNICIPIO, :TELEFONE, :CPF_CNPJ, :EMAIL, :COD_VEND, ' + ' :CREDITO, :ATRASO, :COD_DOC, :DT_VISITAR, :CRD_PERMITIDO, :vLR_pAGAR, :CDR_DISPONIVEL, :COMISSAO)'); qry.ParamByName('COD_PESSOA').AsInteger := ADataSet.FieldByName('COD_PESSOA').AsInteger; qry.ParamByName('NOME_RAZAO').AsString := ADataSet.FieldByName('NOME_RAZAO').AsString; qry.ParamByName('NOME_FANT').AsString := ADataSet.FieldByName('NOME_FANT').AsString; qry.ParamByName('ENDERECO').AsString := ADataSet.FieldByName('ENDERECO').AsString; qry.ParamByName('BAIRRO').AsString := ADataSet.FieldByName('BAIRRO').AsString; qry.ParamByName('MUNICIPIO').AsString := ADataSet.FieldByName('MUNICIPIO').AsString; qry.ParamByName('TELEFONE').AsString := ADataSet.FieldByName('TELEFONE').AsString; qry.ParamByName('CPF_CNPJ').AsString := ADataSet.FieldByName('CPF_CNPJ').AsString; qry.ParamByName('EMAIL').AsString := ADataSet.FieldByName('EMAIL').AsString; qry.ParamByName('COD_VEND').AsInteger := ADataSet.FieldByName('COD_VEND').AsInteger; qry.ParamByName('CREDITO').AsFloat := ADataSet.FieldByName('CREDITO').AsFloat; qry.ParamByName('ATRASO').AsInteger := ADataSet.FieldByName('ATRASO').AsInteger; qry.ParamByName('COD_DOC').AsInteger := ADataSet.FieldByName('COD_DOC').AsInteger; qry.ParamByName('DT_VISITAR').AsDateTime := ADataSet.FieldByName('DT_VISITAR').AsDateTime; qry.ParamByName('CRD_PERMITIDO').AsFloat := ADataSet.FieldByName('CRD_PERMITIDO').AsFloat; qry.ParamByName('VLR_PAGAR').AsFloat := ADataSet.FieldByName('VLR_PAGAR').AsFloat; qry.ParamByName('CDR_DISPONIVEL').AsFloat := ADataSet.FieldByName('CDR_DISPONIVEL').AsFloat; qry.ParamByName('COMISSAO').AsInteger := ADataSet.FieldByName('COMISSAO').AsInteger; qry.ExecSQL; ADataSet.Next; end; finally FreeAndNil(qry); end; end; function TModelClientes.PopulaListView(value: TListView; positivo, negativo: TImage; Pesq: String): iModelClientes; var x : Integer; qry : TFDQuery; item: TListViewItem; txt : TListItemText; img : TListItemImage; begin try result := self; qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; qry.Active := false; qry.SQL.Clear; qry.SQL.Add (' select substr(''0000''||cod_pessoa, -4, 4) as cod_pessoa, nome_fant, nome_razao,cpf_cnpj, bairro|| '' - '' || municipio as endereco, ' + ' case when credito = 1 and atraso = 1 then ''OK!'' when credito = 1 and atraso = 0 then ''TÍTULOS EM ATRASO!'' ' + ' when credito = 0 and atraso = 1 then ''LIMITE EXCEDIDO!'' else ''LIMITE EXCEDIDO E TÍTULOS EM ATRASO!''END as situacao from cliente ' + 'where cod_pessoa = ' + QuotedStr(Pesq) + ' or nome_fant like ''%' + Pesq + '%'' or nome_razao like ''%' + Pesq + '%'''); qry.Open; qry.First; value.Items.Clear; value.BeginUpdate; for x := 1 to qry.RecordCount do begin item := value.Items.Add; with item do begin txt := TListItemText(Objects.FindDrawable('cod_cliente')); txt.Text := formatfloat('0000', qry.FieldByName('cod_pessoa').AsFloat); txt.TagString := qry.FieldByName('cod_pessoa').AsString; if qry.FieldByName('situacao').AsString <> 'OK!' then txt.TextColor := $FFF60000 else txt.TextColor := $FF0C76C1; txt := TListItemText(Objects.FindDrawable('nome_fant')); txt.Text := ' - ' + qry.FieldByName('nome_fant').AsString; if qry.FieldByName('situacao').AsString <> 'OK!' then txt.TextColor := $FFF60000 else txt.TextColor := $FF0C76C1; txt := TListItemText(Objects.FindDrawable('nome_razao')); txt.Text := qry.FieldByName('nome_razao').AsString; if qry.FieldByName('situacao').AsString <> 'OK!' then txt.TextColor := $FFF60000 else txt.TextColor := $FF0C76C1; txt := TListItemText(Objects.FindDrawable('cpf_cnpj')); txt.Text := 'CPF/CNPJ: ' + FormataDoc(qry.FieldByName('cpf_cnpj').AsString); txt := TListItemText(Objects.FindDrawable('bairro')); txt.Text := 'ENDEREÇO: ' + qry.FieldByName('endereco').AsString; txt := TListItemText(Objects.FindDrawable('situacao')); txt.Text := 'SITUAÇÃO: ' + qry.FieldByName('situacao').AsString; img := TListItemImage(Objects.FindDrawable('Image7')); if qry.FieldByName('situacao').AsString <> 'OK!' then img.Bitmap := negativo.Bitmap else img.Bitmap := positivo.Bitmap; end; qry.Next end; finally value.EndUpdate; FreeAndNil(qry); end; end; function TModelClientes.RetornaLimite(value: Integer): String; var qry: TFDQuery; begin qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; qry.Active := false; qry.SQL.Add('SELECT CDR_DISPONIVEL FROM CLIENTE WHERE COD_PESSOA = :ID'); qry.ParamByName('ID').AsInteger := value; qry.Open; result := formatfloat('#,##0.00', qry.FieldByName('CDR_DISPONIVEL').AsFloat); end; function TModelClientes.ValidaCliente(value: Integer): Integer; var qry: TFDQuery; begin qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; qry.Active := false; qry.SQL.Add(' SELECT case when credito = 1 and atraso = 1 then 1 /*Situação OK!*/ ' + ' when credito = 1 and atraso = 0 then 2 /*Títulos em atraso!*/ ' + ' when credito = 0 and atraso = 1 then 3 /*Limite excedido!*/ ' + ' else 4 /*Limite excedido e títulos em atraso!*/ ' + ' END as situacao, (select bloq_clientes from parametros) as bloq_clientes FROM cliente where cod_pessoa = :cliente '); qry.ParamByName('cliente').AsInteger := value; qry.Open; if (qry.FieldByName('bloq_clientes').AsInteger = 0) and (qry.FieldByName('situacao').AsInteger <> 1) then result := 1 // pergunta else if (qry.FieldByName('bloq_clientes').AsInteger = 1) and (qry.FieldByName('situacao').AsInteger <> 1) then result := 2 // bloquea else result := 3; end; function TModelClientes.PopulaCampos(value: Integer; AList: TStringList): iModelClientes; var i : Integer; qry: TFDQuery; begin result := self; qry := TFDQuery.create(nil); qry.Connection := DmDados.ConexaoInterna; qry.FetchOptions.RowsetSize := 50000; qry.Active := false; qry.SQL.Add ('select cod_pessoa, nome_fant, Nome_razao, cpf_cnpj, telefone, dt_visitar, email, endereco, bairro, municipio, crd_permitido, ' + ' cdr_disponivel, vlr_pagar from cliente where cod_pessoa = :ID'); qry.ParamByName('ID').AsInteger := value; qry.Open; if qry.RecordCount = 0 then begin Exibir_Mensagem('ERRO', 'ALERTA', 'Erro', 'Registro não encontrado!', 'OK', '', $FFDF5447, $FFDF5447); Frm_Mensagem.Show; abort; end; for i := 0 to qry.FieldCount - 1 do begin AList.Add(qry.Fields[i].AsString); qry.Next; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox, FMX.Memo, FMX.Edit, FMX.Controls.Presentation, FMX.StdCtrls, Winapi.Winrt, System.WinrtHelpers, ShlObj, ComObj, ActiveX, Winapi.PropSys, Winapi.PropKey, WinAPI.UI.Notifications, WinAPI.Data, WinAPI.Foundation.Types, WinAPI.Storage, WinAPI.Foundation, WinAPI.CommonTypes, Winapi.Windows, FMX.Platform.Win; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; type TAcceptedEventHandler = class(TInspectableObject, TypedEventHandler_2__IToastNotification__IInspectable_Delegate_Base{, Windows_UI_Notifications_IToastActivated}, TypedEventHandler_2__IToastNotification__IInspectable) procedure Invoke(sender: IToastNotification; args: IInspectable); safecall; end; implementation {$R *.fmx} function GetDesktopFolder: string; var PIDList: PItemIDList; Buffer: array [0..MAX_PATH-1] of Char; begin Result := ''; SHGetSpecialFolderLocation(FmxHandleToHWND(Form1.Handle), CSIDL_DESKTOP, PIDList); if Assigned(PIDList) then if SHGetPathFromIDList(PIDList, Buffer) then Result := Buffer; end; function GetStartMenuFolder: string; var Buffer: array [0..MAX_PATH-1] of Char; begin Result := ''; GetEnvironmentVariable(PChar('APPDATA'), Buffer, MAX_PATH - 1); Result := Buffer + '\Microsoft\Windows\Start Menu\Programs\Desktop Delphi Toasts App.lnk'; end; function CreateDesktopShellLink(const TargetName: string): Boolean; var IObject: IUnknown; ISLink: IShellLink; IPFile: IPersistFile; LinkName: string; LStore: IPropertyStore; LValue: TPropVariant; begin Result := False; IObject := CreateComObject(CLSID_ShellLink); ISLink := IObject as IShellLink; IPFile := IObject as IPersistFile; LStore := IObject as IPropertyStore; with ISLink do begin SetPath(PChar(ParamStr(0))); end; ISLink.SetArguments(PChar('')); if Succeeded(InitPropVariantFromStringAsVector( PWideChar('Delphi.DesktopNotification.Sample'), LValue)) then begin if Succeeded(LStore.SetValue(PKEY_AppUserModel_ID, LValue)) then LStore.Commit; end; LinkName := GetStartMenuFolder; if not FileExists(LinkName) then if IPFile.Save(PWideChar(LinkName), TRUE) = S_OK then Result := True; end; procedure TForm1.Button1Click(Sender: TObject); var LString: HString; LString2: HString; LINotificationManagerStatics: IToastNotificationManagerStatics; LXMLTemplate: Xml_Dom_IXmlDocument; LCreated: IInspectable; LToast: IToastNotification; LToastFactory: IToastNotificationFactory; LToastNotifier: IToastNotifier; LAccepted: TAcceptedEventHandler; begin if Succeeded(WindowsCreateString(PWideChar(SToastNotificationManager), Length(SToastNotificationManager), LString)) then begin if Succeeded(RoGetActivationFactory(LString, TGUID.Create('{50AC103F-D235-4598-BBEF-98FE4D1A3AD4}'), LCreated)) then begin LINotificationManagerStatics := LCreated as IToastNotificationManagerStatics; if Succeeded(WindowsCreateString(PWideChar(Edit1.Text), Length(Edit1.Text), LString2)) then begin LToastNotifier := LINotificationManagerStatics.CreateToastNotifier(LString2); LXMLTemplate := LINotificationManagerStatics.GetTemplateContent(ToastTemplateType.ToastText02); if Succeeded(WindowsCreateString(PWideChar(SToastNotification), Length(SToastNotification), LString)) then begin if Succeeded(RoGetActivationFactory(LString, TGUID.Create('{04124B20-82C6-4229-B109-FD9ED4662B53}'), LCreated)) then LToastFactory := LCreated as IToastNotificationFactory; LToast := LToastFactory.CreateToastNotification(LXMLTemplate); LAccepted := TAcceptedEventHandler.Create; LToast.add_Activated(LAccepted); LToastNotifier.Show(LToast); end; end; end; end; end; procedure TForm1.FormCreate(Sender: TObject); begin RoInitialize(RO_INIT_MULTITHREADED); CreateDesktopShellLink(ParamStr(0)); end; { TAcceptedEventHandler } procedure TAcceptedEventHandler.Invoke(sender: IToastNotification; args: IInspectable); begin Form1.Memo1.Lines.Add ('You clicked on the notification!'); end; end.
unit TaskUtils; interface uses Classes, Collection, Kernel, FacIds, Population, Tasks, BuildFacilitiesTask; const tidConstBlockClassName = 'TBlockUnderConstruction'; function FindFacility(FacId : TFacId; Company : TCompany; var Facility : TFacility) : boolean; function FindFacilityInTycoon(FacId : TFacId; Tycoon : TTycoon; var Company : TCompany; var Facility : TFacility) : boolean; function GetTypicalFacilities(MetaTask : TMetaBuildFacilitiesTask) : TStringList; function ConstructionConnected(Block : TBlock) : boolean; function TownHasFacilities(Town : TTown; Facs : array of TFacId) : boolean; function FindFacilityNotBelongingTo(xPos, yPos : integer; Town : TTown; Tycoon : TTycoon; Facs : array of TFacId) : TFacility; function FindSupplierFor(Input : TInput; var Suggestion : array of TPoint) : integer; implementation uses SysUtils, ClassStorage, ClassStorageInt, StdFluids, MathUtils, EvaluatedBlock; // Utilitary Functions function FindFacility(FacId : TFacId; Company : TCompany; var Facility : TFacility) : boolean; var i : integer; cnt : integer; begin Facility := nil; cnt := Company.Facilities.Count; Company.Facilities.Lock; try i := 0; while (i < cnt) and (TFacility(Company.Facilities[i]).MetaFacility.FacID <> FacId) do inc(i); if i < cnt then Facility := TFacility(Company.Facilities[i]) else Facility := nil; result := Facility <> nil; finally Company.Facilities.Unlock; end; end; function FindFacilityInTycoon(FacId : TFacId; Tycoon : TTycoon; var Company : TCompany; var Facility : TFacility) : boolean; var i : integer; cnt : integer; begin Company := nil; Facility := nil; cnt := Tycoon.AllCompaniesCount; i := 0; while (i < cnt) and (Facility = nil) do begin Company := Tycoon.AllCompanies[i]; FindFacility(FacId, Company, Facility); inc(i); end; result := Facility <> nil; end; function GetTypicalFacilities(MetaTask : TMetaBuildFacilitiesTask) : TStringList; var CltCnt : integer; FacCnt : integer; i : integer; c : integer; Fac : TMetaFacility; ClsStg : TClassStorage; idx : integer; begin result := TStringList.Create; // Add the cluster to the list ClsStg := ClassStorage.TheClassStorage; CltCnt := ClsStg.ClassCount[tidClassFamily_Clusters]; for c := 0 to pred(CltCnt) do result.AddObject(TCluster(ClsStg.ClassByIdx[tidClassFamily_Clusters, c]).Id, nil); // Add the meta facilities to the list FacCnt := ClsStg.ClassCount[tidClassFamily_Facilities]; i := 0; while i < FacCnt do begin Fac := TMetaFacility(ClsStg.ClassByIdx[tidClassFamily_Facilities, i]); if MetaTask.IsEquivalent(Fac.FacId) then begin idx := result.IndexOf(uppercase(Fac.ClusterName)); if (idx <> -1) then if result.Objects[idx] = nil then result.Objects[idx] := Fac else if TMetaFacility(result.Objects[idx]).Price > Fac.Price then result.Objects[idx] := Fac; end; inc(i); end; end; function InputConnected(Block : TBlock; InputName : string) : boolean; var Input : TInput; CCnt : integer; i : integer; begin Input := Block.InputsByName[InputName]; if Input = nil then result := true else begin CCnt := Input.ConnectionCount; i := 0; while (i < CCnt) and ((Input.ExtraConnectionInfo[i] = nil) or not Input.ExtraConnectionInfo[i].Connected) do inc(i); result := i < CCnt; end; end; function ConstructionConnected(Block : TBlock) : boolean; begin result := InputConnected(Block, tidFluid_ConstructionForce) and InputConnected(Block, tidFluid_Machinery) and InputConnected(Block, tidFluid_BusinessMachines); end; function TownHasFacilities(Town : TTown; Facs : array of TFacId) : boolean; var Facilities : TLockableCollection; i : integer; count : integer; size : integer; found : integer; lIdx : integer; hIdx : integer; function CheckFacility(Facility : TFacility) : boolean; var k : integer; begin if (Town <> Facility.Town) or (Facility.MetaFacility.FacId = 0) then result := false else begin k := lIdx; while (k <= hIdx) and (Facility.MetaFacility.FacId <> Facs[k]) do inc(k); if k <= hIdx then begin Facs[k] := 0; inc(found); end; result := found = size; end; end; begin Facilities := TInhabitedTown(Town).World.Facilities; lIdx := low(Facs); hIdx := high(Facs); size := hIdx - lIdx + 1; found := 0; Facilities.Lock; try i := 0; count := Facilities.Count; while (i < count) and not CheckFacility(TFacility(Facilities[i])) do inc(i); result := i < count; finally Facilities.UnLock; end; end; function FindFacilityNotBelongingTo(xPos, yPos : integer; Town : TTown; Tycoon : TTycoon; Facs : array of TFacId) : TFacility; var Facilities : TLockableCollection; i : integer; count : integer; dist : integer; function MatchFacility(Fac : TFacility) : boolean; var k : integer; d : integer; begin if (Fac.Company <> nil) and (Fac.Company.Owner <> Tycoon) then begin k := low(Facs); while (k <= high(Facs)) and (Fac.MetaFacility.FacId <> Facs[k])do inc(k); if k <= high(Facs) then begin d := MathUtils.Dist(xPos, yPos, Fac.xPos, Fac.yPos); if (dist = 0) or (dist < d) then begin result := true; dist := d; end else result := false end else result := false; end else result := false; end; begin dist := 0; Facilities := TInhabitedTown(Town).World.Facilities; Facilities.Lock; try i := 0; count := Facilities.Count; while (i < count) and not MatchFacility(TFacility(Facilities[i])) do inc(i); if i < count then result := TFacility(Facilities[i]) else result := nil; finally Facilities.UnLock; end; end; function FacilityProduces(Fac : TFacility; Input : TInput) : boolean; var Block : TBlock; cnt : integer; i : integer; Msg : TBlockOverloadedMsg; begin Block := Fac.CurrBlock; cnt := Block.OutputCount; i := 0; while (i < cnt) and (Block.Outputs[i].MetaOutput.MetaFluid <> Input.MetaInput.MetaFluid) do inc(i); if i < cnt then begin Msg.Gate := Input.MetaInput; Block.Dispatch(Msg); result := Msg.Result; end else result := false; end; function FindSupplierFor(Input : TInput; var Suggestion : array of TPoint) : integer; var Town : TTown; Facilities : TLockableCollection; Fac : TFacility; i : integer; count : integer; dist : integer; xpos : integer; ypos : integer; sgcnt : integer; procedure InsertFacility(Fac : TFacility); begin if (Suggestion[0].x <> 0) or (Suggestion[0].y <> 0) then begin if MathUtils.Dist(Suggestion[0].x, Suggestion[0].y, xPos, ypos) > dist then begin Move(Suggestion[0], Suggestion[1], (sgcnt - 1)*sizeof(Suggestion[0])); Suggestion[0].x := Fac.xPos; Suggestion[0].y := Fac.yPos; end; end else begin Suggestion[0].x := Fac.xPos; Suggestion[0].y := Fac.yPos; end end; begin Town := Input.Block.Facility.Town; sgcnt := high(Suggestion) - low(Suggestion) + 1; result := 0; xpos := Input.Block.xPos; ypos := Input.Block.yPos; dist := 0; Facilities := TInhabitedTown(Town).World.Facilities; Facilities.Lock; try i := 0; count := Facilities.Count; while i < count do begin Fac := TFacility(Facilities[i]); if (Fac.Town = Town) and FacilityProduces(Fac, Input) then begin dist := MathUtils.Dist(xpos, ypos, Fac.xPos, Fac.yPos); InsertFacility(Fac); result := min(sgcnt, result + 1); end; inc(i); end; finally Facilities.UnLock; end; end; end.
PROGRAM Encryption(INPUT, OUTPUT); {Переводит символы из INPUT в код согласно Chiper и печатает новые символы в OUTPUT} CONST Len = 26; FileName = 'Chiper.txt'; TYPE LengthOf = 0 .. Len; Str = ARRAY [1 .. Len] OF CHAR; Chiper = ARRAY [1 .. Len] OF CHAR; VAR Msg: Str; Code: Chiper; Length : LengthOf; ChiperFile: TEXT; PROCEDURE Initialize(VAR Code: Chiper; ChiperFile: TEXT); {Присвоить Code шифр замены} VAR Symbol: CHAR; Index: INTEGER; BEGIN {Initialize} Index := 1; WHILE NOT EOF(ChiperFile) DO BEGIN READ(ChiperFile, Symbol); READLN(ChiperFile, Code[Index]); Index := Index + 1 END END; {Initialize} PROCEDURE Encode(VAR S: Str); {Выводит символы из Code, соответствующие символам из S} VAR Index: 1 .. Len; BEGIN {Encode} FOR Index := 1 TO Len DO IF S[Index] IN ['A' .. 'Z'] THEN WRITE(Code[Index]) ELSE WRITE(S[Index]); WRITELN END; {Encode} BEGIN {Encryption} {Инициализировать Code} ASSIGN(ChiperFile, FileName); Initialize(Code, ChiperFile); WHILE NOT EOF DO BEGIN {читать строку в Msg и распечатать ее} Length := 0; WHILE NOT EOLN AND (Length < Len) DO BEGIN Length := Length + 1; READ(Msg[Length]); WRITE(Msg[Length]) END; READLN; WRITELN; {распечатать кодированное сообщение} Encode(Msg) END END. {Encryption}
program TicketTranslation; uses Classes, RegExpr, SysUtils; type RuleRange = array[0..3] of integer; TicketRule = record r_name: string; r_rule: string; r_ranges: RuleRange; end; Ticket = record t_values: array of integer; end; ValidField = record f_name: string; f_index: integer; end; var NewTicketRule: TicketRule; TicketRules: array of TicketRule; NewTicket: Ticket; YourTicket: Ticket; NearbyTickets: array of Ticket; InvalidTicketIDs: array of integer; ValidTickets: array of Ticket; NewValidField: ValidField; ValidFields: array of ValidField; FieldPossibilities: array[0..19] of array of ValidField; MatchedFields: array[0..19] of string; (* Check if element exists in array *) operator in(i: integer; a: array of integer) Result: Boolean; var b: Integer; begin Result := false; for b in a do begin Result := i = b; if Result then Break; end; end; (* Read file *) procedure ReadFile(filename: string); var re_rules: TRegExpr; re_ticket: TRegExpr; re_yourticket: TRegExpr; re_nearbyticket: TRegExpr; fh: text; line: string; ir: integer; it: integer; isYourTicket: boolean; splitLine: TStringArray; i: integer; begin re_rules := TRegExpr.Create('^([a-z\s]+):\s([0-9\-\sor]+)$'); re_ticket := TRegExpr.Create('^([\d,]+)$'); re_yourticket := TRegExpr.Create('^your ticket:$'); re_nearbyticket := TRegExpr.Create('^nearby tickets:$'); ir := 0; // Index for rules it := 0; // Index for tickets isYourTicket := false; assign(fh, filename); reset(fh); while not eof(fh) do begin readln(fh, line); if line <> '' then begin if re_rules.Exec(line) then begin NewTicketRule.r_name := re_rules.Match[1]; NewTicketRule.r_rule := re_rules.Match[2]; SetLength(TicketRules, Length(TicketRules) + 1); TicketRules[ir] := NewTicketRule; inc(ir); end else if re_yourticket.Exec(line) then begin isYourTicket := true; end else if re_nearbyticket.Exec(line) then begin isYourTicket := false; end else if re_ticket.Exec(line) then begin splitLine := re_ticket.Match[1].Split(','); SetLength(NewTicket.t_values, Length(splitLine)); for i := 0 to Length(splitLine) - 1 do begin if splitLine[i] <> '' then begin NewTicket.t_values[i] := StrToInt(splitLine[i]); end; end; if isYourTicket then begin YourTicket := NewTicket; end else begin SetLength(NearbyTickets, Length(NearbyTickets) + 1); NearbyTickets[it] := NewTicket; inc(it); end; end; end; end; re_rules.Free(); re_ticket.Free(); close(fh); end; (* Parse ticket rules *) procedure ParseRules(); var i: integer; j: integer; re_ranges: TRegExpr; begin re_ranges := TRegExpr.Create('([0-9]+)'); for i := 0 to Length(TicketRules) - 1 do begin if re_ranges.Exec(TicketRules[i].r_rule) then begin j := 0; TicketRules[i].r_ranges[j] := StrToInt(re_ranges.Match[1]); while re_ranges.ExecNext do begin j := j + 1; TicketRules[i].r_ranges[j] := StrToInt(re_ranges.Match[1]); end; end; end; re_ranges.Free(); end; (* Check if ticket matches rules *) procedure CheckTickets(); var i: integer; // NearbyTickets index j: integer; // NearbyTickets t_values index k: integer; // RuleRanges index validFieldFound: boolean; begin for i := 0 to Length(NearbyTickets) - 1 do begin for j := 0 to Length(NearbyTickets[i].t_values) - 1 do begin validFieldFound := false; for k := 0 to Length(TicketRules) - 1 do begin if ((NearbyTickets[i].t_values[j] >= TicketRules[k].r_ranges[0]) and (NearbyTickets[i].t_values[j] <= TicketRules[k].r_ranges[1])) or ((NearbyTickets[i].t_values[j] >= TicketRules[k].r_ranges[2]) and (NearbyTickets[i].t_values[j] <= TicketRules[k].r_ranges[3])) then begin validFieldFound := true; end; end; if validFieldFound <> true then begin SetLength(InvalidTicketIDs, Length(InvalidTicketIDs) + 1); InvalidTicketIDs[Length(InvalidTicketIDs) - 1] := i; end; end; end; end; (* Filter invalid tickets *) procedure FilterInvalidTickets(); var i, j: integer; begin j := 0; // ValidTickets index for i := 0 to Length(NearbyTickets) - 1 do begin if not (i in InvalidTicketIDs) then begin SetLength(ValidTickets, Length(ValidTickets) + 1); ValidTickets[j] := NearbyTickets[i]; inc(j); end; end; end; (* Match rules to field *) procedure MatchRules(); var i: integer; // Fields index j: integer; // Rules index k: integer; // Ticket index l: integer; // ValidFields index validCount: integer; begin l := 0; for i := 0 to Length(ValidTickets[0].t_values) - 1 do // Assuming each ticket has an identical field-count begin for j := 0 to Length(TicketRules) - 1 do begin validCount := 0; for k := 0 to Length(ValidTickets) - 1 do begin if ((ValidTickets[k].t_values[i] >= TicketRules[j].r_ranges[0]) and (ValidTickets[k].t_values[i] <= TicketRules[j].r_ranges[1])) or ((ValidTickets[k].t_values[i] >= TicketRules[j].r_ranges[2]) and (ValidTickets[k].t_values[i] <= TicketRules[j].r_ranges[3])) then begin validCount := validCount + 1; end; end; if validCount = Length(ValidTickets) then begin NewValidField.f_index := i; NewValidField.f_name := TicketRules[j].r_name; SetLength(ValidFields, Length(ValidFields) + 1); ValidFields[l] := NewValidField; inc(l); end; end; end; end; procedure SortFieldsByPossibilities(); var i, j: integer; temp: array of ValidField; begin for i := Length(FieldPossibilities) - 1 DownTo 0 do begin for j := 1 to i do begin if (Length(FieldPossibilities[j - 1]) > Length(FieldPossibilities[j])) then begin SetLength(temp, Length(FieldPossibilities[j - 1])); temp := FieldPossibilities[j - 1]; FieldPossibilities[j - 1] := FieldPossibilities[j]; FieldPossibilities[j] := temp; end; end; end; end; procedure SeaveFields(); var i, j: integer; k: integer; // FieldPossibilities index foundField: boolean; begin for i := 0 to Length(ValidTickets[0].t_values) - 1 do begin k := 0; for j := 0 to Length(ValidFields) - 1 do begin if ValidFields[j].f_index = i then begin SetLength(FieldPossibilities[i], Length(FieldPossibilities[i]) + 1); FieldPossibilities[ValidFields[j].f_index][k] := ValidFields[j]; inc(k); end; end; end; SortFieldsByPossibilities(); for i := 0 to Length(FieldPossibilities) - 1 do begin for j := 0 to Length(FieldPossibilities[i]) - 1 do begin foundField := false; for k := 0 to Length(MatchedFields) - 1 do begin if FieldPossibilities[i][j].f_name = MatchedFields[k] then begin foundField := true; end; end; if foundField <> true then begin MatchedFields[FieldPossibilities[i][j].f_index] := FieldPossibilities[i][j].f_name; end; end; end; end; (* Main *) var i: integer; product: int64; begin ReadFile('./day16/day16.txt'); ParseRules(); CheckTickets(); FilterInvalidTickets(); writeln('# Valid tickets: ', Length(ValidTickets)); MatchRules(); SeaveFields(); product := 1; for i := 0 to Length(MatchedFields) - 1 do begin if pos('departure', MatchedFields[i]) = 1 then begin writeln('Column ', i, ' is ', MatchedFields[i], '. On your ticket this value is ', YourTicket.t_values[i]); product := product * YourTicket.t_values[i]; end; end; writeln('Total product of all values where rule starts with ''Departure'': ', product); end.
{*******************************************************} { } { Delphi Visual Component Library } { Registration of Web server application and } { internet components } { } { Copyright(c) 2016 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit InetWiz; interface uses Classes, Forms; type TProjectType = (ptISAPI, ptCGI, ptWinCGI, ptApacheTwo, ptIndyForm, ptIndyConsole); TProjectTypes = set of TProjectType; TWizardOption = (woUknown, woNoCrossplatformCB, woOutputToProjectDirectory, woDBXTerminateThreads, woVCLFramework); TWizardOptions = set of TWizardOption; TCreateWebProjectOption = (wpCrossplatform, wpNamedProject, wpOutputToProjectDirectory, wbDBXTerminateThreads, wpVCLFramework); TCreateWebProjectOptions = set of TCreateWebProjectOption; TFrameWorkType = (frameworkNone, frameworkVCL, frameworkFMX); procedure RegisterWebProjectWizards; procedure Register; implementation uses ColnEdit, LibHelp, Web.WebConst, NetConst, Windows, Messages, SysUtils, Controls, Dialogs, DesignIntf, DesignEditors, Web.HTTPApp, PlatformAPI, DMForm, Consts, IStreams, ToolsAPI, DCCStrs, CommonOptionStrs, ExpertsRepository, InetExpertsUI, InetExpertsCreators, BCCStrs; {$R *.res} type { TCustomWebModule } TCustomWebModule = class(TDataModuleCustomModule)//TDataModuleDesignerCustomModule) procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; procedure ValidateComponent(Component: TComponent); override; end; { TCustomWebModule } procEdure TCustomWebModule.ExecuteVerb(Index: Integer); begin if Index = 0 then begin ShowCollectionEditor({TForm(Root.Owner).}Designer, Root, TCustomWebDispatcher(Root).Actions, 'Actions'); end; end; function TCustomWebModule.GetVerb(Index: Integer): string; begin if Index = 0 then Result := sEditURLMap else Result := ''; end; function TCustomWebModule.GetVerbCount: Integer; begin Result := 1; end; procedure TCustomWebModule.ValidateComponent(Component: TComponent); begin if (Component = nil) or (Component is TControl) then raise Exception.CreateRes(@SControlInWebModule); end; { Register procedure } procedure RegisterWebProjectWizard(const APersonality: string); begin RegisterPackageWizard(TExpertsRepositoryProjectWizardWithProc.Create(APersonality, sNewWebModuleExpertComment, sNewWebModuleExpertName, 'Borland.NewWebModule', // do not localize sNewPage, 'Embarcadero', // do not localize procedure var LUIModule: TInetExpertsUIModule; begin LUIModule := TInetExpertsUIModule.Create(nil); try LUIModule.ShowPlatformsPage := False; LUIModule.WebServerProjectWizard.Execute( procedure var LModule: TInetExpertsCreatorsModule; begin LModule := TInetExpertsCreatorsModule.Create(nil); try LModule.WebProject.PlatformTypes := LUIModule.PlatformTypes; LModule.WebProject.FrameWorkType := LUIModule.GetFrameWorkType; // Set personality so the correct template files are used LModule.Personality := APersonality; // Indicate which type of project to create LModule.ProjectType := LUIModule.ProjectType; // Indicate port LModule.HTTPPort := LUIModule.HTTPPort; LModule.HTTPS := LUIModule.HTTPS; LModule.CertFileInfo := LUIModule.CertFileInfo; LModule.ApacheInfo := LUIModule.ApacheInfo; LModule.WebProject.CreateProject(APersonality); finally LModule.Free; end; end); finally LUIModule.Free; end; end, function: Cardinal begin Result := LoadIcon(HInstance, 'WEBAPP') end, TArray<string>.Create(cWin32Platform, cWin64Platform), TArray<string>.Create() ) as IOTAWizard); end; procedure RegisterWebProjectWizards; begin RegisterWebProjectWizard(sDelphiPersonality); RegisterWebProjectWizard(sCBuilderPersonality); end; procedure Register; begin // Make module designable RegisterCustomModule(TWebModule, TCustomWebModule); // Note tha webbroker wizards are registered in a different package end; end.
unit LOGIC_DemoAPI; interface uses System.Classes, Vcl.StdCtrls, Commune_APIUtilities, Winapi.Windows; type tDEMO = class private class function UTIL_ByteCountScaled(aByteCount: single; aScale: fsScaleFactor = fss_Byte): single; static; class function UTIL_DiskFree(aDriveLetter: char): Int64; static; class function UTIL_DiskSize(aDriveLetter: char): Int64; static; class function UTIL_DriveLetter(aLetter: string): char; static; class function UTIL_ExtractDriveLetter(aDriveCombo: tComboBox; aIndex: integer): char; static; class function UTIL_SYSUTIL_InternalGetDiskSpace(Drive: char; var TotalSpace, FreeSpaceAvailable: Int64) : Bool; static; public class procedure INFO_AllDrives(aDriveCombo: tComboBox; aMemo: tMemo); static; class function INFO_CapacityOf(aDriveLetter: char): string; static; class function INFO_OneDrive(aDriveLetter: char): string; static; class function INFO_UnusedSpaceOn(aDriveLetter: char): string; static; class procedure LOAD_Combo(aCombo: tComboBox; aStringlist: tStringList); static; class procedure LOAD_Memo(aMemo: tMemo; aStringlist: tStringList); static; end; implementation uses System.SysUtils, math; const GLOBAL_SCALAR = fss_Gigabyte; GLOBAL_SCALARTEXT = 'GB'; { tDEMO } class procedure tDEMO.INFO_AllDrives(aDriveCombo: tComboBox; aMemo: tMemo); { --------------------------------------------------------------------------------------------------------------------------- } var thisDriveString: string; myDrive: char; myDetails: string; begin aMemo.Clear; for thisDriveString in aDriveCombo.Items do begin myDrive := UTIL_DriveLetter(thisDriveString); myDetails := INFO_OneDrive(myDrive); aMemo.Lines.Add(thisDriveString + ' ' + myDetails); end; end; class function tDEMO.INFO_CapacityOf(aDriveLetter: char): string; { --------------------------------------------------------------------------------------------------------------------------- } var myCapacity: Int64; myscaled: single; mystring: string; begin myCapacity := UTIL_DiskSize(aDriveLetter); myscaled := UTIL_ByteCountScaled(myCapacity, GLOBAL_SCALAR); mystring := floattostr(myscaled); result := 'Capacity=' + mystring + GLOBAL_SCALARTEXT; end; class function tDEMO.INFO_OneDrive(aDriveLetter: char): string; { --------------------------------------------------------------------------------------------------------------------------- } var theCapacity: string; theUnused: string; begin theCapacity := INFO_CapacityOf(aDriveLetter); theUnused := INFO_UnusedSpaceOn(aDriveLetter); result := theCapacity + ' ' + theUnused; end; class function tDEMO.INFO_UnusedSpaceOn(aDriveLetter: char): string; { --------------------------------------------------------------------------------------------------------------------------- } var myDASDIndex: integer; myFreeSpace: Int64; myscaled: single; mystring: string; begin myFreeSpace := UTIL_DiskFree(aDriveLetter); myscaled := UTIL_ByteCountScaled(myFreeSpace, GLOBAL_SCALAR); mystring := floattostr(myscaled); result := 'Available= ' + mystring + GLOBAL_SCALARTEXT; end; class procedure tDEMO.LOAD_Combo(aCombo: tComboBox; aStringlist: tStringList); { --------------------------------------------------------------------------------------------------------------------------- } var myDrive: string; begin aCombo.Clear; for myDrive in aStringlist do begin aCombo.Items.Add(myDrive); end; aCombo.ItemIndex := -1; if aCombo.Items.Count > 0 then aCombo.ItemIndex := 0; end; class procedure tDEMO.LOAD_Memo(aMemo: tMemo; aStringlist: tStringList); { --------------------------------------------------------------------------------------------------------------------------- } var myDrive: string; begin aMemo.Clear; for myDrive in aStringlist do begin aMemo.Lines.Add(myDrive); end; end; class function tDEMO.UTIL_ByteCountScaled(aByteCount: single; aScale: fsScaleFactor = fss_Byte): single; { ---------------------------------------------------------------------------------------------------------------------------- } var scaler: extended; scaled: extended; begin scaler := IntPower(1024, ord(aScale)); scaled := aByteCount / scaler; result := ceil(scaled); end; class function tDEMO.UTIL_DiskFree(aDriveLetter: char): Int64; { --------------------------------------------------------------------------------------------------------------------------- } var mySize, myFree: Int64; theDrive: char; begin if not UTIL_SYSUTIL_InternalGetDiskSpace(aDriveLetter, mySize, myFree) then result := -1 else result := myFree; end; class function tDEMO.UTIL_DiskSize(aDriveLetter: char): Int64; { --------------------------------------------------------------------------------------------------------------------------- } var mySize, myFree: Int64; theDrive: char; begin; if not UTIL_SYSUTIL_InternalGetDiskSpace(aDriveLetter, mySize, myFree) then result := -1 else result := mySize; end; class function tDEMO.UTIL_DriveLetter(aLetter: string): char; { --------------------------------------------------------------------------------------------------------------------------- } begin result := aLetter[low(aLetter)]; end; class function tDEMO.UTIL_ExtractDriveLetter(aDriveCombo: tComboBox; aIndex: integer): char; { --------------------------------------------------------------------------------------------------------------------------- } var theLetter: string; begin theLetter := aDriveCombo.Items[aIndex]; result := UTIL_DriveLetter(theLetter); end; class function tDEMO.UTIL_SYSUTIL_InternalGetDiskSpace(Drive: char; var TotalSpace, FreeSpaceAvailable: Int64): Bool; { --------------------------------------------------------------------------------------------------------------------------- } var RootPath: array [0 .. 4] of char; RootPtr: PChar; begin RootPtr := nil; if Drive <> '' then begin RootPath[0] := Drive; RootPath[1] := ':'; RootPath[2] := '\'; RootPath[3] := #0; RootPtr := RootPath; end; result := GetDiskFreeSpaceEx(RootPtr, FreeSpaceAvailable, TotalSpace, nil); end; end.
unit kwPopEditorNextHyperlink; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorNextHyperlink.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_NextHyperlink // // *Формат:* anEditorControl pop:editor:NextHyperlink // *Описание:* Переходит на следущую гиперссылку. Если такой переход невозможен, то ничего не // происходит. // *Пример:* // {code} // focused:control:push pop:editor:NextHyperlink // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditor, tfwScriptingInterfaces, evCustomEditorWindow, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas} TkwPopEditorNextHyperlink = {final} class(_kwEditorWithToolsFromStackWord_) {* *Формат:* anEditorControl pop:editor:NextHyperlink *Описание:* Переходит на следущую гиперссылку. Если такой переход невозможен, то ничего не происходит. *Пример:* [code] focused:control:push pop:editor:NextHyperlink [code] } protected // realized methods procedure DoEditorWithTools(const aCtx: TtfwContext; anEditor: TevCustomEditor); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorNextHyperlink {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorNextHyperlink; {$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas} // start class TkwPopEditorNextHyperlink procedure TkwPopEditorNextHyperlink.DoEditorWithTools(const aCtx: TtfwContext; anEditor: TevCustomEditor); //#UC START# *4F4DD89102E4_4F4DD9B8016A_var* //#UC END# *4F4DD89102E4_4F4DD9B8016A_var* begin //#UC START# *4F4DD89102E4_4F4DD9B8016A_impl* anEditor.NextHyperlink; //#UC END# *4F4DD89102E4_4F4DD9B8016A_impl* end;//TkwPopEditorNextHyperlink.DoEditorWithTools class function TkwPopEditorNextHyperlink.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:NextHyperlink'; end;//TkwPopEditorNextHyperlink.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit MdListAct; interface uses ActnList, Classes, StdCtrls, ExtActns, Controls; type TMdCustomListAction = class (TListControlAction) protected function TargetList (Target: TObject): TCustomListBox; function GetControl(Target: TObject): TCustomListControl; public procedure UpdateTarget (Target: TObject); override; published property Caption; property Enabled; property HelpContext; property Hint; property ImageIndex; property ListControl; property ShortCut; property SecondaryShortCuts; property Visible; property OnHint; end; TMdListCutAction = class (TMdCustomListAction) public procedure ExecuteTarget(Target: TObject); override; end; TMdListCopyAction = class (TMdCustomListAction) public procedure ExecuteTarget(Target: TObject); override; end; TMdListPasteAction = class (TMdCustomListAction) public procedure UpdateTarget (Target: TObject); override; procedure ExecuteTarget (Target: TObject); override; end; procedure Register; implementation uses Windows, Clipbrd; function TMdCustomListAction.GetControl( Target: TObject): TCustomListControl; begin Result := Target as TCustomListControl; end; function TMdCustomListAction.TargetList (Target: TObject): TCustomListBox; begin Result := GetControl (Target) as TCustomListBox; end; procedure TMdCustomListAction.UpdateTarget(Target: TObject); begin Enabled := (TargetList (Target).Items.Count > 0) and (TargetList (Target).ItemIndex >= 0); end; procedure TMdListCopyAction.ExecuteTarget(Target: TObject); begin with TargetList (Target) do Clipboard.AsText := Items [ItemIndex]; end; procedure TMdListCutAction.ExecuteTarget(Target: TObject); begin with TargetList (Target) do begin Clipboard.AsText := Items [ItemIndex]; Items.Delete (ItemIndex); end; end; procedure TMdListPasteAction.ExecuteTarget(Target: TObject); begin TargetList (Target).Items.Add (Clipboard.AsText); end; procedure TMdListPasteAction.UpdateTarget(Target: TObject); begin Enabled := Clipboard.HasFormat (CF_TEXT); end; procedure Register; begin RegisterActions ('List', [TMdListCutAction, TMdListCopyAction, TMdListPasteAction], nil); end; end.
unit simple_statistics_lib; interface uses classes,series; type TAbstract1DStats=class(TPersistent) protected fmin,fmax,fsum,fsumSquares: Real; fcount: Integer; function getRMS: Real; virtual; abstract; function getStdDev: Real; virtual; abstract; function getSampleStdDev: Real; virtual; abstract; function GetAve: Real; virtual; abstract; public procedure AfterConstruction; override; procedure Clear; virtual; procedure Add(value: Real); virtual; abstract; procedure Append(values: TAbstract1DStats); virtual; abstract; published property sum: Real read fsum; property sum_squares: Real read fsumSquares; property count: Integer read fcount; property rms: Real read getRMS; property std_dev: Real read getStdDev; property sample_std_dev: Real read getSampleStdDev; property ave: Real read GetAve; property max: Real read fmax; property min: Real read fmin; end; T1DstatsOld=class(TAbstract1DStats) protected function getStdDev: Real; override; function getSampleStdDev: Real; override; function getAve: Real; override; function getRMS: Real; override; public procedure Add(value: Real); override; procedure Append(values: TAbstract1DStats); override; end; T1Dstats=class(TAbstract1DStats) //better then 1DstatsOld because it computes stdDev with //less error, situation of square root of negative val. is impossible //but append procedure still missing. protected fSumDiff: Real; function getAve: Real; override; function getRMS: Real; override; function getStdDev: Real; override; function getSampleStdDev: Real; override; public procedure Clear; override; procedure Add(value: Real); override; procedure Append(values: TAbstract1DStats); override; end; T1DFullStats=class(T1DStats) //not only computes min,max,ave,std_dev etc, //but also can draw distribution function //median is possible,too protected fvalues: TList; public constructor Create; virtual; Destructor Destroy; override; procedure Clear; override; procedure Add(value: Real); override; procedure Draw(series: TLineSeries); end; TDiscretePick=class protected function GetCount: Integer; virtual; abstract; procedure SetCount(value: Integer); virtual; abstract; function GetProb(index: Integer): Real; virtual; abstract; procedure SetProb(index: Integer;value: Real); virtual; abstract; public function Pick: Integer; virtual; abstract; property Count: Integer read GetCount write SetCount; property Prob[index: Integer]: Real read GetProb write SetProb; procedure Normalize; end; TSimplestPick=class(TDiscretePick) private fchanged: boolean; fCount: Integer; fSumOfProbs: array of Real; fProb: array of Real; procedure Prepare; protected function GetCount: Integer; override; procedure SetCount(value: Integer); override; function GetProb(index: Integer): Real; override; procedure SetProb(index: Integer;value: Real); override; public function Pick: Integer; override; end; TPickingProc=function:Integer of object; TSmallCountPick=class(TSimplestPick) private fNonZeroCount: Integer; fPickingProc: TPickingProc; fIndexes: array of Integer; procedure NewPrepare; function NoChoice: Integer; function OneOfTwo: Integer; function OneofMany: Integer; protected procedure SetCount(value: Integer); override; public function Pick: Integer; override; end; //простейшие классы для конкретного числа объектов, из которых выбирать TNoChoicePick=class(TDiscretePick) protected function GetCount: Integer; override; procedure SetCount(value: Integer); override; function GetProb(index: Integer): Real; override; procedure SetProb(index: Integer;value: Real); override; public function Pick: Integer; override; end; TOneOfTwoChoicePick=class(TDiscretePick) private fprob: array [0..1] of Real; protected function GetCount: Integer; override; procedure SetCount(value: Integer); override; function GetProb(index: Integer): Real; override; procedure SetProb(index: Integer;value: Real); override; public function Pick: Integer; override; end; TPermanentOneOfTwoChoicePick=class(TDiscretePick) private fprob: array [0..1] of Real; fthreshold: Real; protected function GetCount: Integer; override; procedure SetCount(value: Integer); override; function GetProb(index: Integer): Real; override; procedure SetProb(index: Integer; value: Real); override; public function Pick: Integer; override; end; function CreateAppropriatePick(count: Integer;PickToChangeRatio: Real=1000): TDiscretePick; function RealCompareFunc(P1,P2: Pointer): Integer; implementation uses SysUtils; (* TAbstract1DStats *) procedure TAbstract1Dstats.AfterConstruction; begin inherited AfterConstruction; Clear; end; procedure TAbstract1DStats.Clear; begin fsum:=0; fsumSquares:=0; fcount:=0; fmax:=-1.0/0.0; fmin:=1.0/0.0; end; (* T1DstatsOld *) procedure T1DstatsOld.Add(value: Real); begin fSum:=fSum+value; fSumSquares:=fSumSquares+value*value; if value>fmax then fmax:=value; if value<fmin then fmin:=value; inc(fcount); end; procedure T1DstatsOld.Append(values: TAbstract1DStats); begin fcount:=fcount+values.count; fsum:=fsum+values.sum; fSumSquares:=fSumSquares+values.Sum_Squares; if values.min<fmin then fmin:=values.min; if values.max>fmax then fmax:=values.max; end; function T1DstatsOld.GetAve: Real; begin if fcount=0 then Raise Exception.Create('T1Dstats.ave: empty list'); Result:=fsum/fcount; end; function T1DstatsOld.getStdDev: Real; begin result:=sqrt(fSumSquares/fcount-getAve*getAve); end; function T1DStatsOld.getSampleStdDev: Real; begin result:=getStdDev*sqrt(fCount/(fCount-1)); end; function T1DstatsOld.getRMS: Real; begin result:=sqrt(fsumSquares/fcount); end; (* T1DStats *) procedure T1DStats.Clear; begin inherited Clear; fSumDiff:=0; end; procedure T1DStats.Add(value: Real); begin //пока что get_ave возвращает среднее от занесенных чисел, т.е без value if fcount=0 then fSumDiff:=0 else fSumDiff:=fSumDiff+fcount/(fcount+1)*Sqr(value-getAve); inc(fcount); fsum:=fsum+value; fSumSquares:=fSumSquares+value*value; if value>fmax then fmax:=value; if value<fmin then fmin:=value; end; procedure T1Dstats.Append(values: TAbstract1Dstats); begin (* fcount:=fcount+values.fcount; fsum:=fsum+values.fsum; fSumSquares:=fSumSquares+values.fSumSquares; if values.fmin<fmin then fmin:=values.fmin; if values.fmax>fmax then fmax:=values.fmax; *) Raise Exception.Create('T1Dstats.append: stdDev value under construction (have to do later)'); end; function T1Dstats.getAve: Real; begin if fcount=0 then Raise Exception.Create('T1Dstats.ave: empty list'); Result:=fsum/fcount; end; function T1Dstats.getRMS: Real; begin result:=sqrt(fSumSquares/fcount); end; function T1DStats.getStdDev: Real; begin result:=sqrt(fSumDiff/fcount); end; function T1Dstats.getSampleStdDev: Real; begin result:=sqrt(fSumDiff/(fcount-1)); end; (* T1DFullStats *) constructor T1DFullStats.Create; begin inherited Create; fvalues:=TList.Create; end; procedure T1DFullStats.Clear; var i: Integer; begin inherited Clear; for i:=0 to fvalues.Count-1 do Dispose(PDouble(fvalues[i])); fvalues.Clear; end; destructor T1DFullStats.Destroy; begin Clear; fvalues.Free; inherited Destroy; end; procedure T1DFullStats.Add(value: Real); var pval: PDouble; begin inherited Add(value); New(pval); pval^:=value; fvalues.Add(pval); end; procedure T1DFullStats.Draw(series: TLineSeries); var i: Integer; begin fvalues.Sort(RealCompareFunc); series.Clear; for i:=0 to fvalues.Count-1 do begin series.AddXY(PDouble(fvalues[i])^,i/fvalues.Count); series.AddXY(PDouble(fvalues[i])^,(i+1)/fvalues.Count); end; end; (* TDiscretePick *) procedure TDiscretePick.Normalize; var i: Integer; s: Real; begin s:=0; for i:=0 to count-1 do s:=s+prob[i]; Assert(s>0,'TDiscretePick.Normalize: zero total probability'); for i:=0 to count-1 do prob[i]:=prob[i]/s; end; (* TSimplestPick *) procedure TSimplestPick.SetCount(value: Integer); begin fCount:=value; SetLength(fProb,value); SetLength(fSumOfProbs,value); fchanged:=true; end; function TSimplestPick.GetCount: Integer; begin Result:=fCount; end; procedure TSimplestPick.SetProb(index: Integer; value: Real); begin fProb[index]:=value; fchanged:=true; end; function TSimplestPick.GetProb(index: Integer): Real; begin Result:=fprob[index]; end; procedure TSimplestPick.Prepare; var s: Real; i: Integer; begin normalize; s:=0; for i:=0 to fCount-1 do begin s:=s+prob[i]; fSumOfProbs[i]:=s; end; fchanged:=false; end; function TSimplestPick.Pick: Integer; var i: Integer; r: Real; begin if fChanged then prepare; r:=Random; i:=0; while r>fSumOfProbs[i] do inc(i); Result:=i; end; (* TSmallCountPick *) procedure TSmallCountPick.SetCount(value: Integer); begin fCount:=value; SetLength(fProb,value); SetLength(fSumOfProbs,value); SetLength(fIndexes,value); fchanged:=true; end; procedure TSmallCountPick.NewPrepare; var s: Real; i: Integer; begin normalize; s:=0; fNonZeroCount:=0; for i:=0 to fCount-1 do if prob[i]>0 then begin s:=s+prob[i]; fSumOfProbs[fNonZeroCount]:=s; fIndexes[fNonZeroCount]:=i; inc(fNonZeroCount); end; if fNonZeroCount=1 then fPickingProc:=NoChoice else if fNonZeroCount=2 then fPickingProc:=OneOfTwo else fPickingProc:=OneOfMany; fchanged:=false; end; function TSmallCountPick.NoChoice: Integer; begin Result:=fIndexes[0]; end; function TSmallCountPick.OneOfTwo: Integer; begin if Random<fSumOfProbs[0] then Result:=fIndexes[0] else Result:=fIndexes[1]; end; function TSmallCOuntPick.OneofMany: Integer; var i: Integer; r: Real; begin r:=Random; i:=0; while r>fSumOfProbs[i] do inc(i); Result:=fIndexes[i]; end; function TSmallCountPick.Pick: Integer; begin if fChanged then NewPrepare; Result:=fPickingProc; end; (* TNoChoicePick *) procedure TNoChoicePick.SetCount(value: Integer); begin assert(value=1,'unable to change count'); end; function TNoChoicePick.GetCount: Integer; begin Result:=1; end; procedure TNoChoicePick.SetProb(index: Integer; value: Real); begin end; function TNoChoicePick.GetProb(index: Integer): Real; begin Result:=1; end; function TNoChoicePick.Pick: Integer; begin Result:=0; end; (* TOneOfTwoChoicePick *) procedure TOneOfTwoChoicePick.SetCount(value: Integer); begin assert(value=2,'unable to change count'); end; function TOneOfTwoChoicePick.GetCount: Integer; begin Result:=2; end; procedure TOneOfTwoChoicePick.SetProb(index: Integer; value: Real); begin fprob[index]:=value; end; function TOneOfTwoChoicePick.GetProb(index: Integer): Real; begin Result:=fprob[index]; end; function TOneOfTwoChoicePick.Pick: Integer; begin if Random*(fprob[0]+fprob[1])<fprob[0] then Result:=0 else Result:=1; end; (* TPermanentOneOfTwoChoicePick *) procedure TPermanentOneOfTwoChoicePick.SetCount(value: Integer); begin assert(value=2,'PermanentOneOfTwoChoicePick: unable to change count'); end; function TPermanentOneOfTwoChoicePick.GetCount: Integer; begin Result:=2; end; procedure TPermanentOneOfTwoChoicePick.SetProb(index: Integer; value: Real); begin fprob[index]:=value; fthreshold:=fprob[0]/(fprob[0]+fprob[1]); end; function TPermanentOneOfTwoChoicePick.GetProb(index: Integer): Real; begin Result:=fprob[index]; end; function TPermanentOneOfTwoChoicePick.Pick: Integer; begin if Random<fthreshold then Result:=0 else Result:=1; end; //фабрика function CreateAppropriatePick(count: Integer;PickToChangeRatio: Real=1000): TDiscretePick; begin if count=0 then Raise Exception.Create('CreateAppropriatePick: zero count'); if count=1 then Result:=TNoChoicePick.Create else if count=2 then begin if PickToChangeRatio>10 then Result:=TPermanentOneOfTwoChoicePick.Create else Result:=TOneOfTwoChoicePick.Create; end else begin Result:=TSimplestPick.create; Result.Count:=count; end; end; function RealCompareFunc(P1,P2: Pointer): Integer; begin if PDouble(P1)^<PDouble(P2)^ then Result:=-1 else if PDouble(P1)^>PDouble(P2)^ then Result:=1 else Result:=0; end; end.
unit mainNew; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,DATEUTILS, Vcl.ExtCtrls, Vcl.Buttons, Data.DB, Data.Win.ADODB; type TForm2 = class(TForm) cbTask: TComboBox; Label1: TLabel; dtdate: TDateTimePicker; Label2: TLabel; edAutor: TEdit; Label3: TLabel; Memo: TMemo; Label4: TLabel; ADOConnection: TADOConnection; bOK: TBitBtn; TrayIcon: TTrayIcon; ADOCommand: TADOCommand; ADOQuery: TADOQuery; procedure bOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure ReTask(); public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.FormShow(Sender: TObject); begin ADOConnection.Connected := false; ReTask(); try ADOConnection.Connected := True; finally bOK.Enabled := ADOConnection.Connected; end; if not ADOConnection.Connected then begin if MessageDlg('Нет соединения с базой данных, закрыть программу?', mtConfirmation, mbYesNo, 0) = mrYes then begin Close; end end; end; procedure TForm2.ReTask(); Begin cbTask.ItemIndex:= 0; dtdate.Date:= IncDay(now,7); Memo.Lines.Clear; End; procedure TForm2.bOKClick(Sender: TObject); var s:string; begin if not ADOConnection.Connected then begin bOK.Enabled := ADOConnection.Connected; if MessageDlg('Нет соединения с базой данных, закрыть программу?', mtConfirmation, mbYesNo, 0) = mrYes then begin Close; end end; if (Length(cbTask.Text) < 3) OR (Length(Memo.Lines.Text) < 3) OR (Length(Memo.Lines.Text) < 3) then begin ShowMessage('Все поля заявки должны быть заполнены!'); exit; end; ADOQuery.Parameters.ParamByName('name').Value := cbTask.Text; ADOQuery.Parameters.ParamByName('date').DataType:= ftDateTime; ADOQuery.Parameters.ParamByName('date').Value := now; ADOQuery.Parameters.ParamByName('note').Value := Memo.Lines.Text; ADOQuery.Parameters.ParamByName('user_id').Value := edAutor.Text; ADOQuery.Parameters.ParamByName('status_id').Value := 1; ADOQuery.Parameters.ParamByName('userto_id').Value := 2; ADOQuery.Parameters.ParamByName('dateto').DataType:= ftDateTime; ADOQuery.Parameters.ParamByName('dateto').Value := dtdate.Date; ADOQuery.Parameters.ParamByName('ID').Direction:= pdReturnValue ; ADOQuery.ExecSQL; s:=''; try s:=' №'+inttostr(ADOQuery.Parameters.ParamByName('ID').Value); finally end; if MessageDlg('Ваша заявка'+s+' принята, закрыть программу?', mtConfirmation, mbYesNo, 0) = mrYes then begin Close; end else begin ReTask(); end; end; end.
unit nsCustomStyleProcessor; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\f1DocumentTagsImplementation\nsCustomStyleProcessor.pas" // Стереотип: "ServiceImplementation" // Элемент модели: "TnsCustomStyleProcessor" MUID: (53AC08C900D0) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , l3ProtoObject , evCustomStyleManager , evdTypes , afwNavigation , l3Variant , nevTools ; type TnsCustomStyleProcessor = {final} class(Tl3ProtoObject, IevCustomStyleManager) private procedure ReadLinkInfo(aSeg: Tl3Variant; const aPara: InevPara); function GetLinkAddress(aSeg: Tl3Variant): TevAddress; protected function pm_GetLinkViewKind(aSeg: Tl3Variant): TevLinkViewKind; procedure pm_SetLinkViewKind(aSeg: Tl3Variant; aValue: TevLinkViewKind); public function IsAbolishedDocumentLink(aSeg: Tl3Variant; const aPara: InevPara): Boolean; function IsVisitedDocumentLink(aSeg: Tl3Variant): Boolean; class function Instance: TnsCustomStyleProcessor; {* Метод получения экземпляра синглетона TnsCustomStyleProcessor } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } protected property LinkViewKind[aSeg: Tl3Variant]: TevLinkViewKind read pm_GetLinkViewKind write pm_SetLinkViewKind; end;//TnsCustomStyleProcessor implementation uses l3ImplUses , evdTextStyle_Const , k2Tags , k2Const , DocumentUnit , SysUtils {$If Defined(k2ForEditor)} , evParaTools {$IfEnd} // Defined(k2ForEditor) , Document_Const , BaseTypesUnit , HyperLink_Const {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} , nscDocumentHistory {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) , l3Base //#UC START# *53AC08C900D0impl_uses* //#UC END# *53AC08C900D0impl_uses* ; var g_TnsCustomStyleProcessor: TnsCustomStyleProcessor = nil; {* Экземпляр синглетона TnsCustomStyleProcessor } procedure TnsCustomStyleProcessorFree; {* Метод освобождения экземпляра синглетона TnsCustomStyleProcessor } begin l3Free(g_TnsCustomStyleProcessor); end;//TnsCustomStyleProcessorFree function TnsCustomStyleProcessor.pm_GetLinkViewKind(aSeg: Tl3Variant): TevLinkViewKind; //#UC START# *53AD54E80320_53AC08C900D0get_var* //#UC END# *53AD54E80320_53AC08C900D0get_var* begin //#UC START# *53AD54E80320_53AC08C900D0get_impl* Assert(aSeg.IsValid and aSeg.IsKindOf(k2_typHyperLink)); Result := TevLinkViewKind(aSeg.rAtomEx([k2_tiChildren, k2_tiByIndex, 0]).IntA[k2_tiViewKind]); //#UC END# *53AD54E80320_53AC08C900D0get_impl* end;//TnsCustomStyleProcessor.pm_GetLinkViewKind procedure TnsCustomStyleProcessor.pm_SetLinkViewKind(aSeg: Tl3Variant; aValue: TevLinkViewKind); //#UC START# *53AD54E80320_53AC08C900D0set_var* //#UC END# *53AD54E80320_53AC08C900D0set_var* begin //#UC START# *53AD54E80320_53AC08C900D0set_impl* Assert(aSeg.IsValid and aSeg.IsKindOf(k2_typHyperLink)); with aSeg.rAtomEx([k2_tiChildren, k2_tiByIndex, 0]) do if IsValid then (* [16:01] МВ> Че-то в редакторе поломалось: Project Nemesis.exe raised exception class EAssertionFailed with message 'Невозможно присвоить атрибут в Tk2NullTagImpl (w:\common\components\rtl\Garant\L3\l3Variant.pas, line 1566)' При открытии документа 890312 *) IntA[k2_tiViewKind] := Ord(aValue); //#UC END# *53AD54E80320_53AC08C900D0set_impl* end;//TnsCustomStyleProcessor.pm_SetLinkViewKind procedure TnsCustomStyleProcessor.ReadLinkInfo(aSeg: Tl3Variant; const aPara: InevPara); //#UC START# *53AC3FF3021A_53AC08C900D0_var* const lc_Map: array [TLinkKind] of TevLinkViewKind = ( ev_lvkInternalInvalid, ev_lvkInternalValid, ev_lvkExternal, ev_lvkInternalAbolished, ev_lvkInternalPreactive, ev_lvkExternalENO, ev_lvkInternalEdition, ev_lvkScript ); var l_Doc: IDocument; l_DocV: Tl3Variant; l_Topic: TTopic; l_Addr: TevAddress; l_ExtID: Integer; l_Link: ILink; //#UC END# *53AC3FF3021A_53AC08C900D0_var* begin //#UC START# *53AC3FF3021A_53AC08C900D0_impl* if LinkViewKind[aSeg] = ev_lvkUnknown then begin l_ExtID := 0; l_Addr := GetLinkAddress(aSeg); if (l_Addr.TypeID <> CI_TOPIC) then Exit; if Supports(aPara.DocumentContainer, IDocument, l_Doc) then begin with l_Topic do begin rPid.rObjectId := TObjectId(l_Addr.DocID); rPid.rClassId := TClassId(l_Addr.TypeID); rPosition.rPoint := Cardinal(l_Addr.SubID); rPosition.rType := PT_SUB; end; if l_Topic.rPid.rClassId <> 0 then begin if evInPara(aPara.AsObject, k2_typDocument, l_DocV) then l_ExtID := l_DocV.rLong(k2_tiExternalHandle, -1); l_Doc.GetLink(l_ExtID, l_Topic, l_Addr.RevisionID, l_Link); LinkViewKind[aSeg] := lc_Map[l_Link.GetKind]; end; end; end; //#UC END# *53AC3FF3021A_53AC08C900D0_impl* end;//TnsCustomStyleProcessor.ReadLinkInfo function TnsCustomStyleProcessor.GetLinkAddress(aSeg: Tl3Variant): TevAddress; //#UC START# *5542334A00E6_53AC08C900D0_var* const evNullAddress: TevAddress = (DocID : -1; SubID : -1); //#UC END# *5542334A00E6_53AC08C900D0_var* begin //#UC START# *5542334A00E6_53AC08C900D0_impl* Result := evNullAddress; if aSeg.IsValid then with aSeg.rAtomEx([k2_tiChildren, k2_tiByIndex, 0]) do if IsValid then begin with Attr[k2_tiDocID] do if IsValid then Result.DocID := AsLong else Result.DocID := 0; with Attr[k2_tiSubID] do if IsValid then Result.SubID := AsLong else Result.SubID := 0; with Attr[k2_tiType] do if IsValid then Result.TypeID := AsLong else Result.TypeID := ev_defAddressType; with Attr[k2_tiRevision] do if IsValid then Result.RevisionID := AsLong else Result.RevisionID := 0; end;//IsValid //#UC END# *5542334A00E6_53AC08C900D0_impl* end;//TnsCustomStyleProcessor.GetLinkAddress function TnsCustomStyleProcessor.IsAbolishedDocumentLink(aSeg: Tl3Variant; const aPara: InevPara): Boolean; //#UC START# *5549E17B01C5_53AC08C900D0_var* //#UC END# *5549E17B01C5_53AC08C900D0_var* begin //#UC START# *5549E17B01C5_53AC08C900D0_impl* Result := False; if aSeg.IsValid then if aSeg.IsKindOf(k2_typHyperLink) then begin ReadLinkInfo(aSeg, aPara); Result := LinkViewKind[aSeg] = ev_lvkInternalAbolished; end; //#UC END# *5549E17B01C5_53AC08C900D0_impl* end;//TnsCustomStyleProcessor.IsAbolishedDocumentLink function TnsCustomStyleProcessor.IsVisitedDocumentLink(aSeg: Tl3Variant): Boolean; //#UC START# *5549E1DA0063_53AC08C900D0_var* {$If not defined(Admin) AND not defined(Monitorings)} var l_Addr: TevAddress; {$ifend} //#UC END# *5549E1DA0063_53AC08C900D0_var* begin //#UC START# *5549E1DA0063_53AC08C900D0_impl* {$If not defined(Admin) AND not defined(Monitorings)} if aSeg.IsValid then if aSeg.IsKindOf(k2_typHyperLink) then begin l_Addr := GetLinkAddress(aSeg); if (l_Addr.TypeID = CI_TOPIC) then begin Result := TnscDocumentHistory.Instance.HasDocument(l_Addr.DocID - 100000); Exit; end; end; {$ifend} Result := False; //#UC END# *5549E1DA0063_53AC08C900D0_impl* end;//TnsCustomStyleProcessor.IsVisitedDocumentLink class function TnsCustomStyleProcessor.Instance: TnsCustomStyleProcessor; {* Метод получения экземпляра синглетона TnsCustomStyleProcessor } begin if (g_TnsCustomStyleProcessor = nil) then begin l3System.AddExitProc(TnsCustomStyleProcessorFree); g_TnsCustomStyleProcessor := Create; end; Result := g_TnsCustomStyleProcessor; end;//TnsCustomStyleProcessor.Instance class function TnsCustomStyleProcessor.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TnsCustomStyleProcessor <> nil; end;//TnsCustomStyleProcessor.Exists initialization TevCustomStyleManager.Instance.Alien := TnsCustomStyleProcessor.Instance; {* Регистрация TnsCustomStyleProcessor } end.
unit DW.OSDevice; {*******************************************************} { } { 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 // RTL System.SysUtils, System.Types, System.Classes; type TOSPlatform = TOSVersion.TPlatform; TLocaleInfo = record CountryCode: string; CountryDisplayName: string; CurrencySymbol: string; LanguageCode: string; LanguageDisplayName: string; function Culture: string; end; /// <summary> /// Operating System specific functions that operate below FMX /// </summary> /// <remarks> /// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS /// </remarks> TOSDevice = record public class function GetCurrentLocaleInfo: TLocaleInfo; static; /// <summary> /// Returns the model of the device, if available /// </summary> class function GetDeviceModel: string; static; /// <summary> /// Returns the name of the device, whether it is mobile or desktop /// </summary> class function GetDeviceName: string; static; /// <summary> /// Returns a summary of information about the device/application, including Package ID, Version, Device Name and Device ID /// </summary> class function GetDeviceSummary: string; static; /// <summary> /// Returns environment vars /// </summary> class procedure GetEnvironmentVars(const AVars: TStrings); static; /// <summary> /// Returns build for the application package, if any exists /// </summary> class function GetPackageBuild: string; static; /// <summary> /// Returns id for the application package, if any exists /// </summary> class function GetPackageID: string; static; /// <summary> /// Returns version for the application package, if any exists /// </summary> class function GetPackageVersion: string; static; /// <summary> /// Returns the unique id for the device, if any exists /// </summary> class function GetUniqueDeviceID: string; static; class function GetUsername: string; static; /// <summary> /// Returns whether the application is a beta version /// </summary> class function IsBeta: Boolean; static; /// <summary> /// Returns whether the device is a mobile device /// </summary> class function IsMobile: Boolean; static; /// <summary> /// Returns whether the screen is locked /// </summary> class function IsScreenLocked: Boolean; static; /// <summary> /// Returns whether the device has touch capability /// </summary> class function IsTouchDevice: Boolean; static; /// <summary> /// Returns whether the platform matches /// </summary> class function IsPlatform(const APlatform: TOSPlatform): Boolean; static; /// <summary> /// Opens the default browser with the URL /// </summary> class procedure OpenURL(const AURL: string); static; /// <summary> /// Shows the folder that contains the nominated files /// </summary> class procedure ShowFilesInFolder(const AFileNames: array of string); static; end; implementation uses // DW DW.OSLog, {$IF Defined(POSIX)} DW.OSDevice.Posix, {$ENDIF} {$IF Defined(ANDROID)} DW.OSDevice.Android; {$ELSEIF Defined(IOS)} DW.OSDevice.iOS; {$ELSEIF Defined(MACOS)} DW.OSDevice.Mac; {$ELSEIF Defined(MSWINDOWS)} DW.Winapi.Helpers, DW.OSDevice.Win; {$ELSEIF Defined(LINUX)} DW.OSDevice.Linux; {$ENDIF} { TOSDevice } class function TOSDevice.GetCurrentLocaleInfo: TLocaleInfo; begin Result := TPlatformOSDevice.GetCurrentLocaleInfo; end; class function TOSDevice.GetDeviceModel: string; begin {$IF Defined(MACOS)} Result := TPlatformOSDevice.GetDeviceModel; {$ELSE} Result := ''; {$ENDIF} end; class function TOSDevice.GetDeviceName: string; begin Result := TPlatformOSDevice.GetDeviceName; end; class function TOSDevice.GetDeviceSummary: string; begin Result := Format('%s Version: %s, Device: %s (%s)', [GetPackageID, GetPackageVersion, GetDeviceName, GetUniqueDeviceID]); end; class procedure TOSDevice.GetEnvironmentVars(const AVars: TStrings); begin {$IF Defined(MSWINDOWS)} TWinapiHelper.GetEnvironmentVars(AVars, True); {$ELSEIF Defined(POSIX)} TPosixOSDevice.GetEnvironmentVars(AVars); {$ENDIF} end; class function TOSDevice.GetPackageBuild: string; begin {$IF Defined(MSWINDOWS)} Result := TPlatformOSDevice.GetPackageBuild; {$ELSE} Result := ''; {$ENDIF} end; class function TOSDevice.GetPackageID: string; begin Result := TPlatformOSDevice.GetPackageID; end; class function TOSDevice.GetPackageVersion: string; begin Result := TPlatformOSDevice.GetPackageVersion; end; class function TOSDevice.GetUniqueDeviceID: string; begin Result := TPlatformOSDevice.GetUniqueDeviceID; end; class function TOSDevice.GetUsername: string; begin {$IF Defined(MSWINDOWS) or Defined(OSX)} Result := TPlatformOSDevice.GetUsername; {$ELSE} Result := ''; {$ENDIF} end; class function TOSDevice.IsBeta: Boolean; begin {$IF Defined(MSWINDOWS)} Result := TPlatformOSDevice.IsBeta; {$ELSE} Result := False; {$ENDIF} end; class function TOSDevice.IsMobile: Boolean; begin Result := TOSVersion.Platform in [TOSVersion.TPlatform.pfiOS, TOSVersion.TPlatform.pfAndroid]; end; class function TOSDevice.IsPlatform(const APlatform: TOSPlatform): Boolean; begin Result := TOSVersion.Platform = APlatform; end; class function TOSDevice.IsScreenLocked: Boolean; begin {$IF Defined(IOS) or Defined(ANDROID)} Result := TPlatformOSDevice.IsScreenLocked; {$ELSE} Result := False; {$ENDIF} end; class function TOSDevice.IsTouchDevice: Boolean; begin Result := TPlatformOSDevice.IsTouchDevice; end; class procedure TOSDevice.OpenURL(const AURL: string); begin {$IF Defined(IOS)} TPlatformOSDevice.OpenURL(AURL); {$ENDIF} end; class procedure TOSDevice.ShowFilesInFolder(const AFileNames: array of string); begin {$IF Defined(MSWINDOWS) or Defined(OSX)} TPlatformOSDevice.ShowFilesInFolder(AFileNames); {$ENDIF} end; { TLocaleInfo } function TLocaleInfo.Culture: string; begin Result := ''; // WIP end; end.
unit FeatureParserIntf; interface uses Classes, FeatureIntf; type IFeatureParser = interface(IInterface) ['{0017D4E2-14B2-4841-A738-7090AFF16D10}'] function GetErrors: IInterfaceList; function GetFeatureFileName: string; procedure SetFeatureFileName(const Value: string); function Parse: IFeature; procedure SetErrors(const Value: IInterfaceList); property Errors: IInterfaceList read GetErrors write SetErrors; property FeatureFileName: string read GetFeatureFileName write SetFeatureFileName; end; implementation end.
unit aeShader; interface uses windows, types, classes, aeConst, dglOpenGL, sysutils, aeLoggingManager; type TaeShader = class private _text: TStringList; _handle: GLHandle; public constructor Create; destructor destroy; override; function SetShader(text: TStrings): boolean; function LoadFromFile(filename: string): boolean; function Compile: boolean; end; implementation { TaeShader } function TaeShader.Compile: boolean; begin end; constructor TaeShader.Create; begin self._text := TStringList.Create; self._handle := glCreateProgram; end; destructor TaeShader.destroy; begin glDeleteProgram(self._handle); self._text.Free; inherited; end; function TaeShader.LoadFromFile(filename: string): boolean; begin if (FileExists(filename)) then begin self._text.LoadFromFile(filename); Result := true; end else AE_LOGGING.AddEntry('TaeShader.LoadFromFile() : File not found. file=' + filename, AE_LOG_MESSAGE_ENTRY_TYPE_ERROR); end; function TaeShader.SetShader(text: TStrings): boolean; begin self._text.text := text.text; end; end.
unit LUX.GPU.Vulkan.Imager; interface //#################################################################### ■ uses System.Generics.Collections, vulkan_core, vulkan.util, LUX.GPU.Vulkan.root, LUX.GPU.Vulkan.Memory, LUX.GPU.Vulkan.Buffer; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkImager<TVkDevice_,TVkParent_:class> = class; TVkViewer<TVkDevice_,TVkParent_:class> = class; TVkImaBuf<TVkDevice_,TVkParent_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkImaBuf<TVkDevice_,TVkParent_> TVkImaBuf<TVkDevice_,TVkParent_:class> = class( TVkBuffer<TVkDevice_,TVkImager<TVkDevice_,TVkParent_>> ) private type TVkImager_ = TVkImager<TVkDevice_,TVkParent_>; protected ///// アクセス function GetDevice :TVkDevice_; override; public constructor Create; override; ///// プロパティ property Imager :TVkImager_ read GetParent; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkViewer<TVkDevice_,TVkParent_> TVkViewer<TVkDevice_,TVkParent_:class> = class( TVkDeviceObject<TVkDevice_,TVkImager<TVkDevice_,TVkParent_>> ) private type TVkImager_ = TVkImager<TVkDevice_,TVkParent_>; protected _Inform :VkImageViewCreateInfo; _Handle :VkImageView; ///// アクセス function GetDevice :TVkDevice_; override; function GetHandle :VkImageView; procedure SetHandle( const Handle_:VkImageView ); ///// メソッド procedure CreateHandle; procedure DestroHandle; public constructor Create; override; destructor Destroy; override; ///// プロパティ property Imager :TVkImager_ read GetParent; property Inform :VkImageViewCreateInfo read _Inform; property Handle :VkImageView read GetHandle write SetHandle; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkImaMem<TVkDevice_,TVkParent_> TVkImaMem<TVkDevice_,TVkParent_:class> = class( TVkMemory<TVkDevice_,TVkImager<TVkDevice_,TVkParent_>> ) private type TVkImager_ = TVkImager<TVkDevice_,TVkParent_>; protected ///// アクセス function GetDevice :TVkDevice_; override; function GetSize :VkDeviceSize; override; function GetTypeI :UInt32; override; ///// メソッド procedure CreateHandle; override; public ///// プロパティ property Imager :TVkImager_ read GetParent; property Size :VkDeviceSize read GetSize ; property TypeI :UInt32 read GetTypeI ; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkImager<TVkDevice_,TVkParent_> TVkImager<TVkDevice_,TVkParent_:class> = class( TVkDeviceObject<TVkDevice_,TVkParent_> ) private type TVkViewer_ = TVkViewer<TVkDevice_,TVkParent_>; TVkImaMem_ = TVkImaMem<TVkDevice_,TVkParent_>; TVkImaBuf_ = TVkImaBuf<TVkDevice_,TVkParent_>; ///// メソッド procedure InitBufferSize; protected _Usagers :VkImageUsageFlags; _Featurs :VkFormatFeatureFlags; _Inform :VkImageCreateInfo; _Handle :VkImage; _Memory :TVkImaMem_; _Viewer :TVkViewer_; _Buffer :TVkImaBuf_; ///// アクセス function GetStaging :Boolean; virtual; function GetPixelsW :UInt32; virtual; procedure SetPixelsW( const PixelsW_:UInt32 ); virtual; function GetPixelsH :UInt32; virtual; procedure SetPixelsH( const PixelsH_:UInt32 ); virtual; function GetHandle :VkImage; virtual; procedure SetHandle( const Handle_:VkImage ); virtual; function GetRequir :VkMemoryRequirements; virtual; ///// メソッド procedure CreateHandle; procedure DestroHandle; public constructor Create; override; destructor Destroy; override; ///// プロパティ property Usagers :VkImageUsageFlags read _Usagers write _Usagers; property Featurs :VkFormatFeatureFlags read _Featurs write _Featurs; property Staging :Boolean read GetStaging ; property Inform :VkImageCreateInfo read _Inform ; property PixelsW :UInt32 read GetPixelsW write SetPixelsW; property PixelsH :UInt32 read GetPixelsH write SetPixelsH; property Handle :VkImage read GetHandle write SetHandle ; property Requir :VkMemoryRequirements read GetRequir ; property Memory :TVkImaMem_ read _Memory ; property Viewer :TVkViewer_ read _Viewer ; ///// メソッド function Bind( const Memory_:TVkImaMem_ ) :Boolean; function Map( var Pointer_:Pointer ) :Boolean; procedure Unmap; procedure LoadFromFile( const FileName_:String ); end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses FMX.Types, vulkan.util_init, LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkImaBuf<TVkDevice_,TVkParent_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkImaBuf<TVkDevice_,TVkParent_>.GetDevice :TVkDevice_; begin Result := Imager.Device; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkImaBuf<TVkDevice_,TVkParent_>.Create; begin inherited; Usage := Ord( VK_BUFFER_USAGE_TRANSFER_SRC_BIT ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkViewer<TVkDevice_,TVkParent_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkViewer<TVkDevice_,TVkParent_>.GetDevice :TVkDevice_; begin Result := Imager.Device; end; //------------------------------------------------------------------------------ function TVkViewer<TVkDevice_,TVkParent_>.GetHandle :VkImageView; begin if _Handle = VK_NULL_HANDLE then CreateHandle; Result := _Handle; end; procedure TVkViewer<TVkDevice_,TVkParent_>.SetHandle( const Handle_:VkImageView ); begin if _Handle <> VK_NULL_HANDLE then DestroHandle; _Handle := Handle_; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkViewer<TVkDevice_,TVkParent_>.CreateHandle; begin with _Inform do begin sType := VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; pNext := nil; flags := 0; image := Imager.Handle; viewType := VK_IMAGE_VIEW_TYPE_2D; format := VK_FORMAT_R8G8B8A8_UNORM; with components do begin r := VK_COMPONENT_SWIZZLE_R; g := VK_COMPONENT_SWIZZLE_G; b := VK_COMPONENT_SWIZZLE_B; a := VK_COMPONENT_SWIZZLE_A; end; with subresourceRange do begin aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT ); baseMipLevel := 0; levelCount := 1; baseArrayLayer := 0; layerCount := 1; end; end; Assert( vkCreateImageView( TVkDevice( Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS ); end; procedure TVkViewer<TVkDevice_,TVkParent_>.DestroHandle; begin vkDestroyImageView( TVkDevice( Device ).Handle, _Handle, nil ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkViewer<TVkDevice_,TVkParent_>.Create; begin inherited; _Handle := VK_NULL_HANDLE; end; destructor TVkViewer<TVkDevice_,TVkParent_>.Destroy; begin Handle := VK_NULL_HANDLE; inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkImaMem<TVkDevice_,TVkParent_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkImaMem<TVkDevice_,TVkParent_>.GetDevice :TVkDevice_; begin Result := Imager.Device; end; //------------------------------------------------------------------------------ function TVkImaMem<TVkDevice_,TVkParent_>.GetSize :VkDeviceSize; begin Result := Imager.Requir.size; end; //------------------------------------------------------------------------------ function TVkImaMem<TVkDevice_,TVkParent_>.GetTypeI :UInt32; var R :VkFlags; begin if Imager.Staging then R := 0 else R := Ord( VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ) or Ord( VK_MEMORY_PROPERTY_HOST_COHERENT_BIT ); Assert( TVkDevice( Device ).memory_type_from_properties( Imager.Requir.memoryTypeBits, R, Result ) ); end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkImaMem<TVkDevice_,TVkParent_>.CreateHandle; begin inherited; Imager.Bind( Self ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkImager<TVkDevice_,TVkParent_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// メソッド procedure TVkImager<TVkDevice_,TVkParent_>.InitBufferSize; begin _Buffer.Size := 4{Byte} * PixelsH * PixelsW; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkImager<TVkDevice_,TVkParent_>.GetStaging :Boolean; var Ps :VkFormatProperties; Fs :VkFormatFeatureFlags; begin vkGetPhysicalDeviceFormatProperties( TVkDevice( Device ).Physic, VK_FORMAT_R8G8B8A8_UNORM, @Ps ); (* See if we can use a linear tiled image for a texture, if not, we will * need a staging buffer for the texture data *) Fs := Ord( VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) or Featurs; Result := ( Ps.linearTilingFeatures and Fs ) <> Fs; if Result then Assert( ( Ps.optimalTilingFeatures and Fs ) = Fs ); end; //------------------------------------------------------------------------------ function TVkImager<TVkDevice_,TVkParent_>.GetPixelsW :UInt32; begin Result := _Inform.extent.width; end; procedure TVkImager<TVkDevice_,TVkParent_>.SetPixelsW( const PixelsW_:UInt32 ); begin _Inform.extent.width := PixelsW_; Handle := VK_NULL_HANDLE; InitBufferSize; end; function TVkImager<TVkDevice_,TVkParent_>.GetPixelsH :UInt32; begin Result := _Inform.extent.height; end; procedure TVkImager<TVkDevice_,TVkParent_>.SetPixelsH( const PixelsH_:UInt32 ); begin _Inform.extent.height := PixelsH_; Handle := VK_NULL_HANDLE; InitBufferSize; end; //------------------------------------------------------------------------------ function TVkImager<TVkDevice_,TVkParent_>.GetHandle :VkImage; begin if _Handle = VK_NULL_HANDLE then CreateHandle; Result := _Handle; end; procedure TVkImager<TVkDevice_,TVkParent_>.SetHandle( const Handle_:VkImage ); begin if _Handle <> VK_NULL_HANDLE then DestroHandle; _Handle := Handle_; end; //------------------------------------------------------------------------------ function TVkImager<TVkDevice_,TVkParent_>.GetRequir :VkMemoryRequirements; begin vkGetImageMemoryRequirements( TVkDevice( Device ).Handle, Handle, @Result ); end; /////////////////////////////////////////////////////////////////////// メソッド procedure TVkImager<TVkDevice_,TVkParent_>.CreateHandle; begin if Staging then Usagers := Usagers or Ord( VK_IMAGE_USAGE_TRANSFER_DST_BIT ); with _Inform do begin sType := VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; pNext := nil; flags := 0; imageType := VK_IMAGE_TYPE_2D; format := VK_FORMAT_R8G8B8A8_UNORM; with extent do begin // width = PixelsW; // height = PixelsH; depth := 1; end; mipLevels := 1; arrayLayers := 1; samples := NUM_SAMPLES; if Staging then tiling := VK_IMAGE_TILING_OPTIMAL else tiling := VK_IMAGE_TILING_LINEAR; usage := Ord( VK_IMAGE_USAGE_SAMPLED_BIT ) or Usagers; sharingMode := VK_SHARING_MODE_EXCLUSIVE; queueFamilyIndexCount := 0; pQueueFamilyIndices := nil; if Staging then initialLayout := VK_IMAGE_LAYOUT_UNDEFINED else initialLayout := VK_IMAGE_LAYOUT_PREINITIALIZED; end; Assert( vkCreateImage( TVkDevice( Device ).Handle, @_Inform, nil, @_Handle ) = VK_SUCCESS ); Assert( Bind( _Memory ) ); end; procedure TVkImager<TVkDevice_,TVkParent_>.DestroHandle; begin _Memory.Handle := VK_NULL_HANDLE; vkDestroyImage( TVkDevice( Device ).Handle, _Handle , nil ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkImager<TVkDevice_,TVkParent_>.Create; begin inherited; _Handle := VK_NULL_HANDLE; _Memory := TVkImaMem_.Create( Self ); _Viewer := TVkViewer_.Create( Self ); _Buffer := TVkImaBuf_.Create( Self ); Usagers := 0; Featurs := 0; end; destructor TVkImager<TVkDevice_,TVkParent_>.Destroy; begin _Buffer.Free; _Viewer.Free; _Memory.Free; Handle := VK_NULL_HANDLE; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TVkImager<TVkDevice_,TVkParent_>.Bind( const Memory_:TVkImaMem_ ) :Boolean; begin Result := vkBindImageMemory( TVkDevice( Device ).Handle, Handle, Memory_.Handle, 0 ) = VK_SUCCESS; end; //------------------------------------------------------------------------------ function TVkImager<TVkDevice_,TVkParent_>.Map( var Pointer_:Pointer ) :Boolean; begin if Staging then Result := _Buffer.Memory.Map( Pointer_ ) else Result := _Memory.Map( Pointer_ ); end; procedure TVkImager<TVkDevice_,TVkParent_>.Unmap; begin if Staging then _Buffer.Memory.Unmap else _Memory.Unmap; end; //------------------------------------------------------------------------------ procedure TVkImager<TVkDevice_,TVkParent_>.LoadFromFile( const FileName_:String ); var PsW :Int32; PsH :Int32; res :VkResult; pass :Boolean; cmd_bufs :array [ 0..1-1 ] of VkCommandBuffer; fenceInfo :VkFenceCreateInfo; cmdFence :VkFence; submit_info :array [ 0..1-1 ] of VkSubmitInfo; subres :VkImageSubresource; layout :VkSubresourceLayout; data :Pointer; rowPitch :UInt64; copy_region :VkBufferImageCopy; _imageLayout :VkImageLayout; begin if not read_ppm( FileName_, PsW, PsH, 0, nil ) then begin Log.d( 'Could not read texture file ' + FileName_ ); RunError( 256-1 ); end; PixelsW := PsW; PixelsH := PsH; ////////// TVkDevice( Device ).Poolers[0].Commans[0].EndRecord; cmd_bufs[0] := TVkDevice( Device ).Poolers[0].Commans[0].Handle; fenceInfo.sType := VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext := nil; fenceInfo.flags := 0; vkCreateFence( TVkDevice( Device ).Handle, @fenceInfo, nil, @cmdFence ); submit_info[0] := Default( VkSubmitInfo ); submit_info[0].pNext := nil; submit_info[0].sType := VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount := 0; submit_info[0].pWaitSemaphores := nil; submit_info[0].pWaitDstStageMask := nil; submit_info[0].commandBufferCount := 1; submit_info[0].pCommandBuffers := @cmd_bufs[0]; submit_info[0].signalSemaphoreCount := 0; submit_info[0].pSignalSemaphores := nil; (* Queue the command buffer for execution *) Assert( vkQueueSubmit( TVkDevice( Device ).QueuerG, 1, @submit_info[0], cmdFence ) = VK_SUCCESS ); subres := Default( VkImageSubresource ); subres.aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT ); subres.mipLevel := 0; subres.arrayLayer := 0; layout := Default( VkSubresourceLayout ); if not Staging then begin (* Get the subresource layout so we know what the row pitch is *) vkGetImageSubresourceLayout( TVkDevice( Device ).Handle, Handle, @subres, @layout ); end; (* Make sure command buffer is finished before mapping *) repeat res := vkWaitForFences( TVkDevice( Device ).Handle, 1, @cmdFence, VK_TRUE, FENCE_TIMEOUT ); until res <> VK_TIMEOUT; Assert( res = VK_SUCCESS ); vkDestroyFence( TVkDevice( Device ).Handle, cmdFence, nil ); ////////// Map( data ); (* Read the ppm file into the mappable image's memory *) if Staging then rowPitch := PixelsW * 4 else rowPitch := layout.rowPitch; if not read_ppm( FileName_, PsW, PsH, rowPitch, data ) then begin Log.d( 'Could not load texture file lunarg.ppm' ); RunError( 256-1 ); end; Unmap; ////////// Assert( vkResetCommandBuffer( TVkDevice( Device ).Poolers[0].Commans[0].Handle, 0 ) = VK_SUCCESS ); TVkDevice( Device ).Poolers[0].Commans[0].BeginRecord; if not Staging then begin (* If we can use the linear tiled image as a texture, just do it *) _imageLayout := VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; set_image_layout( TVkDevice( Device ).Instan.Vulkan, Handle, Ord( VK_IMAGE_ASPECT_COLOR_BIT ), VK_IMAGE_LAYOUT_PREINITIALIZED, _imageLayout, Ord( VK_PIPELINE_STAGE_HOST_BIT ), Ord( VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT ) ); end else begin (* Since we're going to blit to the texture image, set its layout to * DESTINATION_OPTIMAL *) set_image_layout( TVkDevice( Device ).Instan.Vulkan, Handle, Ord( VK_IMAGE_ASPECT_COLOR_BIT ), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, Ord( VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT ), Ord( VK_PIPELINE_STAGE_TRANSFER_BIT ) ); copy_region.bufferOffset := 0; copy_region.bufferRowLength := PixelsW; copy_region.bufferImageHeight := PixelsH; copy_region.imageSubresource.aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT ); copy_region.imageSubresource.mipLevel := 0; copy_region.imageSubresource.baseArrayLayer := 0; copy_region.imageSubresource.layerCount := 1; copy_region.imageOffset.x := 0; copy_region.imageOffset.y := 0; copy_region.imageOffset.z := 0; copy_region.imageExtent.width := PixelsW; copy_region.imageExtent.height := PixelsH; copy_region.imageExtent.depth := 1; (* Put the copy command into the command buffer *) vkCmdCopyBufferToImage( TVkDevice( Device ).Poolers[0].Commans[0].Handle, _Buffer.Handle, Handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, @copy_region ); (* Set the layout for the texture image from DESTINATION_OPTIMAL to * SHADER_READ_ONLY *) _imageLayout := VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; set_image_layout( TVkDevice( Device ).Instan.Vulkan, Handle, Ord( VK_IMAGE_ASPECT_COLOR_BIT ), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, _imageLayout, Ord( VK_PIPELINE_STAGE_TRANSFER_BIT ), Ord( VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT ) ); end; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 end. //######################################################################### ■
unit TTSELTAG2Table; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSELTAG2Record = record PSortBy: String[120]; PSeparateby: String[10]; PGroupBy: String[10]; PCifFlag: String[1]; PLoanNum: String[20]; PAcolNum: Integer; PTrackCode: String[8]; PSubNum: Integer; End; TTTSELTAG2Buffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSELTAG2Record; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSELTAG2 = (TTSELTAG2PrimaryKey); TTTSELTAG2Table = class( TDBISAMTableAU ) private FDFSortBy: TStringField; FDFSeparateby: TStringField; FDFGroupBy: TStringField; FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFAcolNum: TIntegerField; FDFTrackCode: TStringField; FDFSubNum: TIntegerField; procedure SetPSortBy(const Value: String); function GetPSortBy:String; procedure SetPSeparateby(const Value: String); function GetPSeparateby:String; procedure SetPGroupBy(const Value: String); function GetPGroupBy:String; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPAcolNum(const Value: Integer); function GetPAcolNum:Integer; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPSubNum(const Value: Integer); function GetPSubNum:Integer; procedure SetEnumIndex(Value: TEITTSELTAG2); function GetEnumIndex: TEITTSELTAG2; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSELTAG2Record; procedure StoreDataBuffer(ABuffer:TTTSELTAG2Record); property DFSortBy: TStringField read FDFSortBy; property DFSeparateby: TStringField read FDFSeparateby; property DFGroupBy: TStringField read FDFGroupBy; property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFAcolNum: TIntegerField read FDFAcolNum; property DFTrackCode: TStringField read FDFTrackCode; property DFSubNum: TIntegerField read FDFSubNum; property PSortBy: String read GetPSortBy write SetPSortBy; property PSeparateby: String read GetPSeparateby write SetPSeparateby; property PGroupBy: String read GetPGroupBy write SetPGroupBy; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PAcolNum: Integer read GetPAcolNum write SetPAcolNum; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PSubNum: Integer read GetPSubNum write SetPSubNum; published property Active write SetActive; property EnumIndex: TEITTSELTAG2 read GetEnumIndex write SetEnumIndex; end; { TTTSELTAG2Table } procedure Register; implementation procedure TTTSELTAG2Table.CreateFields; begin FDFSortBy := CreateField( 'SortBy' ) as TStringField; FDFSeparateby := CreateField( 'Separateby' ) as TStringField; FDFGroupBy := CreateField( 'GroupBy' ) as TStringField; FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFAcolNum := CreateField( 'AcolNum' ) as TIntegerField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFSubNum := CreateField( 'SubNum' ) as TIntegerField; end; { TTTSELTAG2Table.CreateFields } procedure TTTSELTAG2Table.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSELTAG2Table.SetActive } procedure TTTSELTAG2Table.SetPSortBy(const Value: String); begin DFSortBy.Value := Value; end; function TTTSELTAG2Table.GetPSortBy:String; begin result := DFSortBy.Value; end; procedure TTTSELTAG2Table.SetPSeparateby(const Value: String); begin DFSeparateby.Value := Value; end; function TTTSELTAG2Table.GetPSeparateby:String; begin result := DFSeparateby.Value; end; procedure TTTSELTAG2Table.SetPGroupBy(const Value: String); begin DFGroupBy.Value := Value; end; function TTTSELTAG2Table.GetPGroupBy:String; begin result := DFGroupBy.Value; end; procedure TTTSELTAG2Table.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSELTAG2Table.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSELTAG2Table.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSELTAG2Table.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSELTAG2Table.SetPAcolNum(const Value: Integer); begin DFAcolNum.Value := Value; end; function TTTSELTAG2Table.GetPAcolNum:Integer; begin result := DFAcolNum.Value; end; procedure TTTSELTAG2Table.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSELTAG2Table.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSELTAG2Table.SetPSubNum(const Value: Integer); begin DFSubNum.Value := Value; end; function TTTSELTAG2Table.GetPSubNum:Integer; begin result := DFSubNum.Value; end; procedure TTTSELTAG2Table.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('SortBy, String, 120, N'); Add('Separateby, String, 10, N'); Add('GroupBy, String, 10, N'); Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('AcolNum, Integer, 0, N'); Add('TrackCode, String, 8, N'); Add('SubNum, Integer, 0, N'); end; end; procedure TTTSELTAG2Table.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, SortBy;Separateby;GroupBy;CifFlag;LoanNum;AcolNum;TrackCode;SubNum, Y, Y, N, N'); end; end; procedure TTTSELTAG2Table.SetEnumIndex(Value: TEITTSELTAG2); begin case Value of TTSELTAG2PrimaryKey : IndexName := ''; end; end; function TTTSELTAG2Table.GetDataBuffer:TTTSELTAG2Record; var buf: TTTSELTAG2Record; begin fillchar(buf, sizeof(buf), 0); buf.PSortBy := DFSortBy.Value; buf.PSeparateby := DFSeparateby.Value; buf.PGroupBy := DFGroupBy.Value; buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PAcolNum := DFAcolNum.Value; buf.PTrackCode := DFTrackCode.Value; buf.PSubNum := DFSubNum.Value; result := buf; end; procedure TTTSELTAG2Table.StoreDataBuffer(ABuffer:TTTSELTAG2Record); begin DFSortBy.Value := ABuffer.PSortBy; DFSeparateby.Value := ABuffer.PSeparateby; DFGroupBy.Value := ABuffer.PGroupBy; DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFAcolNum.Value := ABuffer.PAcolNum; DFTrackCode.Value := ABuffer.PTrackCode; DFSubNum.Value := ABuffer.PSubNum; end; function TTTSELTAG2Table.GetEnumIndex: TEITTSELTAG2; var iname : string; begin result := TTSELTAG2PrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSELTAG2PrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSELTAG2Table, TTTSELTAG2Buffer ] ); end; { Register } function TTTSELTAG2Buffer.FieldNameToIndex(s:string):integer; const flist:array[1..8] of string = ('SORTBY','SEPARATEBY','GROUPBY','CIFFLAG','LOANNUM','ACOLNUM' ,'TRACKCODE','SUBNUM' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 8) and (flist[x] <> s) do inc(x); if x <= 8 then result := x else result := 0; end; function TTTSELTAG2Buffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftInteger; 7 : result := ftString; 8 : result := ftInteger; end; end; function TTTSELTAG2Buffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PSortBy; 2 : result := @Data.PSeparateby; 3 : result := @Data.PGroupBy; 4 : result := @Data.PCifFlag; 5 : result := @Data.PLoanNum; 6 : result := @Data.PAcolNum; 7 : result := @Data.PTrackCode; 8 : result := @Data.PSubNum; end; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.MainForm; { Application main form. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Actions, System.ImageList, System.Win.TaskbarCore, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.Taskbar, Vcl.ActnList, Vcl.ImgList, Vcl.ToolWin, ChromeTabs, ChromeTabsClasses, ChromeTabsTypes, kcontrols, kprogress, Spring, DDuce.Settings.TextFormat, DDuce.Utils, LogViewer.Interfaces, LogViewer.Factories, LogViewer.Manager, LogViewer.Settings, LogViewer.ComPort.Settings, LogViewer.Dashboard.View; type TfrmMain = class(TForm) {$REGION 'designer controls'} aclMain : TActionList; actCenterToScreen : TAction; actShowVersion : TAction; ctMain : TChromeTabs; imlMain : TImageList; pnlMainClient : TPanel; pnlStatusBar : TPanel; pnlTop : TPanel; tskbrMain : TTaskbar; tmrPoll : TTimer; pnlSourceName : TPanel; pnlDelta : TPanel; pbrCPU : TKPercentProgressBar; pnlMessageCount : TPanel; pnlMemory : TPanel; {$ENDREGION} procedure actCenterToScreenExecute(Sender: TObject); procedure actShowVersionExecute(Sender: TObject); procedure ctMainButtonCloseTabClick( Sender : TObject; ATab : TChromeTab; var Close : Boolean ); procedure ctMainNeedDragImageControl( Sender : TObject; ATab : TChromeTab; var DragControl : TWinControl ); procedure ctMainActiveTabChanged( Sender : TObject; ATab : TChromeTab ); procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean); procedure tmrPollTimer(Sender: TObject); private FManager : ILogViewerManager; FSettings : TLogViewerSettings; FMainToolbar : TToolBar; FDashboard : TfrmDashboard; procedure SettingsChanged(Sender: TObject); procedure EventsAddLogViewer( Sender : TObject; ALogViewer : ILogViewer ); procedure EventsActiveViewChange( Sender : TObject; ALogViewer : ILogViewer ); procedure DrawPanelText( APanel : TPanel; const AText : string ); protected {$REGION 'property access methods'} function GetEvents: ILogViewerEvents; function GetActions: ILogViewerActions; function GetMenus: ILogViewerMenus; function GetManager: ILogViewerManager; {$ENDREGION} procedure CreateDashboardView; procedure UpdateStatusBar; procedure UpdateActions; override; procedure OptimizeWidth(APanel: TPanel); procedure OptimizeStatusBarPanelWidths; public procedure AfterConstruction; override; procedure BeforeDestruction; override; property Manager: ILogViewerManager read GetManager; property Actions: ILogViewerActions read GetActions; { Menu components to use in the user interface. } property Menus: ILogViewerMenus read GetMenus; { Set of events where the user interface can respond to. } property Events: ILogViewerEvents read GetEvents; end; var frmMain: TfrmMain; implementation uses Spring.Utils, DDuce.ObjectInspector.zObjectInspector, DDuce.Logger, DDuce.Utils.Winapi; {$R *.dfm} {$REGION 'non-interfaced routines'} { Extracts the ZMQ library form resources if it does not exist. } procedure EnsureZMQLibExists; const LIBZMQ = 'libzmq'; var LResStream : TResourceStream; LFileStream : TFileStream; LPath : string; begin LPath := Format('%s\%s.dll', [ExtractFileDir(ParamStr(0)), LIBZMQ]); if not FileExists(LPath) then begin LResStream := TResourceStream.Create(HInstance, LIBZMQ, RT_RCDATA); try LFileStream := TFileStream.Create(LPath, fmCreate); try LFileStream.CopyFrom(LResStream, 0); finally LFileStream.Free; end; finally LResStream.Free; end; end; end; {$ENDREGION} {$REGION 'construction and destruction'} procedure TfrmMain.AfterConstruction; var FVI : TFileVersionInfo; begin inherited AfterConstruction; FVI := TFileVersionInfo.GetVersionInfo(Application.ExeName); Caption := Format('%s %s', [FVI.ProductName, FVI.ProductVersion]); FSettings := TLogViewerFactories.CreateSettings; try FSettings.Load; except // ignore it end; FManager := TLogViewerFactories.CreateManager(Self, FSettings); Events.OnAddLogViewer.Add(EventsAddLogViewer); Events.OnActiveViewChange.Add(EventsActiveViewChange); FSettings.FormSettings.AssignTo(Self); FSettings.OnChanged.Add(SettingsChanged); FMainToolbar := TLogViewerFactories.CreateMainToolbar( FManager.AsComponent, pnlTop, Actions, Menus ); CreateDashboardView; ctMain.LookAndFeel.Tabs.NotActive.Style.StartColor := ColorToRGB(clBtnFace); ctMain.LookAndFeel.Tabs.NotActive.Style.StopColor := ColorToRGB(clBtnFace); ctMain.LookAndFeel.Tabs.Active.Style.StartColor := ColorToRGB(clWindowFrame); ctMain.LookAndFeel.Tabs.Active.Style.StopColor := ColorToRGB(clWindowFrame); ctMain.LookAndFeel.Tabs.Hot.Style.StartColor := clSilver; ctMain.LookAndFeel.Tabs.Hot.Style.StopColor := clSilver; end; procedure TfrmMain.BeforeDestruction; var CR : IChannelReceiver; begin Logger.Track(Self, 'BeforeDestruction'); tmrPoll.Enabled := False; for CR in Manager.Receivers do CR.Enabled := False; FreeAndNil(FDashboard); FManager.Settings.FormSettings.Assign(Self); FManager.Settings.Save; FManager.Settings.OnChanged.Remove(SettingsChanged); FSettings.Free; FManager := nil; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'action handlers'} procedure TfrmMain.actCenterToScreenExecute(Sender: TObject); begin WindowState := wsMinimized; Top := 0; Left := 0; WindowState := wsMaximized; end; procedure TfrmMain.actShowVersionExecute(Sender: TObject); const LIBZMQ = 'libzmq'; var FVI : TFileVersionInfo; begin FVI := TFileVersionInfo.GetVersionInfo(Format('%s\%s.dll', [ExtractFileDir(ParamStr(0)), LIBZMQ])); ShowMessage(FVI.ToString); end; {$ENDREGION} {$REGION 'event handlers'} procedure TfrmMain.ctMainActiveTabChanged(Sender: TObject; ATab: TChromeTab); var MV : ILogViewer; begin Logger.Track(Self, 'ctMainActiveTabChanged'); if ATab.DisplayName = 'Dashboard' then begin FDashboard.Show; FDashboard.SetFocus; pnlSourceName.Caption := ''; pnlMessageCount.Caption := ''; pnlDelta.Caption := ''; Manager.ActiveView := nil; OptimizeStatusBarPanelWidths; end else if Assigned(ATab.Data) then begin MV := ILogViewer(ATab.Data); MV.Form.Show; MV.Form.SetFocus; Manager.ActiveView := MV; UpdateStatusBar; OptimizeStatusBarPanelWidths; end; end; procedure TfrmMain.ctMainButtonCloseTabClick(Sender: TObject; ATab: TChromeTab; var Close: Boolean); var V : ILogViewer; begin Close := ATab.DisplayName <> 'Dashboard'; if Close then begin V := ILogViewer(ATab.Data); Manager.DeleteView(V); end; end; procedure TfrmMain.ctMainNeedDragImageControl(Sender: TObject; ATab: TChromeTab; var DragControl: TWinControl); begin DragControl := pnlMainClient; end; procedure TfrmMain.DrawPanelText(APanel: TPanel; const AText: string); var LCanvas : Shared<TControlCanvas>; LBitmap : Shared<TBitmap>; LWidth : Integer; X : Integer; begin LBitmap := TBitmap.Create; LBitmap.Value.SetSize(APanel.Width, APanel.Height); LBitmap.Value.Canvas.Brush.Color := APanel.Color; LBitmap.Value.Canvas.FillRect(LBitmap.Value.Canvas.ClipRect); LWidth := DrawFormattedText( LBitmap.Value.Canvas.ClipRect, LBitmap.Value.Canvas, AText ); X := (APanel.Width - LWidth) div 2; LCanvas := TControlCanvas.Create; LCanvas.Value.Control := APanel; LCanvas.Value.Draw(X, 0, LBitmap); end; procedure TfrmMain.EventsActiveViewChange(Sender: TObject; ALogViewer: ILogViewer); var CT : TChromeTab; I : Integer; begin Logger.Track(Self, 'EventsActiveViewChange'); if Assigned(ALogViewer) then begin for I := 0 to ctMain.Tabs.Count - 1 do begin CT := ctMain.Tabs[I]; if CT.Data = Pointer(ALogViewer) then ctMain.ActiveTab := CT; end; ALogViewer.Form.Show; end else begin FDashboard.Show; end; end; procedure TfrmMain.EventsAddLogViewer(Sender: TObject; ALogViewer: ILogViewer); var S : string; begin ALogViewer.Subscriber.Enabled := True; ALogViewer.Form.Parent := pnlMainClient; S := ExtractFileName(ALogViewer.Subscriber.SourceName); ctMain.Tabs.Add; ctMain.ActiveTab.Data := Pointer(ALogViewer); ctMain.ActiveTab.Caption := Format('%s (%s, %d) . ', [ ALogViewer.Subscriber.Receiver.ToString, S, ALogViewer.Subscriber.SourceId ]); ALogViewer.Form.Show; UpdateStatusBar; OptimizeStatusBarPanelWidths; end; procedure TfrmMain.SettingsChanged(Sender: TObject); begin FormStyle := FSettings.FormSettings.FormStyle; WindowState := FSettings.FormSettings.WindowState; end; procedure TfrmMain.tmrPollTimer(Sender: TObject); begin pbrCPU.Position := Round(GetProcessCpuUsagePct(GetCurrentProcessId)); pnlMemory.Caption := FormatBytes(MemoryUsed); end; procedure TfrmMain.FormShortCut(var Msg: TWMKey; var Handled: Boolean); begin Handled := Manager.Actions.ActionList.IsShortCut(Msg); end; {$ENDREGION} {$REGION 'property access methods'} function TfrmMain.GetActions: ILogViewerActions; begin Result := Manager.Actions; end; function TfrmMain.GetEvents: ILogViewerEvents; begin Result := FManager as ILogViewerEvents; end; function TfrmMain.GetManager: ILogViewerManager; begin Result := FManager as ILogViewerManager; end; function TfrmMain.GetMenus: ILogViewerMenus; begin Result := Manager.Menus; end; {$ENDREGION} {$REGION 'protected methods'} procedure TfrmMain.CreateDashboardView; begin FDashboard := TfrmDashboard.Create(Self, Manager); FDashboard.Parent := pnlMainClient; FDashboard.BorderStyle := bsNone; FDashboard.Align := alClient; ctMain.Tabs.Add; ctMain.ActiveTab.Data := Pointer(FDashboard); ctMain.ActiveTab.Caption := 'Dashboard'; ctMain.ActiveTab.DisplayName := 'Dashboard'; ctMain.ActiveTab.Pinned := True; FDashboard.Show; end; procedure TfrmMain.UpdateActions; begin UpdateStatusBar; inherited UpdateActions; end; procedure TfrmMain.OptimizeStatusBarPanelWidths; begin OptimizeWidth(pnlSourceName); end; procedure TfrmMain.OptimizeWidth(APanel: TPanel); var S : string; begin S := APanel.Caption; if Trim(S) <> '' then begin APanel.Width := GetTextWidth(APanel.Caption, APanel.Font) + 10; APanel.BevelKind := bkFlat; APanel.AlignWithMargins := True; end else begin APanel.BevelKind := bkNone; APanel.Width := 0; APanel.AlignWithMargins := False; end; end; procedure TfrmMain.UpdateStatusBar; var N : Integer; S : string; begin if Assigned(ctMain.ActiveTab) and Assigned(Manager) and Assigned(Manager.ActiveView) and Assigned(Manager.ActiveView.Subscriber) and (ctMain.ActiveTab.Caption <> 'Dashboard') then begin pnlSourceName.Caption := Format('%s (%d)', [ Manager.ActiveView.Subscriber.SourceName, Manager.ActiveView.Subscriber.SourceId ]); N := Manager.ActiveView.MilliSecondsBetweenSelection; if N <> -1 then begin pnlDelta.Caption := Format('Delta: %dms', [N]); pnlDelta.Color := clWhite; pnlDelta.BevelKind := bkFlat; end else begin pnlDelta.Caption := ''; pnlDelta.Color := clBtnFace; pnlDelta.BevelKind := bkNone; end; S := Format( '<b>%d</b></x>', [Manager.ActiveView.Subscriber.MessageCount] ); DrawPanelText(pnlMessageCount, S); end else begin pnlSourceName.Caption := ''; pnlMessageCount.Caption := ''; pnlDelta.Caption := ''; OptimizeStatusBarPanelWidths; end; end; {$ENDREGION} initialization EnsureZMQLibExists; end.
unit TemplateReplace; interface uses Classes, StrUtils; //function DoTemplateReplace(const Template: String; // DataSetRecord: TDataSet): String; implementation {$ifdef jshdglksghskdhg} function DoTemplateReplace(const Template: String; DataSetRecord: TDataSet): String; var sl: TStringList; str: String; i: Integer; begin //Delphi 7 note //Make sure your uses clause includes Classes and StrUtils //Delphi 8 note //Make sure your uses clause includes Borland.Vcl.Classes //and Borland.Vcl.StrUtils sl := TStringList.Create; try sl.Text := Template; //remove all comment lines i := 0; while i < sl.Count do begin if UpperCase(Copy(sl.Strings[i],1,3)) = 'REM' then begin sl.Delete(i); continue; end; //This line is executed if a comment is NOT removed inc(i); end; str := sl.Text; finally sl.Free; end; //we now have the template in a string. //Use StringReplace to replace parts of the template //with data from our database //begin by iterating through the AttendeesDataSource.DataSet Fields //Replace {fieldname} tags in str with field contents for i := 0 to Pred(DataSetRecord.Fields.Count) do str := StringReplace(str, '{'+DataSetRecord.Fields[i].FieldName+'}', DataSetRecord.Fields[i].AsString, [rfReplaceAll,rfIgnoreCase]); //Check for today's date tag {TODAY} if Pos('{TODAY}', UpperCase(str)) > 0 then begin str := StringReplace(str, '{today}', FormatDateTime('mmmm, dd, yyyy',Date),[rfReplaceAll, rfIgnoreCase]); end; //Check for current time tag {TIME} if Pos('{TIME}', UpperCase(str)) > 0 then begin str := StringReplace(str, '{time}', FormatDateTime('tt',Time),[rfReplaceAll, rfIgnoreCase]); end; //You can create any additional //custom tags using this same technique Result := str; end; {$endif} end.
unit Skill; interface uses gm_engine, IniFiles; const SkillCount = 12; // Количество навыков. SkillMax = 5; // Максимальный уровень навыка. SkillIconSize = 64; // Размер иконки навыка. type TBaseSkill = class(TObject) private FSkill: array [0..SkillCount] of Byte; public constructor Create; destructor Destroy; override; procedure Clear; function Count: Byte; function Value(I: Byte): Byte; procedure SetValue(I, V: Byte); end; TIniSkill = class(TObject) private FIni: TIniFile; public constructor Create(const FileName: string); destructor Destroy; override; function ReadStr(SkillID: Byte; Ident, Default: string): string; function ReadInt(SkillID: Byte; Ident: string; Default: Integer): Integer; end; TSimpleSkill = class(TBaseSkill) private FIni: TIniSkill; public constructor Create(); overload; destructor Destroy; override; function Inc(I: Byte): Boolean; function Dec(I: Byte): Boolean; function Name(I: Byte): string; function Hint(I: Byte): string; function Pos(I: Byte): TPoint; function IsOpen(I: Byte): Boolean; function IsNeed(I: Byte): Boolean; function IsActive(I: Byte): Boolean; function Script(I: Byte): string; function NeedA(I: Byte): ShortInt; function NeedB(I: Byte): ShortInt; function NeedLevel(I: Byte): Byte; function Cooldown(I: Byte): Word; function ActiveCount: Byte; end; TSkill = class(TSimpleSkill) private // Image: TImage; IconSize: Integer; // SFrame: array [0..1] of TBitmap; public TreeLeft: Integer; TreeTop: Integer; IconLeft: Integer; IconTop: Integer; // SkillIcons: TImages; // DSkillIcons: TImages; constructor Create(); overload; destructor Destroy; override; procedure RenderAsLine; procedure RenderAsTree; // function Keys(var Key: Word): Boolean; function GetIconPos(I: Byte): TPoint; end; implementation uses SysUtils, gm_creature; const Margin = 5; SH = 'SkillID%d'; { TBaseSkill } procedure TBaseSkill.Clear; var I: Byte; begin for I := 0 to High(FSkill) do FSkill[I] := 0; end; function TBaseSkill.Count: Byte; begin Result := SkillCount; end; constructor TBaseSkill.Create; begin Clear; end; destructor TBaseSkill.Destroy; begin inherited; end; procedure TBaseSkill.SetValue(I, V: Byte); begin FSkill[I] := V; end; function TBaseSkill.Value(I: Byte): Byte; begin Result := FSkill[I]; end; { TIniSkill } constructor TIniSkill.Create(const FileName: string); begin FIni := TIniFile.Create(FileName); end; destructor TIniSkill.Destroy; begin FIni.Free; inherited; end; function TIniSkill.ReadInt(SkillID: Byte; Ident: string; Default: Integer): Integer; begin Result := FIni.ReadInteger(IntToStr(SkillID), Ident, Default); end; function TIniSkill.ReadStr(SkillID: Byte; Ident, Default: string): string; begin Result := FIni.ReadString(IntToStr(SkillID), Ident, Default); end; {TSimpleSkill} constructor TSimpleSkill.Create(); begin inherited Create; //FIni := TIniSkill.Create('Data\' + VM.GetStr('Hero.ClassID') + '.ini'); end; destructor TSimpleSkill.Destroy; begin FIni.Free; inherited; end; function TSimpleSkill.Name(I: Byte): string; begin Result := FIni.ReadStr(I, 'Name', ''); end; function TSimpleSkill.Hint(I: Byte): string; begin Result := FIni.ReadStr(I, 'Hint', ''); end; function TSimpleSkill.Script(I: Byte): string; begin Result := FIni.ReadStr(I, 'Script', ''); end; function TSimpleSkill.Pos(I: Byte): TPoint; begin Result.X := FIni.ReadInt(I, 'X', -1); Result.Y := FIni.ReadInt(I, 'Y', -1); end; function TSimpleSkill.NeedA(I: Byte): ShortInt; begin Result := FIni.ReadInt(I, 'NeedA', -1); end; function TSimpleSkill.NeedB(I: Byte): ShortInt; begin Result := FIni.ReadInt(I, 'NeedB', -1); end; function TSimpleSkill.NeedLevel(I: Byte): Byte; var Y: ShortInt; begin Y := Pos(I).Y; if (Y < 0) then Y := 0; Result := Y * 5; end; function TSimpleSkill.Cooldown(I: Byte): Word; begin Result := FIni.ReadInt(I, 'Cooldown', 1); end; function TSimpleSkill.IsOpen(I: Byte): Boolean; begin Result := ((NeedA(I) = -1) and (NeedB(I) = -1)) or ((NeedA(I) > -1) and (NeedB(I) = -1) and (Value(NeedA(I)) > 0)) or ((NeedA(I) = -1) and (Value(NeedB(I)) > 0)) or ((NeedA(I) > -1) and (NeedB(I) > -1) and (Value(NeedA(I)) > 0) and (Value(NeedB(I)) > 0)); Result := Result and (PC.Level >= NeedLevel(I)); end; function TSimpleSkill.IsActive(I: Byte): Boolean; begin Result := (FIni.ReadInt(I, 'Active', 0) = 1); end; function TSimpleSkill.IsNeed(I: Byte): Boolean; begin Result := (NeedA(I) >= 0) or (NeedB(I) >= 0); end; function TSimpleSkill.Dec(I: Byte): Boolean; begin Result := False; if IsOpen(I) and (FSkill[I] > 0) then begin FSkill[I] := FSkill[I] - 1; Result := True; end; end; function TSimpleSkill.Inc(I: Byte): Boolean; begin Result := False; if IsOpen(I) and (FSkill[I] < SkillMax) then begin FSkill[I] := FSkill[I] + 1; Result := True; end; end; function TSimpleSkill.ActiveCount: Byte; var I: Byte; begin Result := 0; for I := 0 to Self.Count - 1 do if Self.IsActive(I) then Result := Result + 1; end; { TSkill } constructor TSkill.Create; var I: Integer; S: string; begin inherited Create; IconTop := 38; IconLeft := 45; TreeTop := 10; TreeLeft := 88; { // fix for old saves S := VM.GetStr('Hero.ClassID'); if S = '' then S := 'Warrior'; S := Path + 'Data\Images\Classes\' + S + '.png'; Image := TImage.Create; Image.Split(S, SkillIcons, SkillIconSize, False); Image.Split(S, DSkillIcons, SkillIconSize, False); for I := 0 to SkillCount - 1 do Image.MixColors(DSkillIcons[I], clGray); IconSize := SkillIcons[0].Width; for I := 0 to 1 do begin SFrame[I] := TBitmap.Create; SFrame[I].Transparent := True; end; Image.Load(Path + 'Data\Images\GUI\SFrame.png', SFrame[0]); SFrame[1].Assign(SFrame[0]); Image.MixColors(SFrame[1], clGray); for I := 0 to 1 do SFrame[I].TransparentColor := SFrame[I].Canvas.Pixels[10, 10]; } end; destructor TSkill.Destroy; var I: Integer; begin { Image.Free; for I := 0 to 1 do FreeAndNil(SFrame[I]); for I := 0 to SkillCount - 1 do begin FreeAndNil(SkillIcons[I]); FreeAndNil(DSkillIcons[I]); end; } inherited; end; function TSkill.GetIconPos(I: Byte): TPoint; begin Result.X := (Pos(I).X * 80) + TreeLeft; Result.Y := (Pos(I).Y * 80) + TreeTop; end; {function TSkill.Keys(var Key: Word): Boolean; var K, I, H: Integer; P: string; begin Result := False; K := Key - 111; if (K < 1) or (K > ActiveCount) then Exit; H := 0; for I := 0 to SkillCount - 1 do if IsActive(I) then begin System.Inc(H); P := Self.Script(I); if (Value(I) > 0) and (H = K) and (P <> '') and not TV.IsVar(Format(SH, [I])) then begin uScript.Run(P); TV.Add(Format(SH, [I]), Self.Cooldown(I)); Result := True; Exit; end else Continue; end; end; } procedure TSkill.RenderAsLine; var I, P, H, L, V, Z: Integer; S, F: string; R: TRect; begin { ACanvas.Brush.Style := bsClear; ACanvas.Font.Style := [fsBold]; P := 0; H := 0; for I := 0 to SkillCount - 1 do if Self.IsActive(I) then begin System.Inc(H); if (Self.Value(I) > 0) then begin L := P * (IconSize + Margin) + Margin; F := 'F' + IntToStr(H); S := IntToStr(TV.Value(Format(SH, [I]))); if (S = '0') then ACanvas.Draw(L, Margin, SkillIcons[I]) else begin Z := IconSize div Self.Cooldown(I); V := TV.Value(Format(SH, [I])); V := Self.Cooldown(I) - V; R := Rect(L, Margin, L + IconSize, V * Z + Margin); ACanvas.Draw(L, Margin, DSkillIcons[I]); ACanvas.CopyRect(R, SkillIcons[I].Canvas, Rect(0, 0, IconSize, V * Z)); end; if TV.IsVar(Format(SH, [I])) then ACanvas.Font.Color := clWhite else ACanvas.Font.Color := clYellow; ACanvas.TextOut(L + ((IconSize div 2) - (ACanvas.TextWidth(F) div 2)), Margin, F); ACanvas.Font.Color := clYellow; if (S <> '0') then ACanvas.TextOut(L + ((IconSize div 2) - (ACanvas.TextWidth(S) div 2)), (IconSize + Margin) - ACanvas.TextHeight(S), S); System.Inc(P); end; end; } end; procedure TSkill.RenderAsTree; var I, X, Y: Integer; { procedure RenderLines; var I: Integer; procedure Line(C: Integer); begin if (C >= 0) then begin ACanvas.MoveTo(GetIconPos(I).X + IconLeft - 12, GetIconPos(I).Y + IconTop - 8); ACanvas.LineTo(GetIconPos(C).X + IconLeft - 12, GetIconPos(C).Y + IconTop - 8); end; end; begin ACanvas.Pen.Width := 10; ACanvas.Pen.Color := $00444444; for I := 0 to SkillCount - 1 do begin Line(NeedA(I)); Line(NeedB(I)); end; end; } begin { RenderLines; for I := 0 to SkillCount - 1 do begin X := GetIconPos(I).X; Y := GetIconPos(I).Y; if IsOpen(I) then begin ACanvas.Draw(X, Y, SkillIcons[I]); ACanvas.Draw(X, Y, SFrame[0]); ACanvas.TextOut(X + 50, Y + 42, IntToStr(Self.Value(I))); end else begin ACanvas.Draw(X, Y, DSkillIcons[I]); ACanvas.Draw(X, Y, SFrame[1]); end; end; } end; end.
unit myevent; interface uses syncobjs; type TMyEventResult = (merSignaled, merTimeOut, merDestroyed, merError); TMyEvent = class private FEvent: TEvent; Destroying: TEvent; public constructor Create(ManualReset, InitialState: Boolean); destructor Destroy; override; function WaitFor(timeout: Cardinal): TMyEventResult; procedure SetEvent; procedure ResetEvent; end; implementation constructor TMyEvent.Create(ManualReset, InitialState: Boolean); begin inherited Create; FEvent := TEvent.Create(nil, ManualReset, InitialState, ''); Destroying := TEvent.Create(nil, True, False, ''); end; destructor TMyEvent.Destroy; var c: Integer; begin Destroying.SetEvent; c := 0; repeat FEvent.SetEvent; //Melde solange, bis die Meldung von keinem anderen Thread mehr abgefangen //wird. if (FEvent.WaitFor(0) = wrSignaled) then inc(c); until (c > 10); FEvent.Free; Destroying.Free; inherited; end; procedure TMyEvent.ResetEvent; begin FEvent.ResetEvent; end; procedure TMyEvent.SetEvent; begin FEvent.SetEvent; end; function TMyEvent.WaitFor(timeout: Cardinal): TMyEventResult; begin if (Destroying.WaitFor(0) = wrSignaled) then begin Result := merDestroyed; end else begin case FEvent.WaitFor(timeout) of wrSignaled: begin if (Destroying.WaitFor(0) = wrSignaled) then Result := merDestroyed else Result := merSignaled; end; wrTimeout: Result := merTimeOut; else Result := merError; end; end; end; end.
unit csClientMessageRequest; interface uses Classes, CsDataPipe, csRequestTask, CsNotification, DT_types; type TddClientMessage = class(TddRequestTask) private f_Data: Integer; f_NotifyType: TCsNotificationType; f_Text: string; protected procedure Cleanup; override; procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override; public constructor Create(aOwner: TObject; aUserID: TUserID); override; procedure FromPipe(aDataPipe: TcsDataPipe); procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override; property Data: Integer read f_Data write f_Data; property NotifyType: TCsNotificationType read f_NotifyType write f_NotifyType; property Text: string read f_Text write f_Text; end; implementation constructor TddClientMessage.Create(aOwner: TObject; aUserID: TUserID); begin inherited; end; procedure TddClientMessage.Cleanup; begin inherited; end; procedure TddClientMessage.FromPipe(aDataPipe: TcsDataPipe); begin with aDataPipe do begin f_NotifyType := TCsNotificationType(ReadInteger); f_Data := ReadInteger; f_Text := ReadStr; end; end; procedure TddClientMessage.LoadFrom(aStream: TStream; aIsPipe: Boolean); var l_N: Integer; begin inherited; with aStream do begin Read(l_N, SizeOf(Integer)); f_NotifyType := TCsNotificationType(l_N); Read(f_Data, SizeOf(f_Data)); ReadString(aStream, f_Text); end; // with aStream end; procedure TddClientMessage.SaveTo(aStream: TStream; aIsPipe: Boolean); var l_N: Integer; begin inherited; with aStream do begin l_N := Ord(f_NotifyType); Write(l_N, SizeOf(Integer)); Write(f_Data, SizeOf(f_Data)); WriteString(aStream, f_Text); end; // with aStream end; end.
unit ServerMethodsUnit1; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth; type {$METHODINFO ON} TServerMethods1 = class(TComponent) private { Déclarations privées } public { Déclarations publiques } function EchoString(Value: string): string; function ReverseString(Value: string): string; end; {$METHODINFO OFF} implementation uses System.StrUtils; function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
unit daTabledQuery; // Модуль: "w:\common\components\rtl\Garant\DA\daTabledQuery.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaTabledQuery" MUID: (5600FA2301B9) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , daQuery , daInterfaces , daSelectFieldList , daSortFieldList ; type TdaTabledQuery = class(TdaQuery, IdaTabledQuery) private f_SelectFields: TdaSelectFieldList; f_WhereCondition: IdaCondition; f_FromClause: IdaFromClause; f_OrderBy: TdaSortFieldList; f_Factory: IdaTableQueryFactory; private function BuildFromClause(const aHelper: IdaParamListHelper): AnsiString; function BuildSelectClause: AnsiString; function BuildWhereClause(const aHelper: IdaParamListHelper): AnsiString; function BuildOrderByClause: AnsiString; protected procedure pm_SetWhereCondition(const aValue: IdaCondition); virtual; procedure PrepareTable; virtual; abstract; procedure UnPrepareTable; virtual; abstract; procedure AddSelectField(const aField: IdaSelectField); function MakeResultSet(Unidirectional: Boolean): IdaResultSet; override; procedure PrepareQuery; override; procedure UnprepareQuery; override; function Get_WhereCondition: IdaCondition; procedure Set_WhereCondition(const aValue: IdaCondition); function DoBuildSQLValue(const aHelper: IdaParamListHelper): AnsiString; override; procedure AddOrderBy(const aSortField: IdaSortField); function SelectFieldByName(const anAlias: AnsiString): IdaSelectField; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(const aFactory: IdaTableQueryFactory; const aDataConverter: IdaDataConverter; const aFromClause: IdaFromClause); reintroduce; protected property SelectFields: TdaSelectFieldList read f_SelectFields; property WhereCondition: IdaCondition read f_WhereCondition write pm_SetWhereCondition; property FromClause: IdaFromClause read f_FromClause; property OrderBy: TdaSortFieldList read f_OrderBy; property Factory: IdaTableQueryFactory read f_Factory; end;//TdaTabledQuery implementation uses l3ImplUses , SysUtils , daTypes //#UC START# *5600FA2301B9impl_uses* //#UC END# *5600FA2301B9impl_uses* ; procedure TdaTabledQuery.pm_SetWhereCondition(const aValue: IdaCondition); //#UC START# *5600FAC103DE_5600FA2301B9set_var* //#UC END# *5600FAC103DE_5600FA2301B9set_var* begin //#UC START# *5600FAC103DE_5600FA2301B9set_impl* f_WhereCondition := aValue; UnPrepare; //#UC END# *5600FAC103DE_5600FA2301B9set_impl* end;//TdaTabledQuery.pm_SetWhereCondition constructor TdaTabledQuery.Create(const aFactory: IdaTableQueryFactory; const aDataConverter: IdaDataConverter; const aFromClause: IdaFromClause); //#UC START# *5600FB3903DE_5600FA2301B9_var* //#UC END# *5600FB3903DE_5600FA2301B9_var* begin //#UC START# *5600FB3903DE_5600FA2301B9_impl* inherited Create(aDataConverter); f_Factory := aFactory; f_FromClause := aFromClause; UnPrepare; f_SelectFields := TdaSelectFieldList.Make; f_OrderBy := TdaSortFieldList.Create; //#UC END# *5600FB3903DE_5600FA2301B9_impl* end;//TdaTabledQuery.Create function TdaTabledQuery.BuildFromClause(const aHelper: IdaParamListHelper): AnsiString; //#UC START# *56050F450363_5600FA2301B9_var* //#UC END# *56050F450363_5600FA2301B9_var* begin //#UC START# *56050F450363_5600FA2301B9_impl* Result := ' from '#13#10' ' + FromClause.BuildSQLValue(aHelper); //#UC END# *56050F450363_5600FA2301B9_impl* end;//TdaTabledQuery.BuildFromClause function TdaTabledQuery.BuildSelectClause: AnsiString; //#UC START# *56050F3E0081_5600FA2301B9_var* var l_IDX: Integer; l_Count: Integer; //#UC END# *56050F3E0081_5600FA2301B9_var* begin //#UC START# *56050F3E0081_5600FA2301B9_impl* Assert(SelectFields.Count > 0); Result := 'select '; for l_IDX := 0 to SelectFields.Count - 1 do begin if l_IDX > 0 then Result := Result + ', '#13#10+' '; Result := Result + SelectFields[l_IDX].BuildSQLValue; end; //#UC END# *56050F3E0081_5600FA2301B9_impl* end;//TdaTabledQuery.BuildSelectClause function TdaTabledQuery.BuildWhereClause(const aHelper: IdaParamListHelper): AnsiString; //#UC START# *56050F510228_5600FA2301B9_var* //#UC END# *56050F510228_5600FA2301B9_var* begin //#UC START# *56050F510228_5600FA2301B9_impl* if WhereCondition <> nil then Result := #13#10' where ' + WhereCondition.BuildSQLValue(aHelper) else Result := ''; //#UC END# *56050F510228_5600FA2301B9_impl* end;//TdaTabledQuery.BuildWhereClause function TdaTabledQuery.BuildOrderByClause: AnsiString; //#UC START# *5680E19E003D_5600FA2301B9_var* var l_IDX: Integer; const cMap: array [TdaSortOrder] of AnsiString = ('ASC', 'DESC'); //#UC END# *5680E19E003D_5600FA2301B9_var* begin //#UC START# *5680E19E003D_5600FA2301B9_impl* if OrderBy.Count > 0 then begin Result := #13#10' order by '; for l_IDX := 0 to OrderBy.Count - 1 do begin if l_IDX <> 0 then Result := Result + ', '; Result := Format('%s %s %s', [Result, IntToStr(SelectFields.IndexOf(OrderBy[l_IDX].SelectField) + 1), cMap[OrderBy[l_IDX].SortOrder]]); end; end else Result := ''; //#UC END# *5680E19E003D_5600FA2301B9_impl* end;//TdaTabledQuery.BuildOrderByClause procedure TdaTabledQuery.AddSelectField(const aField: IdaSelectField); //#UC START# *5551DC42038C_5600FA2301B9_var* //#UC END# *5551DC42038C_5600FA2301B9_var* begin //#UC START# *5551DC42038C_5600FA2301B9_impl* f_SelectFields.Add(aField); UnPrepare; //#UC END# *5551DC42038C_5600FA2301B9_impl* end;//TdaTabledQuery.AddSelectField function TdaTabledQuery.MakeResultSet(Unidirectional: Boolean): IdaResultSet; //#UC START# *56010A7801F2_5600FA2301B9_var* //#UC END# *56010A7801F2_5600FA2301B9_var* begin //#UC START# *56010A7801F2_5600FA2301B9_impl* Result := nil; //#UC END# *56010A7801F2_5600FA2301B9_impl* end;//TdaTabledQuery.MakeResultSet procedure TdaTabledQuery.PrepareQuery; //#UC START# *56010AB70258_5600FA2301B9_var* var l_Field: IdaFieldFromTable; l_ParamDescription: IdaParamDescription; l_IDX: Integer; l_Dummy: Integer; function lp_ProcessCondition(const anItem: IdaCondition): Boolean; var l_Field: IdaFieldFromTable; l_ParamDescription: IdaParamDescription; begin Result := True; if Supports(anItem, IdaFieldFromTable, l_Field) then Assert(FromClause.HasTable(l_Field.Field.Table)); if Supports(anItem, IdaParamDescription, l_ParamDescription) then AddParam(l_ParamDescription); end; function lp_ProcessRelation(const anItem: IdaCondition): Boolean; var l_ParamDescription: IdaParamDescription; l_Join: IdaJoinCondition; procedure lp_CheckJoin(const aPart: IdaFieldFromTable); begin Assert(FromClause.FindTable(aPart.TableAlias).Table = aPart.Field.Table); end; begin Result := True; lp_ProcessCondition(anItem); if Supports(anItem, IdaJoinCondition, l_Join) then begin lp_CheckJoin(l_Join.Left); lp_CheckJoin(l_Join.Right); end; end; function CheckTable(const anItem: IdaTableDescription): Boolean; begin Result := True; Assert(FromClause.HasTable(anItem)); end; //#UC END# *56010AB70258_5600FA2301B9_var* begin //#UC START# *56010AB70258_5600FA2301B9_impl* Assert(f_SelectFields.Count > 0); for l_IDX := 0 to f_SelectFields.Count - 1 do f_SelectFields[l_IDX].IterateTables(L2daSelectFieldIteratorIterateTablesAction(@CheckTable)); Assert(Assigned(FromClause)); Assert(FromClause.IsRelationsConditionsValid); FromClause.IterateRelationConditionsF(L2daFromClauseIteratorIterateRelationConditionsFAction(@lp_ProcessRelation)); if Assigned(f_WhereCondition) then f_WhereCondition.IterateF(L2DaConditionIteratorIterateAction(@lp_ProcessCondition)); for l_IDX := 0 to f_OrderBy.Count - 1 do Assert(f_SelectFields.IndexOf(f_OrderBy[l_IDX].SelectField) <> -1); PrepareTable; //#UC END# *56010AB70258_5600FA2301B9_impl* end;//TdaTabledQuery.PrepareQuery procedure TdaTabledQuery.UnprepareQuery; //#UC START# *56010ACB00F0_5600FA2301B9_var* //#UC END# *56010ACB00F0_5600FA2301B9_var* begin //#UC START# *56010ACB00F0_5600FA2301B9_impl* UnprepareTable; //#UC END# *56010ACB00F0_5600FA2301B9_impl* end;//TdaTabledQuery.UnprepareQuery function TdaTabledQuery.Get_WhereCondition: IdaCondition; //#UC START# *563B18FB0212_5600FA2301B9get_var* //#UC END# *563B18FB0212_5600FA2301B9get_var* begin //#UC START# *563B18FB0212_5600FA2301B9get_impl* Result := f_WhereCondition; //#UC END# *563B18FB0212_5600FA2301B9get_impl* end;//TdaTabledQuery.Get_WhereCondition procedure TdaTabledQuery.Set_WhereCondition(const aValue: IdaCondition); //#UC START# *563B18FB0212_5600FA2301B9set_var* //#UC END# *563B18FB0212_5600FA2301B9set_var* begin //#UC START# *563B18FB0212_5600FA2301B9set_impl* WhereCondition := aValue; //#UC END# *563B18FB0212_5600FA2301B9set_impl* end;//TdaTabledQuery.Set_WhereCondition function TdaTabledQuery.DoBuildSQLValue(const aHelper: IdaParamListHelper): AnsiString; //#UC START# *566A850001E5_5600FA2301B9_var* //#UC END# *566A850001E5_5600FA2301B9_var* begin //#UC START# *566A850001E5_5600FA2301B9_impl* Result := Format('%s'#13#10+' %s%s%s', [BuildSelectClause, BuildFromClause(aHelper), BuildWhereClause(aHelper), BuildOrderByClause]); //#UC END# *566A850001E5_5600FA2301B9_impl* end;//TdaTabledQuery.DoBuildSQLValue procedure TdaTabledQuery.AddOrderBy(const aSortField: IdaSortField); //#UC START# *567D12D00384_5600FA2301B9_var* //#UC END# *567D12D00384_5600FA2301B9_var* begin //#UC START# *567D12D00384_5600FA2301B9_impl* f_OrderBy.Add(aSortField); //#UC END# *567D12D00384_5600FA2301B9_impl* end;//TdaTabledQuery.AddOrderBy function TdaTabledQuery.SelectFieldByName(const anAlias: AnsiString): IdaSelectField; //#UC START# *56F3D89F01C8_5600FA2301B9_var* var l_IDX: Integer; //#UC END# *56F3D89F01C8_5600FA2301B9_var* begin //#UC START# *56F3D89F01C8_5600FA2301B9_impl* if f_SelectFields.FindData(anAlias, l_IDX) then Result := f_SelectFields[l_IDX] else Result := nil; //#UC END# *56F3D89F01C8_5600FA2301B9_impl* end;//TdaTabledQuery.SelectFieldByName procedure TdaTabledQuery.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5600FA2301B9_var* //#UC END# *479731C50290_5600FA2301B9_var* begin //#UC START# *479731C50290_5600FA2301B9_impl* f_FromClause := nil; f_WhereCondition := nil; FreeAndNil(f_SelectFields); FreeAndNil(f_OrderBy); f_Factory := nil; inherited; //#UC END# *479731C50290_5600FA2301B9_impl* end;//TdaTabledQuery.Cleanup procedure TdaTabledQuery.ClearFields; begin WhereCondition := nil; f_FromClause := nil; f_Factory := nil; inherited; end;//TdaTabledQuery.ClearFields end.
unit Unit_data; interface uses SysUtils; const __multipl=1; __min=50*__multipl; __max=2*__min; Max_integer=1000000000; type trextract=record one, two : word; end;{trextract} telementtype=record mask : word; _topl : array[1..16] of integer; _nagr : array[1..16] of integer; sum_topl : integer; end;{telementtype} trmassivtype=record _data : array [__min*0..__max*16] of telementtype; end;{trmassivtype} tresultinfo=record iterations : double; __time : TdateTime; end;{tresultinfo} Procedure GLobal_optimization; function Num_to_Un(a:word):word; procedure perebor; var result_massiv : trmassivtype; general_mask : word; resinfo : tresultinfo; implementation var oper_mask : trextract; dec_massiv : array[1..256] of trmassivtype; iters : double; Function __topl(vid : integer; x : real):integer; begin Result:=0; x:=x/__multipl; case vid of 1 : Result:=Round(-1.3593E-02*x*sqr(x) + 3.5524E+00*x*x - 1.5115E+02*x + 8.6706E+03); 2 : Result:=Round(-1.8354E-03*x*sqr(x) + 6.9561E-01*x*x + 8.1260E+01*x + 2.4491E+03); 3 : Result:=Round(8.0685E-04*x*sqr(x) + 2.0774E-01*x*x + 1.0639E+02*x + 2.1748E+03); 4 : Result:=Round(2.8613E-03*x*sqr(x) - 1.7243E-01*x*x + 1.2553E+02*x + 2.0034E+03); end;{case} end;{__topl} function un_to_Num(a:word):word; var i : integer; begin Result:=1; for i:=1 to 16 do begin if a mod 2>0 then exit; a:=a div 2; inc(Result); end; end;{un_to_Num} function Num_to_Un(a:word):word; var i : integer; begin Result:=1; for i:=1 to a-1 do inc(Result, Result) end;{Num_to_Un} Function Extract_mask(a : word):trextract; begin Result.two:=Num_to_Un(un_to_num(a)); Result.one:=a - Result.two; end;{Extract_mask} Procedure Init_massiv; var i : integer; begin for i:=1 to 256 do if Extract_mask(i).one<>0 then fillchar(dec_massiv[i], sizeof(trmassivtype), #0); end;{Init_massiv} Procedure Init_massiv_1; var i, j : integer; begin for i:=1 to 256 do if Extract_mask(i).one<>0 then for j:=__min to __max*16 do dec_massiv[i]._data[j].sum_topl:=Max_Integer; fillchar(result_massiv, sizeof(trmassivtype), #0); for j:=__min to __max*16 do result_massiv._data[j].sum_topl:=Max_integer; end;{Init_massiv_1} Procedure Assign_massiv; var i, j, num_func : integer; _mask : word; begin Init_massiv; Init_massiv_1; for i:=1 to 8 do begin num_func:=(i+1) div 2; _mask:=Num_to_Un(i); fillchar(dec_massiv[_mask], sizeof(trmassivtype), #0); for j:= __min to __max do begin dec_massiv[_mask]._data[j].mask:=_mask; dec_massiv[_mask]._data[j]._topl[i]:=__topl(num_func,j); dec_massiv[_mask]._data[j]._nagr[i]:=j; dec_massiv[_mask]._data[j].sum_topl:=__topl(num_func,j); end;{for} end;{for} end;{Assign_massiv} Procedure element_optimization(one, two : word); var i, j, res_mask, num_two, max_i, max_j, oper_perem : integer; function calcul_max_limit(a:word):integer; var i : integer; begin Result:=__max*16; for i:=__min to __max*16 do begin if dec_massiv[a]._data[i].mask=0 then begin Result:=i-1; Exit; end;{if} end;{for} end;{calcul_max_limit} begin if one*two=0 then Exit; res_mask:=one+two; num_two:=un_to_Num(two); max_i:=calcul_max_limit(one); max_j:=calcul_max_limit(two); for i:=__min to max_i do if dec_massiv[one]._data[i].sum_topl<dec_massiv[res_mask]._data[i].sum_topl then dec_massiv[res_mask]._data[i]:=dec_massiv[one]._data[i]; for j:=__min to max_j do if dec_massiv[two]._data[j].sum_topl<dec_massiv[res_mask]._data[j].sum_topl then dec_massiv[res_mask]._data[j]:=dec_massiv[two]._data[j]; for i:=__min to max_i do for j:=__min to max_j do begin iters:=iters+1; oper_perem:=dec_massiv[one]._data[i].sum_topl+dec_massiv[two]._data[j].sum_topl; if oper_perem < dec_massiv[res_mask]._data[i+j].sum_topl then begin dec_massiv[res_mask]._data[i+j]:=dec_massiv[one]._data[i]; dec_massiv[res_mask]._data[i+j].mask:=dec_massiv[res_mask]._data[i+j].mask or two; dec_massiv[res_mask]._data[i+j]._topl[num_two]:=dec_massiv[two]._data[j].sum_topl; dec_massiv[res_mask]._data[i+j]._nagr[num_two]:=j; dec_massiv[res_mask]._data[i+j].sum_topl:=oper_perem; end;{if} end;{for if for if} end;{element_optimization} Procedure Gen_optimization; var i : integer; begin for i:=1 to 256 do if (not general_mask) and i = 0 then begin oper_mask:=Extract_mask(i); element_optimization(oper_mask.one, oper_mask.two); end;{for} end;{Gen_optimization} Procedure GLobal_optimization; var i, j : integer; beg_time : TdateTime; begin iters:=0; beg_time:=Now; Init_massiv_1; Gen_optimization; for j:=__min to __max*16 do for i:=1 to 256 do if (not general_mask) and i = 0 then if dec_massiv[i]._data[j].sum_topl<result_massiv._data[j].sum_topl then if dec_massiv[i]._data[j].sum_topl>0 then result_massiv._data[j]:=dec_massiv[i]._data[j]; resinfo.iterations:=iters; resinfo.__time:=Now-beg_time; end;{GLobal_optimization} procedure perebor; var i1, i2,i3,i4,i5,i6,i7,i8, k :integer; maxi1, maxi2,maxi3,maxi4,maxi5,maxi6,maxi7,maxi8 :integer; a, b : array [1..8] of integer; nakop_a, nakop_b, nakop_mask : integer; beg_time : Tdatetime; begin iters:=0; beg_time:=Now; Init_massiv_1; if general_mask and Num_to_un(1)=0 then maxi1:=__min-1 else maxi1:=__max; if general_mask and Num_to_un(2)=0 then maxi2:=__min-1 else maxi2:=__max; if general_mask and Num_to_un(3)=0 then maxi3:=__min-1 else maxi3:=__max; if general_mask and Num_to_un(4)=0 then maxi4:=__min-1 else maxi4:=__max; if general_mask and Num_to_un(5)=0 then maxi5:=__min-1 else maxi5:=__max; if general_mask and Num_to_un(6)=0 then maxi6:=__min-1 else maxi6:=__max; if general_mask and Num_to_un(7)=0 then maxi7:=__min-1 else maxi7:=__max; if general_mask and Num_to_un(8)=0 then maxi8:=__min-1 else maxi8:=__max; for i1:=__min-1 to maxi1 do for i2:=__min-1 to maxi2 do for i3:=__min-1 to maxi3 do for i4:=__min-1 to maxi4 do for i5:=__min-1 to maxi5 do for i6:=__min-1 to maxi6 do for i7:=__min-1 to maxi7 do for i8:=__min-1 to maxi8 do begin iters:=iters+1; for k:=1 to 8 do begin a[k]:=0; b[k]:=0; end;{for} nakop_a:=0; nakop_b:=0; nakop_mask:=0; if i1>=__min then if general_mask and Num_to_un(1)<>0 then begin a[1]:=dec_massiv[Num_to_un(1)]._data[i1]._nagr[1]; b[1]:=dec_massiv[Num_to_un(1)]._data[i1].sum_topl; nakop_a:=nakop_a+a[1]; nakop_b:=nakop_b+b[1]; nakop_mask:=nakop_mask or Num_to_un(1); end;{if i1} if i2>=__min then if general_mask and Num_to_un(2)<>0 then begin a[2]:=dec_massiv[Num_to_un(2)]._data[i2]._nagr[2]; b[2]:=dec_massiv[Num_to_un(2)]._data[i2].sum_topl; nakop_a:=nakop_a+a[2]; nakop_b:=nakop_b+b[2]; nakop_mask:=nakop_mask or Num_to_un(2); end;{if i2} if i3>=__min then if general_mask and Num_to_un(3)<>0 then begin a[3]:=dec_massiv[Num_to_un(3)]._data[i3]._nagr[3]; b[3]:=dec_massiv[Num_to_un(3)]._data[i3].sum_topl; nakop_a:=nakop_a+a[3]; nakop_b:=nakop_b+b[3]; nakop_mask:=nakop_mask or Num_to_un(3); end;{if i3} if i4>=__min then if general_mask and Num_to_un(4)<>0 then begin a[4]:=dec_massiv[Num_to_un(4)]._data[i4]._nagr[4]; b[4]:=dec_massiv[Num_to_un(4)]._data[i4].sum_topl; nakop_a:=nakop_a+a[4]; nakop_b:=nakop_b+b[4]; nakop_mask:=nakop_mask or Num_to_un(4); end;{if i4} if i5>=__min then if general_mask and Num_to_un(5)<>0 then begin a[5]:=dec_massiv[Num_to_un(5)]._data[i5]._nagr[5]; b[5]:=dec_massiv[Num_to_un(5)]._data[i5].sum_topl; nakop_a:=nakop_a+a[5]; nakop_b:=nakop_b+b[5]; nakop_mask:=nakop_mask or Num_to_un(5); end;{if i5} if i6>=__min then if general_mask and Num_to_un(6)<>0 then begin a[6]:=dec_massiv[Num_to_un(6)]._data[i6]._nagr[6]; b[6]:=dec_massiv[Num_to_un(6)]._data[i6].sum_topl; nakop_a:=nakop_a+a[6]; nakop_b:=nakop_b+b[6]; nakop_mask:=nakop_mask or Num_to_un(6); end;{if i6} if i7>=__min then if general_mask and Num_to_un(7)<>0 then begin a[7]:=dec_massiv[Num_to_un(7)]._data[i7]._nagr[7]; b[7]:=dec_massiv[Num_to_un(7)]._data[i7].sum_topl; nakop_a:=nakop_a+a[7]; nakop_b:=nakop_b+b[7]; nakop_mask:=nakop_mask or Num_to_un(7); end;{if i7} if i8>=__min then if general_mask and Num_to_un(8)<>0 then begin a[8]:=dec_massiv[Num_to_un(8)]._data[i8]._nagr[8]; b[8]:=dec_massiv[Num_to_un(8)]._data[i8].sum_topl; nakop_a:=nakop_a+a[8]; nakop_b:=nakop_b+b[8]; nakop_mask:=nakop_mask or Num_to_un(8); end;{if i8} if nakop_b<result_massiv._data[nakop_a].sum_topl then if nakop_b>0 then begin result_massiv._data[nakop_a].mask:=nakop_mask; for k:= 1 to 8 do result_massiv._data[nakop_a]._nagr[k]:=a[k]; result_massiv._data[nakop_a].sum_topl:=nakop_b; end;{if} end;{for} resinfo.iterations:=iters; resinfo.__time:=Now-beg_time; end;{perebor} Procedure __test; var a : integer; begin GLobal_optimization; oper_mask:=Extract_mask(56); if oper_mask.one=0 then; a:=un_to_Num(128); if a=0 then; a:=Num_to_un(8); if a=0 then; a:=__topl(1,50); if a=0 then; a:=__topl(2,50); if a=0 then; a:=__topl(3,50); if a=0 then; a:=__topl(4,50); if a=0 then; end;{__test} begin // __Test; Assign_massiv; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2023 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit PhotoBoxMainFmx; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.TabControl, FMX.StdCtrls, FMX.Objects, FMX.Edit, FMX.Layouts, FMX.Media, FMX.ListBox, FMX.ExtCtrls, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo, FB4D.Interfaces, FB4D.Configuration, FB4D.SelfRegistrationFra, CameraCaptureFra, PhotoThreads; type TfmxMain = class(TForm) TabControl: TTabControl; tabRegister: TTabItem; tabBox: TTabItem; layFBConfig: TLayout; edtKey: TEdit; Text2: TText; edtProjectID: TEdit; Text3: TText; lblVersionInfo: TLabel; edtBucket: TEdit; Text1: TText; tabCaptureImg: TTabItem; layToolbar: TLayout; lstPhotoList: TListBox; btnCaptureImg: TButton; fraCameraCapture: TfraCameraCapture; btnPhotoLib: TButton; sptPreview: TSplitter; imvPreview: TImageViewer; StatusBar: TStatusBar; lblStatus: TLabel; layPreview: TLayout; memPhotoInterpretation: TMemo; btnHidePreview: TButton; btnDelete: TButton; btnDownload: TButton; FraSelfRegistration: TFraSelfRegistration; txtLoggedInUser: TText; layUserInfo: TLayout; btnSignOut: TButton; procedure FormCreate(Sender: TObject); procedure btnCaptureImgClick(Sender: TObject); procedure btnPhotoLibClick(Sender: TObject); procedure lstPhotoListItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); procedure lstPhotoListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure imvPreviewResized(Sender: TObject); procedure btnDownloadClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnHidePreviewClick(Sender: TObject); procedure btnSignOutClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fConfig: IFirebaseConfiguration; fUID: string; function GetSettingFilename: string; function GetAuth: IFirebaseAuthentication; procedure OnUserLogin(const Info: string; User: IFirebaseUser); procedure SaveSettings; procedure HidePreview; procedure ShowPreview; procedure OnPhotoCaptured(Image: TBitmap; const FileName: string); procedure FillPhotoInterpreation(PI: TPhotoInterpretation); procedure OnChangedColDocument(Document: IFirestoreDocument); procedure OnDeletedColDocument(const DeleteDocumentPath: string; TimeStamp: TDateTime); procedure OnListenerError(const RequestID, ErrMsg: string); procedure OnStopListening(Sender: TObject); procedure OnUploaded(Item: TListBoxItem); procedure OnUploadFailed(Item: TListBoxItem; const Msg: string); procedure OnDownloaded(Item: TListBoxItem); procedure OnDownloadFailed(Item: TListBoxItem; const Msg: string); procedure OnDocumentDelete(const RequestID: string; Response: IFirebaseResponse); procedure OnPhotoDeleted(const ObjectName: TObjectName); procedure OnDeleteFailed(const RequestID, ErrMsg: string); public procedure WipeToTab(ActiveTab: TTabItem); end; var fmxMain: TfmxMain; implementation {$R *.fmx} uses System.IniFiles, System.IOUtils, System.Math, System.StrUtils, FB4D.Helpers, FB4D.Firestore; // Install the following Firestore Rule: // rules_version = '2'; // service cloud.firestore { // match /databases/{database}/documents { // match /photos/{photoID} { // allow read: // if (request.auth.uid != null) && // (request.auth.uid == resource.data.createdBy); // allow write: // if (request.auth.uid != null) && // (request.auth.uid == request.resource.data.createdBy); }}} // Install the following Storage Rule: // rules_version = '2'; // service firebase.storage { // match /b/{bucket}/o { // match /photos/{userID}/{photoID} { // allow read, write: // if request.auth.uid == userID;}}} resourcestring rsNoItemSelected = 'First, select an item in the list box'; rsListenerError = 'Database listener error: %s (%s)'; rsListenerStopped = 'Database listener stopped'; rsUploaded = ' uploaded'; rsUploadFailed = ' upload failed: '; rsDownloaded = ' downloaded'; rsDownloadFailed = ' download failed: '; rsDeletePhotoFailed = 'Delete photo %s failed: %s'; rsPhotoDeleted = 'Photo %s deleted'; {$REGION 'Form Handling'} procedure TfmxMain.FormCreate(Sender: TObject); var IniFile: TIniFile; LastEMail: string; LastToken: string; begin Caption := Caption + ' - ' + TFirebaseHelpers.GetConfigAndPlatform + ' [' + TFirebaseConfiguration.GetLibVersionInfo + ']'; IniFile := TIniFile.Create(GetSettingFilename); try edtKey.Text := IniFile.ReadString('FBProjectSettings', 'APIKey', ''); edtProjectID.Text := IniFile.ReadString('FBProjectSettings', 'ProjectID', ''); edtBucket.Text := IniFile.ReadString('FBProjectSettings', 'Bucket', ''); LastEMail := IniFile.ReadString('Authentication', 'User', ''); LastToken := IniFile.ReadString('Authentication', 'Token', ''); fraCameraCapture.InitialDir := IniFile.ReadString('Path', 'ImageLib', TPath.GetPicturesPath); finally IniFile.Free; end; TabControl.ActiveTab := tabRegister; {$IFDEF ANDROID} layPreview.Align := TAlignLayout.Client; StatusBar.Visible := false; btnPhotoLib.StyleLookup := 'organizetoolbutton'; {$ENDIF} FraSelfRegistration.InitializeAuthOnDemand(GetAuth, OnUserLogin, LastToken, LastEMail, true, false, true); if edtProjectID.Text.IsEmpty then edtProjectID.SetFocus; end; procedure TfmxMain.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; end; function TfmxMain.GetSettingFilename: string; var FileName: string; begin FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); result := IncludeTrailingPathDelimiter(TPath.GetHomePath) + FileName + TFirebaseHelpers.GetPlatform + '.ini'; end; function TfmxMain.GetAuth: IFirebaseAuthentication; function GetCacheFolder: string; var FileName: string; begin FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); result := IncludeTrailingPathDelimiter(TPath.GetHomePath) + IncludeTrailingPathDelimiter(FileName); end; begin fConfig := TFirebaseConfiguration.Create(edtKey.Text, edtProjectID.Text, edtBucket.Text); fConfig.Storage.SetupCacheFolder(GetCacheFolder); result := fConfig.Auth; layFBConfig.Visible := false; end; procedure TfmxMain.SaveSettings; var IniFile: TIniFile; begin IniFile := TIniFile.Create(GetSettingFilename); try IniFile.WriteString('FBProjectSettings', 'APIKey', edtKey.Text); IniFile.WriteString('FBProjectSettings', 'ProjectID', edtProjectID.Text); IniFile.WriteString('FBProjectSettings', 'Bucket', edtBucket.Text); IniFile.WriteString('Authentication', 'User', FraSelfRegistration.GetEMail); if assigned(fConfig) and fConfig.Auth.Authenticated then IniFile.WriteString('Authentication', 'Token', fConfig.Auth.GetRefreshToken) else IniFile.DeleteKey('Authentication', 'Token'); IniFile.WriteString('Path', 'ImageLib', fraCameraCapture.InitialDir); finally IniFile.Free; end; end; procedure TfmxMain.WipeToTab(ActiveTab: TTabItem); var c: integer; begin if TabControl.ActiveTab <> ActiveTab then begin if ActiveTab = tabBox then HidePreview; ActiveTab.Visible := true; {$IFDEF ANDROID} TabControl.ActiveTab := ActiveTab; {$ELSE} TabControl.GotoVisibleTab(ActiveTab.Index, TTabTransition.Slide, TTabTransitionDirection.Normal); {$ENDIF} for c := 0 to TabControl.TabCount - 1 do TabControl.Tabs[c].Visible := TabControl.Tabs[c] = ActiveTab; end; end; {$ENDREGION} {$REGION 'User Login'} procedure TfmxMain.OnUserLogin(const Info: string; User: IFirebaseUser); var Query: IStructuredQuery; begin txtLoggedInUser.Text := User.DisplayName; {$IFDEF DEBUG} txtLoggedInUser.Text := txtLoggedInUser.Text + #13#10'(UID:' + User.UID + ')'; {$ENDIF} fUID := User.UID; Query := TStructuredQuery.CreateForCollection(TPhotoThread.cCollectionID). QueryForFieldFilter( TQueryFilter.StringFieldFilter('createdBy', TWhereOperator.woEqual, fUID)); fConfig.Database.SubscribeQuery(Query, OnChangedColDocument, OnDeletedColDocument); fConfig.Database.StartListener(OnStopListening, OnListenerError); WipeToTab(tabBox); end; procedure TfmxMain.btnSignOutClick(Sender: TObject); begin fConfig.Database.StopListener; fConfig.Auth.SignOut; fUID := ''; lstPhotoList.Items.Clear; FraSelfRegistration.StartEMailEntering; WipeToTab(tabRegister); end; {$ENDREGION} procedure TfmxMain.btnCaptureImgClick(Sender: TObject); begin fraCameraCapture.StartCapture(OnPhotoCaptured); end; procedure TfmxMain.btnPhotoLibClick(Sender: TObject); begin fraCameraCapture.StartTakePhotoFromLib(OnPhotoCaptured); end; procedure TfmxMain.btnDeleteClick(Sender: TObject); var Item: TListBoxItem; DocID: string; begin if lstPhotoList.ItemIndex < 0 then fraCameraCapture.ToastMsg(rsNoItemSelected) else begin Item := lstPhotoList.ItemByIndex(lstPhotoList.ItemIndex); DocID := Item.TagString; // 1st step: Delete document in Firestore fConfig.Database.Delete([TPhotoThread.cCollectionID, DocID], nil, OnDocumentDelete, OnDeleteFailed); end; end; procedure TfmxMain.btnDownloadClick(Sender: TObject); var Item: TListBoxItem; ObjName: string; Obj: IStorageObject; Stream: TStream; begin if lstPhotoList.ItemIndex < 0 then fraCameraCapture.ToastMsg(rsNoItemSelected) else begin Item := lstPhotoList.ItemByIndex(lstPhotoList.ItemIndex); ObjName := TPhotoThread.GetStorageObjName(Item.TagString, fUID); Obj := fConfig.Storage.GetObjectFromCache(ObjName); if assigned(Obj) then begin Stream := fConfig.Storage.GetFileFromCache(ObjName); if assigned(Stream) then begin fraCameraCapture.SaveImageToFile(Stream, Obj.ContentType); Stream.Free; end; end; end; end; procedure TfmxMain.btnHidePreviewClick(Sender: TObject); begin HidePreview; end; procedure TfmxMain.HidePreview; begin sptPreview.Visible := false; layPreview.Visible := false; btnHidePreview.Visible := false; btnDownload.Visible := false; btnDelete.Visible := false; {$IFDEF ANDROID} btnCaptureImg.Visible := true; btnPhotoLib.Visible := true; {$ENDIF} end; procedure TfmxMain.ShowPreview; begin layPreview.Visible := true; btnHidePreview.Visible := true; btnDelete.Visible := true; {$IFDEF ANDROID} btnCaptureImg.Visible := false; btnPhotoLib.Visible := false; {$ELSE} btnDownload.Visible := true; sptPreview.Visible := true; {$ENDIF} TThread.ForceQueue(nil, procedure begin Application.ProcessMessages; imvPreview.BestFit; end); end; procedure TfmxMain.imvPreviewResized(Sender: TObject); begin TThread.ForceQueue(nil, procedure begin imvPreview.BestFit; end); end; procedure TfmxMain.OnPhotoCaptured(Image: TBitmap; const FileName: string); var Item: TListBoxItem; Upload: TPhotoThread; Thumbnail: TBitmap; begin if TabControl.ActiveTab <> tabBox then WipeToTab(tabBox); imvPreview.Bitmap.Width := Image.Width; imvPreview.Bitmap.Height := Image.Height; imvPreview.Bitmap.CopyFromBitmap(Image); Item := TListBoxItem.Create(lstPhotoList); Item.Text := FileName; Thumbnail := TPhotoThread.CreateThumbnail(Image); try Item.ItemData.Bitmap.Assign(Thumbnail); finally Thumbnail.Free; end; lstPhotoList.AddObject(Item); lstPhotoList.ItemIndex := Item.Index; Upload := TPhotoThread.CreateForUpload(fConfig, fUID, Image, Item); Upload.StartThread(OnUploaded, OnUploadFailed); memPhotoInterpretation.Lines.Clear; ShowPreview; end; procedure TfmxMain.OnUploaded(Item: TListBoxItem); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsUploaded); if layPreview.Visible then if assigned(Item.Data) then FillPhotoInterpreation(Item.Data as TPhotoInterpretation) else memPhotoInterpretation.Lines.Clear; end; procedure TfmxMain.OnUploadFailed(Item: TListBoxItem; const Msg: string); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsUploadFailed + Msg); end; procedure TfmxMain.OnDownloaded(Item: TListBoxItem); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsDownloaded); end; procedure TfmxMain.OnDownloadFailed(Item: TListBoxItem; const Msg: string); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsDownloadFailed + Msg); end; procedure TfmxMain.OnChangedColDocument(Document: IFirestoreDocument); var Download: TPhotoThread; begin Download := TPhotoThread.CreateForDownload(fConfig, fUID, lstPhotoList, Document); Download.StartThread(OnDownloaded, OnDownloadFailed); end; procedure TfmxMain.OnDeletedColDocument(const DeleteDocumentPath: string; TimeStamp: TDateTime); var arr: TStringDynArray; Item: TListBoxItem; begin arr := SplitString(DeleteDocumentPath, '/'); Assert(length(arr) >= 6, 'Deleted document path is to short: ' + DeleteDocumentPath); Item := TPhotoThread.SearchItem(lstPhotoList, arr[length(arr) - 1 ]); if assigned(Item) then begin if layPreview.Visible and (lstPhotoList.ItemIndex = Item.Index) then HidePreview; Item.Free; end; end; procedure TfmxMain.OnDeleteFailed(const RequestID, ErrMsg: string); begin fraCameraCapture.ToastMsg(Format(rsDeletePhotoFailed, [RequestID, ErrMsg])); end; procedure TfmxMain.OnDocumentDelete(const RequestID: string; Response: IFirebaseResponse); var StorageObjName: string; arr: TStringDynArray; begin arr := SplitString(RequestID, ','); Assert(length(arr) = 2, 'RequestID does not contain a path with 2 levels in OnDeletePhoto'); StorageObjName := TPhotoThread.GetStorageObjName(arr[1], fUID); fConfig.Storage.Delete(StorageObjName, OnPhotoDeleted, OnDeleteFailed); end; procedure TfmxMain.OnListenerError(const RequestID, ErrMsg: string); begin if not Application.Terminated then fraCameraCapture.ToastMsg(Format(rsListenerError, [ErrMsg, RequestID])); end; procedure TfmxMain.OnPhotoDeleted(const ObjectName: TObjectName); begin fraCameraCapture.ToastMsg(Format(rsPhotoDeleted, [ObjectName])); end; procedure TfmxMain.OnStopListening(Sender: TObject); begin if not Application.Terminated then fraCameraCapture.ToastMsg(rsListenerStopped); end; procedure TfmxMain.lstPhotoListItemClick(const Sender: TCustomListBox; const Item: TListBoxItem); var ObjName: string; Stream: TStream; begin ObjName := TPhotoThread.GetStorageObjName(Item.TagString, fUID); Stream := fConfig.Storage.GetFileFromCache(ObjName); if assigned(Stream) then begin imvPreview.Bitmap.LoadFromStream(Stream); Stream.Free; if assigned(Item.Data) then FillPhotoInterpreation(Item.Data as TPhotoInterpretation) else memPhotoInterpretation.Lines.Clear; ShowPreview; end; end; procedure TfmxMain.FillPhotoInterpreation(PI: TPhotoInterpretation); const cBorders = 4; begin memPhotoInterpretation.Lines.Text := PI.FullInfo; memPhotoInterpretation.Height := min(cBorders * 2 + memPhotoInterpretation.Lines.Count * (memPhotoInterpretation.Font.Size + cBorders), layPreview.Height / 4); end; procedure TfmxMain.lstPhotoListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if lstPhotoList.ItemByPoint(X, Y) = nil then HidePreview; end; end.
{ DO NOT USE! } unit uTrigger; interface uses tinyglr, glrMath, uPhysics2D, uBox2DImport; const CAT_SENSOR = $8000; type TpdTrigger = class; TpdOnTrigger = procedure(Trigger: TpdTrigger; Catched: Tb2Fixture) of object; { TpdTrigger } TpdTrigger = class private fWorld: Tglrb2World; FActive: Boolean; FOnEnter, FOnLeave: TpdOnTrigger; function GetPos: TdfVec2f; function GetSize: TdfVec2f; function GetVisible: Boolean; procedure SetPos(const Value: TdfVec2f); procedure SetSize(const Value: TdfVec2f); procedure SetVisible(const Value: Boolean); class function CreateBoxTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; W, H: Single; mask: Word; IsStatic: Boolean): TpdTrigger; class function CreateCircleTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; Rad: Single; mask: Word; IsStatic: Boolean): TpdTrigger; public Sprite: TglrSprite; Body: Tb2Body; property Position: TdfVec2f read GetPos write SetPos; property Size: TdfVec2f read GetSize write SetSize; property Visible: Boolean read GetVisible write SetVisible; property OnEnter: TpdOnTrigger read FOnEnter write FOnEnter; property OnLeave: TpdOnTrigger read FOnLeave write FOnLeave; property IsActive: Boolean read FActive; constructor Create(); destructor Destroy(); override; procedure SetTrigger(Active: Boolean; Catched: Tb2Fixture); end; { TpdTriggerFactory } TpdTriggerFactory = class private procedure OnBeginContact(var contact: Tb2Contact); procedure OnEndContact(var contact: Tb2Contact); public constructor Create(); destructor Destroy(); override; function AddBoxTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; W, H: Single; mask: Word; IsStatic: Boolean): TpdTrigger; function AddCircleTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; Rad: Single; mask: Word; IsStatic: Boolean): TpdTrigger; end; implementation { TpdTrigger } const COLOR_INACTIVE: TdfVec4f = (x: 0.3; y: 0.9; z: 0.3; w: 0.3); COLOR_ACTIVE: TdfVec4f = (x: 0.9; y: 0.3; z: 0.3; w: 0.3); constructor TpdTrigger.Create; begin inherited; Sprite := TglrSprite.Create(); with Sprite do begin Visible := False; SetVerticesColor(COLOR_INACTIVE); Position.z := 5; end; end; class function TpdTrigger.CreateBoxTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; W, H: Single; mask: Word; IsStatic: Boolean): TpdTrigger; var f: Tb2Filter; begin Result := TpdTrigger.Create(); with Result do begin fWorld := aWorld; Sprite.Width := W; Sprite.Height := H; Sprite.Position := dfVec3f(aPos, Sprite.Position.z); Body := Box2D.BoxSensor(aWorld, aPos, dfVec2f(W, H), 0, mask, CAT_SENSOR, IsStatic); Body.UserData := @Result; end; end; class function TpdTrigger.CreateCircleTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; Rad: Single; mask: Word; IsStatic: Boolean): TpdTrigger; var f: Tb2Filter; begin Result := TpdTrigger.Create(); with Result do begin fWorld := aWorld; Sprite.Width := Rad; Sprite.Height := Rad; Sprite.Position := dfVec3f(aPos, Sprite.Position.z); Body := Box2D.CircleSensor(aWorld, aPos, Rad, mask, CAT_SENSOR, IsStatic); Body.UserData := @Result; f.categoryBits := CAT_SENSOR; f.maskBits := mask; Body.GetFixtureList.SetFilterData(f); end; end; destructor TpdTrigger.Destroy; begin Sprite.Free(); fWorld.DestroyBody(Body); inherited; end; function TpdTrigger.GetPos: TdfVec2f; begin Result := dfVec2f(Sprite.Position); end; function TpdTrigger.GetSize: TdfVec2f; begin Result := dfVec2f(Sprite.Width, Sprite.Height); end; function TpdTrigger.GetVisible: Boolean; begin Result := Sprite.Visible; end; procedure TpdTrigger.SetPos(const Value: TdfVec2f); begin Sprite.Position.x := Value.x; Sprite.Position.y := Value.y; end; procedure TpdTrigger.SetSize(const Value: TdfVec2f); begin Sprite.Width := Value.x; Sprite.Height := Value.y; end; procedure TpdTrigger.SetTrigger(Active: Boolean; Catched: Tb2Fixture); begin if Active then begin Sprite.SetVerticesColor(COLOR_ACTIVE); if Assigned(FOnEnter) then FOnEnter(Self, Catched); end else begin Sprite.SetVerticesColor(COLOR_INACTIVE); if Assigned(FOnLeave) then FOnLeave(Self, Catched); end; // if Active and not FActive then // begin // Sprite.Material.Diffuse := COLOR_ACTIVE; // if Assigned(FOnEnter) then // FOnEnter(Self, Catched); // end // else if not Active and FActive then // begin // Sprite.Material.Diffuse := COLOR_INACTIVE; // if Assigned(FOnLeave) then // FOnLeave(Self, Catched); // end; FActive := Active; end; procedure TpdTrigger.SetVisible(const Value: Boolean); begin Sprite.Visible := Value; end; { TpdTriggerFactory } function TpdTriggerFactory.AddBoxTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; W, H: Single; mask: Word; IsStatic: Boolean): TpdTrigger; begin Result := TpdTrigger.CreateBoxTrigger(aWorld, aPos, W, H, mask, IsStatic); end; function TpdTriggerFactory.AddCircleTrigger(aWorld: Tglrb2World; aPos: TdfVec2f; Rad: Single; mask: Word; IsStatic: Boolean): TpdTrigger; begin Result := TpdTrigger.CreateCircleTrigger(aWorld, aPos, Rad, mask, IsStatic); end; constructor TpdTriggerFactory.Create; begin inherited; b2world.AddOnBeginContact(OnBeginContact); b2world.AddOnEndContact(OnEndContact); end; destructor TpdTriggerFactory.Destroy; begin b2world.RemoveOnBeginContact(OnBeginContact); b2world.RemoveOnEndContact(OnEndContact); inherited; end; procedure TpdTriggerFactory.OnBeginContact(var contact: Tb2Contact); var f1, f2: Tb2Fixture; p: TpdUserData; begin f1 := contact.m_fixtureA; f2 := contact.m_fixtureB; if f1.IsSensor and (not f2.IsSensor) then begin p := TpdUserData(f1.GetBody.UserData^); TpdTrigger(p.aObject).SetTrigger(True, f2); end; if (not f1.IsSensor) and f2.IsSensor then begin p := TpdUserData(f2.GetBody.UserData^); TpdTrigger(p.aObject).SetTrigger(True, f1); //!!!! //move it to afterupdate end; end; procedure TpdTriggerFactory.OnEndContact(var contact: Tb2Contact); var f1, f2: Tb2Fixture; p: TpdUserData; begin f1 := contact.m_fixtureA; f2 := contact.m_fixtureB; if f1.IsSensor and (not f2.IsSensor) then begin p := TpdUserData(f1.GetBody.UserData^); TpdTrigger(p.aObject).SetTrigger(False, f2); end; if (not f1.IsSensor) and f2.IsSensor then begin p := TpdUserData(f2.GetBody.UserData^); TpdTrigger(p.aObject).SetTrigger(False, f1); end; end; end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.HttpServer.Intf.Cache Description : Http Server Cache Interface Author : Kike Pérez Version : 1.0 Created : 12/10/2019 Modified : 27/10/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Cache.Intf; {$i QuickLib.inc} interface type ICache = interface ['{CF5061E1-BEAC-4CCC-8469-5020968116B9}'] function GetCompression: Boolean; procedure SetCompression(const Value: Boolean); function GetCachedObjects: Integer; function GetCacheSize: Integer; property Compression : Boolean read GetCompression write SetCompression; property CachedObjects : Integer read GetCachedObjects; property CacheSize : Integer read GetCacheSize; procedure SetValue(const aKey : string; aValue : TObject; aExpirationMilliseconds : Integer = 0); overload; procedure SetValue(const aKey : string; aValue : TObject; aExpirationDate : TDateTime); overload; procedure SetValue(const aKey, aValue : string; aExpirationMilliseconds : Integer = 0); overload; procedure SetValue(const aKey, aValue : string; aExpirationDate : TDateTime); overload; procedure SetValue(const aKey : string; aValue : TArray<string>; aExpirationMilliseconds : Integer = 0); overload; procedure SetValue(const aKey : string; aValue : TArray<string>; aExpirationDate : TDateTime); overload; procedure SetValue(const aKey : string; aValue : TArray<TObject>; aExpirationMilliseconds : Integer = 0); overload; procedure SetValue(const aKey : string; aValue : TArray<TObject>; aExpirationDate : TDateTime); overload; function GetValue(const aKey : string) : string; overload; function TryGetValue(const aKey : string; aValue : TObject) : Boolean; overload; function TryGetValue(const aKey : string; out aValue : string) : Boolean; overload; function TryGetValue(const aKey : string; out aValue : TArray<string>) : Boolean; overload; function TryGetValue(const aKey : string; out aValue : TArray<TObject>) : Boolean; overload; procedure RemoveValue(const aKey : string); procedure Flush; end; IMemoryCache = ICache; implementation end.
program sumOfDigits(input, output); var number : integer; digit : integer; sum : integer; flag : integer; begin write('Number: '); read(number); if number < 0 then writeln('Must be positive.') else begin flag := number; sum := 0; digit := 0; while (number > 0) do begin digit := number mod 10; sum := sum + digit; number := number div 10; end; writeln('The sum of digits of ', flag, ' is: ', sum); end end.
(*============================================================================= * * SHA1 计 算 * 来源:本代码摘自 CnPack * 说明:只保留 WebSocket 握手必须的 SHA1 计算 * 优化: 高凉新农 * =============================================================================*) {******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2016 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} {* |<PRE> ================================================================================ * 软件名称:开发包基础库 * 单元名称:SHA1算法单元 * 单元作者:刘啸(Liu Xiao) * 备 注: * 开发平台:PWin2000Pro + Delphi 5.0 * 兼容测试:PWin9X/2000/XP + Delphi 5/6 * 本 地 化:该单元中的字符串均符合本地化处理方式 * 单元标识:$Id: CnSHA1.pas 426 2010-02-09 07:01:49Z liuxiao $ * 修改记录:2015.08.14 V1.2 * 汇编切换至 Pascal 以支持跨平台 * 2014.10.22 V1.1 * 加入 HMAC 方法 * 2010.07.14 V1.0 * 创建单元。从网上佚名代码移植而来,加入部分功能 * ================================================================================ |</PRE>} unit iocp_SHA1; interface {$I in_iocp.inc} {$IF CompilerVersion >= 18.5} {$DEFINE USE_INLINE} {$ELSE} {$DEFINE DELPHI_7} {$IFEND} uses {$IFDEF DELPHI_XE7UP} WinAPI.Windows, System.Classes, System.SysUtils {$ELSE} Windows, Classes, SysUtils {$ENDIF}; type PSHA1Hash = ^TSHA1Hash; TSHA1Hash = array[0..4] of DWORD; PHashRecord = ^THashRecord; THashRecord = record case Integer of 0: (A, B, C, D, E: DWORD); 1: (Hash: TSHA1Hash); end; PSHA1Digest = ^TSHA1Digest; TSHA1Digest = array[0..19] of Byte; PSHA1Block = ^TSHA1Block; TSHA1Block = array[0..63] of Byte; PSHA1Data = ^TSHA1Data; TSHA1Data = array[0..79] of DWORD; TSHA1Context = record Hash: TSHA1Hash; Hi, Lo: DWORD; Buffer: TSHA1Block; Index: Integer; end; // 计算 AnsiString function SHA1StringA(const Str: AnsiString): TSHA1Digest; // 计算内存块 function SHA1StringB(const Buffers: Pointer; Len: Integer): TSHA1Digest; // TSHA1Digest 转为 Base64,生成 WebSocket 握手的 WebSocket-Accept key function EncodeBase64(const Digest: TSHA1Digest): String; implementation type PPacket = ^TPacket; TPacket = packed record case Integer of 0: (b0, b1, b2, b3: Byte); 1: (i: Integer); 2: (a: array[0..3] of Byte); 3: (c: array[0..3] of AnsiChar); end; const SHA_INIT_HASH: TSHA1Hash = ( $67452301, $EFCDAB89, $98BADCFE, $10325476, $C3D2E1F0 ); SHA_ZERO_BUFFER: TSHA1Block = ( 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, // 0..19 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, // 20..39 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, // 40..59 0,0,0,0 // 60..63 ); EncodeTable: array[0..63] of AnsiChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789+/'; function RB(A: DWORD): DWORD; {$IFDEF USE_INLINE} inline {$ENDIF} begin Result := (A shr 24) or ((A shr 8) and $FF00) or ((A shl 8) and $FF0000) or (A shl 24); end; function LRot32(X: DWORD; c: Integer): DWORD; {$IFDEF USE_INLINE} inline {$ENDIF} begin Result := X shl (c and 31) + X shr (32 - c and 31); end; procedure SHA1Init(var Context: TSHA1Context); {$IFDEF USE_INLINE} inline {$ENDIF} begin Context.Hi := 0; Context.Lo := 0; Context.Index := 0; Context.Buffer := SHA_ZERO_BUFFER; Context.Hash := SHA_INIT_HASH; end; procedure SHA1UpdateLen(var Context: TSHA1Context; Len: Integer); {$IFDEF USE_INLINE} inline {$ENDIF} var i, k: DWORD; begin for k := 0 to 7 do begin i := Context.Lo; Inc(Context.Lo, Len); if Context.Lo < i then Inc(Context.Hi); end; end; procedure SHA1Compress(var Data: TSHA1Context; Block: PSHA1Data = nil; SetNull: Boolean = True); procedure _FW(var W: TSHA1Data; Bk: PSHA1Data); {$IFDEF USE_INLINE} inline {$ENDIF} var i: Integer; begin for i := 0 to 15 do W[i] := RB(Bk^[i]); end; function _F1(const HR: THashRecord): DWORD; {$IFDEF USE_INLINE} inline {$ENDIF} begin Result := HR.D xor (HR.B and (HR.C xor HR.D)); end; function _F2(const HR: THashRecord): DWORD; {$IFDEF USE_INLINE} inline {$ENDIF} begin Result := HR.B xor HR.C xor HR.D; end; function _F3(const HR: THashRecord): DWORD; {$IFDEF USE_INLINE} inline {$ENDIF} begin Result := (HR.B and HR.C) or (HR.D and (HR.B or HR.C)); end; var i: Integer; T: DWORD; HR: THashRecord; W: TSHA1Data; begin if (Block = nil) then begin _FW(W, PSHA1Data(@Data.Buffer)); Data.Buffer := SHA_ZERO_BUFFER; // 清空 end else _FW(W, Block); for i := 16 to 79 do // 16-3=13, 79-16=63 W[i] := LRot32(W[i - 3] xor W[i - 8] xor W[i - 14] xor W[i - 16], 1); HR.Hash := Data.Hash; for i := 0 to 19 do begin T := LRot32(HR.A, 5) + _F1(HR) + HR.E + W[i] + $5A827999; HR.E := HR.D; HR.D := HR.C; HR.C := LRot32(HR.B, 30); HR.B := HR.A; HR.A := T; end; for i := 20 to 39 do begin T := LRot32(HR.A, 5) + _F2(HR) + HR.E + W[i] + $6ED9EBA1; HR.E := HR.D; HR.D := HR.C; HR.C := LRot32(HR.B, 30); HR.B := HR.A; HR.A := T; end; for i := 40 to 59 do begin T := LRot32(HR.A, 5) + _F3(HR) + HR.E + W[i] + $8F1BBCDC; HR.E := HR.D; HR.D := HR.C; HR.C := LRot32(HR.B, 30); HR.B := HR.A; HR.A := T; end; for i := 60 to 79 do begin T := LRot32(HR.A, 5) + _F2(HR) + HR.E + W[i] + $CA62C1D6; HR.E := HR.D; HR.D := HR.C; HR.C := LRot32(HR.B, 30); HR.B := HR.A; HR.A := T; end; Inc(Data.Hash[0], HR.A); Inc(Data.Hash[1], HR.B); Inc(Data.Hash[2], HR.C); Inc(Data.Hash[3], HR.D); Inc(Data.Hash[4], HR.E); end; procedure SHA1Update(var Context: TSHA1Context; Buffer: Pointer; Len: Integer); var i: Integer; begin SHA1UpdateLen(Context, Len); if (Context.Index = 0) then while (Len >= 64) do begin SHA1Compress(Context, PSHA1Data(Buffer), False); // 直接传原数据 Inc(PByte(Buffer), 64); Dec(Len, 64); end; while (Len > 0) do begin i := 64 - Context.Index; // 剩余空间 if (Len < i) then // 剩余空间能容纳剩余内容 i := Len; Move(Buffer^, Context.Buffer[Context.Index], i); Inc(PByte(Buffer), i); Inc(Context.Index, i); Dec(Len, i); if Context.Index = 64 then begin Context.Index := 0; SHA1Compress(Context); end; end; end; procedure SHA1Final(var Context: TSHA1Context; var Digest: TSHA1Digest); begin Context.Buffer[Context.Index] := $80; if Context.Index >= 56 then SHA1Compress(Context); PDWord(@Context.Buffer[56])^ := RB(Context.Hi); PDWord(@Context.Buffer[60])^ := RB(Context.Lo); SHA1Compress(Context); Context.Hash[0] := RB(Context.Hash[0]); Context.Hash[1] := RB(Context.Hash[1]); Context.Hash[2] := RB(Context.Hash[2]); Context.Hash[3] := RB(Context.Hash[3]); Context.Hash[4] := RB(Context.Hash[4]); Digest := PSHA1Digest(@Context.Hash)^; end; // ============================================================ function SHA1StringA(const Str: AnsiString): TSHA1Digest; var Context: TSHA1Context; begin // 计算 AnsiString 的 SHA1 值 SHA1Init(Context); SHA1Update(Context, PAnsiChar(Str), Length(Str)); SHA1Final(Context, Result); end; function SHA1StringB(const Buffers: Pointer; Len: Integer): TSHA1Digest; var Context: TSHA1Context; begin // 计算 Buffers 的 SHA1 值 SHA1Init(Context); SHA1Update(Context, Buffers, Len); SHA1Final(Context, Result); end; // ============================================================ procedure EncodePacket(const Packet: TPacket; NumChars: Integer; OutBuf: PAnsiChar); begin OutBuf[0] := EnCodeTable[Packet.a[0] shr 2]; OutBuf[1] := EnCodeTable[((Packet.a[0] shl 4) or (Packet.a[1] shr 4)) and $0000003f]; if NumChars < 2 then OutBuf[2] := '=' else OutBuf[2] := EnCodeTable[((Packet.a[1] shl 2) or (Packet.a[2] shr 6)) and $0000003f]; if NumChars < 3 then OutBuf[3] := '=' else OutBuf[3] := EnCodeTable[Packet.a[2] and $0000003f]; end; function EncodeBase64(const Digest: TSHA1Digest): String; var OutBuf: array[0..56] of AnsiChar; BufPtr: PAnsiChar; I, J, K, BytesRead: Integer; Packet: TPacket; begin // 摘自 delphi 2007, 单元 encddecd.pas I := 0; K := 0; BytesRead := SizeOf(TSHA1Digest); BufPtr := OutBuf; while I < BytesRead do begin if BytesRead - I < 3 then J := BytesRead - I else J := 3; Packet.i := 0; Packet.b0 := Digest[I]; if J > 1 then Packet.b1 := Digest[I + 1]; if J > 2 then Packet.b2 := Digest[I + 2]; EncodePacket(Packet, J, BufPtr); Inc(I, 3); Inc(BufPtr, 4); Inc(K, 4); if K > 75 then begin BufPtr[0] := #$0D; BufPtr[1] := #$0A; Inc(BufPtr, 2); K := 0; end; end; SetString(Result, OutBuf, BufPtr - PAnsiChar(@OutBuf)); end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://187.121.80.12:12121/wsdl/IIntegraViagens?wsdl // >Import : http://187.121.80.12:12121/wsdl/IIntegraViagens?wsdl>0 // Version : 1.0 // (14/11/2017 17:22:27 - - $Rev: 56641 $) // ************************************************************************ // unit IIntegraViagens1; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Embarcadero types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:dateTime - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:double - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:int - "http://www.w3.org/2001/XMLSchema"[Gbl] Permissao = class; { "urn:IntegraViagensIntf"[GblCplx] } PermissaoPeriodo = class; { "urn:IntegraViagensIntf"[GblCplx] } PermissaoPlaca = class; { "urn:IntegraViagensIntf"[GblCplx] } PosicaoHistorico = class; { "urn:IntegraViagensIntf"[GblCplx] } RetornoMensagem = class; { "urn:IntegraViagensIntf"[GblCplx] } Viagem = class; { "urn:IntegraViagensIntf"[GblCplx] } CancelarViagem = class; { "urn:IntegraViagensIntf"[GblCplx] } Retorno = class; { "urn:IntegraViagensIntf"[GblCplx] } VeiculoConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } ParametroVeiculoConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } ClienteConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } ParametroClienteConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } EmbarcadorConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } ParametroEmbarcadorConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } MotoristaConsulta = class; { "urn:IntegraViagensIntf"[GblCplx] } MotoristaInsert = class; { "urn:IntegraViagensIntf"[GblCplx] } VeiculoInsert = class; { "urn:IntegraViagensIntf"[GblCplx] } CarretaInsert = class; { "urn:IntegraViagensIntf"[GblCplx] } HodometroVeiculo = class; { "urn:IntegraViagensIntf"[GblCplx] } Entrega = class; { "urn:IntegraViagensIntf"[GblCplx] } Vinculo = class; { "urn:IntegraViagensIntf"[GblCplx] } TipoCarroceria = class; { "urn:IntegraViagensIntf"[GblCplx] } RetornoInsert = class; { "urn:IntegraViagensIntf"[GblCplx] } ClienteInsert = class; { "urn:IntegraViagensIntf"[GblCplx] } Rota = class; { "urn:IntegraViagensIntf"[GblCplx] } Posicao = class; { "urn:IntegraViagensIntf"[GblCplx] } StatusColetaEntrega = class; { "urn:IntegraViagensIntf"[GblCplx] } StatusViagem = class; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYMensagem = array of RetornoMensagem; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYHodometroVeiculo = array of HodometroVeiculo; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYPosicaoHistorico = array of PosicaoHistorico; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYMotoristaConsulta = array of MotoristaConsulta; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYEmbarcadorConsulta = array of EmbarcadorConsulta; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYClienteConsulta = array of ClienteConsulta; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYVeiculoConsulta = array of VeiculoConsulta; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYRotas = array of Rota; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYEntregas = array of Entrega; { "urn:IntegraViagensIntf"[GblCplx] } // ************************************************************************ // // XML : Permissao, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Permissao = class(TRemotable) private FClienteCNPJ: string; FUsuario: string; FLiberacao: string; published property ClienteCNPJ: string read FClienteCNPJ write FClienteCNPJ; property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; end; // ************************************************************************ // // XML : PermissaoPeriodo, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // PermissaoPeriodo = class(TRemotable) private FClienteCNPJ: string; FUsuario: string; FLiberacao: string; FDataInicio: string; FDataFim: string; FPlaca: string; published property ClienteCNPJ: string read FClienteCNPJ write FClienteCNPJ; property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; property DataInicio: string read FDataInicio write FDataInicio; property DataFim: string read FDataFim write FDataFim; property Placa: string read FPlaca write FPlaca; end; // ************************************************************************ // // XML : PermissaoPlaca, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // PermissaoPlaca = class(TRemotable) private FClienteCNPJ: string; FUsuario: string; FLiberacao: string; FPlaca: string; published property ClienteCNPJ: string read FClienteCNPJ write FClienteCNPJ; property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; property Placa: string read FPlaca write FPlaca; end; // ************************************************************************ // // XML : PosicaoHistorico, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // PosicaoHistorico = class(TRemotable) private FPlaca: string; FDataPosicao: TXSDateTime; FLatitude: Double; FLongitude: Double; FVelocidade: Double; FDescPosicao: string; FIgnicao: string; public destructor Destroy; override; published property Placa: string read FPlaca write FPlaca; property DataPosicao: TXSDateTime read FDataPosicao write FDataPosicao; property Latitude: Double read FLatitude write FLatitude; property Longitude: Double read FLongitude write FLongitude; property Velocidade: Double read FVelocidade write FVelocidade; property DescPosicao: string read FDescPosicao write FDescPosicao; property Ignicao: string read FIgnicao write FIgnicao; end; // ************************************************************************ // // XML : RetornoMensagem, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // RetornoMensagem = class(TRemotable) private FData: TXSDateTime; FMensagem: string; FNumeroMacro: string; FLatitude: Double; FLongitude: Double; FIgnicao: string; FPlaca: string; public destructor Destroy; override; published property Data: TXSDateTime read FData write FData; property Mensagem: string read FMensagem write FMensagem; property NumeroMacro: string read FNumeroMacro write FNumeroMacro; property Latitude: Double read FLatitude write FLatitude; property Longitude: Double read FLongitude write FLongitude; property Ignicao: string read FIgnicao write FIgnicao; property Placa: string read FPlaca write FPlaca; end; // ************************************************************************ // // XML : Viagem, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Viagem = class(TRemotable) private FUsuario: string; FLiberacao: string; FCodViagem: string; FClienteRazaoSocial: string; FClienteCNPJ: string; FVeiculoPlaca: string; FVeiculoTecnologia: string; FVeiculoIDRastreador: string; FVeiculoCNPJProprietario: string; FVeiculoRazaoSocial: string; FCarreta1Placa: string; FCarreta1CNPJProprietario: string; FCarreta1RazaoSocial: string; FCarreta2Placa: string; FCarreta2CNPJProprietario: string; FCarreta2RazaoSocial: string; FCarreta3Placa: string; FCarreta3CNPJProprietario: string; FCarreta3RazaoSocial: string; FMotoristaNome: string; FMotoristaCPF: string; FMotoristaTelefone: string; FCargaProdutoPredominante: string; FCargaValorTotal: Double; FCargaPesoTotal: Double; FOrigem: Entrega; FDestino: Entrega; FRaioOrigem: Integer; FRaioDestino: Integer; FEntregas: ARRAYEntregas; FDataSaida: TXSDateTime; FDataChegadaPrev: TXSDateTime; FObservacao: string; FManifesto_CTE: string; FRota: Integer; public destructor Destroy; override; published property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; property CodViagem: string read FCodViagem write FCodViagem; property ClienteRazaoSocial: string read FClienteRazaoSocial write FClienteRazaoSocial; property ClienteCNPJ: string read FClienteCNPJ write FClienteCNPJ; property VeiculoPlaca: string read FVeiculoPlaca write FVeiculoPlaca; property VeiculoTecnologia: string read FVeiculoTecnologia write FVeiculoTecnologia; property VeiculoIDRastreador: string read FVeiculoIDRastreador write FVeiculoIDRastreador; property VeiculoCNPJProprietario: string read FVeiculoCNPJProprietario write FVeiculoCNPJProprietario; property VeiculoRazaoSocial: string read FVeiculoRazaoSocial write FVeiculoRazaoSocial; property Carreta1Placa: string read FCarreta1Placa write FCarreta1Placa; property Carreta1CNPJProprietario: string read FCarreta1CNPJProprietario write FCarreta1CNPJProprietario; property Carreta1RazaoSocial: string read FCarreta1RazaoSocial write FCarreta1RazaoSocial; property Carreta2Placa: string read FCarreta2Placa write FCarreta2Placa; property Carreta2CNPJProprietario: string read FCarreta2CNPJProprietario write FCarreta2CNPJProprietario; property Carreta2RazaoSocial: string read FCarreta2RazaoSocial write FCarreta2RazaoSocial; property Carreta3Placa: string read FCarreta3Placa write FCarreta3Placa; property Carreta3CNPJProprietario: string read FCarreta3CNPJProprietario write FCarreta3CNPJProprietario; property Carreta3RazaoSocial: string read FCarreta3RazaoSocial write FCarreta3RazaoSocial; property MotoristaNome: string read FMotoristaNome write FMotoristaNome; property MotoristaCPF: string read FMotoristaCPF write FMotoristaCPF; property MotoristaTelefone: string read FMotoristaTelefone write FMotoristaTelefone; property CargaProdutoPredominante: string read FCargaProdutoPredominante write FCargaProdutoPredominante; property CargaValorTotal: Double read FCargaValorTotal write FCargaValorTotal; property CargaPesoTotal: Double read FCargaPesoTotal write FCargaPesoTotal; property Origem: Entrega read FOrigem write FOrigem; property Destino: Entrega read FDestino write FDestino; property RaioOrigem: Integer read FRaioOrigem write FRaioOrigem; property RaioDestino: Integer read FRaioDestino write FRaioDestino; property Entregas: ARRAYEntregas read FEntregas write FEntregas; property DataSaida: TXSDateTime read FDataSaida write FDataSaida; property DataChegadaPrev: TXSDateTime read FDataChegadaPrev write FDataChegadaPrev; property Observacao: string read FObservacao write FObservacao; property Manifesto_CTE: string read FManifesto_CTE write FManifesto_CTE; property Rota: Integer read FRota write FRota; end; // ************************************************************************ // // XML : CancelarViagem, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // CancelarViagem = class(TRemotable) private FCodViagem: Integer; FCNPJEmpresa: string; FUsuario: string; FLiberacao: string; published property CodViagem: Integer read FCodViagem write FCodViagem; property CNPJEmpresa: string read FCNPJEmpresa write FCNPJEmpresa; property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; end; // ************************************************************************ // // XML : Retorno, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Retorno = class(TRemotable) private FCodigo: Integer; FDescricao: string; FModulo: string; FCampoChave: string; FMotivo: string; FDataHora: string; FCodigosEntrega: string; published property Codigo: Integer read FCodigo write FCodigo; property Descricao: string read FDescricao write FDescricao; property Modulo: string read FModulo write FModulo; property CampoChave: string read FCampoChave write FCampoChave; property Motivo: string read FMotivo write FMotivo; property DataHora: string read FDataHora write FDataHora; property CodigosEntrega: string read FCodigosEntrega write FCodigosEntrega; end; // ************************************************************************ // // XML : VeiculoConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // VeiculoConsulta = class(TRemotable) private FCodigoCliente: Integer; FCodigoVeiculo: Integer; FPlaca: string; FChassi: string; FRenavan: string; FCodigoIBGE: Integer; FModelo: string; FAnoModelo: Integer; FAnoFabricado: Integer; FPesoPermitido: Double; FCubagemPermitida: Double; FVinculo: Integer; FTipoVeiculo: Integer; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; property CodigoVeiculo: Integer read FCodigoVeiculo write FCodigoVeiculo; property Placa: string read FPlaca write FPlaca; property Chassi: string read FChassi write FChassi; property Renavan: string read FRenavan write FRenavan; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; property Modelo: string read FModelo write FModelo; property AnoModelo: Integer read FAnoModelo write FAnoModelo; property AnoFabricado: Integer read FAnoFabricado write FAnoFabricado; property PesoPermitido: Double read FPesoPermitido write FPesoPermitido; property CubagemPermitida: Double read FCubagemPermitida write FCubagemPermitida; property Vinculo: Integer read FVinculo write FVinculo; property TipoVeiculo: Integer read FTipoVeiculo write FTipoVeiculo; end; // ************************************************************************ // // XML : ParametroVeiculoConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // ParametroVeiculoConsulta = class(TRemotable) private FCodigoCliente: Integer; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; end; // ************************************************************************ // // XML : ClienteConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // ClienteConsulta = class(TRemotable) private FCodigoCliente: Integer; FFantasia: string; FRazaoSocial: string; FCpfCnpj: string; FRg: string; FEndereco: string; FComplemento: string; FBairro: string; FCep: string; FCodigoIBGE: Integer; FTelefone: string; FCelular: string; FEmail: string; FInscricaoEstadual: string; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; property Fantasia: string read FFantasia write FFantasia; property RazaoSocial: string read FRazaoSocial write FRazaoSocial; property CpfCnpj: string read FCpfCnpj write FCpfCnpj; property Rg: string read FRg write FRg; property Endereco: string read FEndereco write FEndereco; property Complemento: string read FComplemento write FComplemento; property Bairro: string read FBairro write FBairro; property Cep: string read FCep write FCep; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; property Telefone: string read FTelefone write FTelefone; property Celular: string read FCelular write FCelular; property Email: string read FEmail write FEmail; property InscricaoEstadual: string read FInscricaoEstadual write FInscricaoEstadual; end; // ************************************************************************ // // XML : ParametroClienteConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // ParametroClienteConsulta = class(TRemotable) private FCodigoCliente: Integer; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; end; // ************************************************************************ // // XML : EmbarcadorConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // EmbarcadorConsulta = class(TRemotable) private FCodigoEmbarcador: Integer; FNome: string; FEndereco: string; FCidade: string; FCnpj: string; FCodigoIBGE: Integer; published property CodigoEmbarcador: Integer read FCodigoEmbarcador write FCodigoEmbarcador; property Nome: string read FNome write FNome; property Endereco: string read FEndereco write FEndereco; property Cidade: string read FCidade write FCidade; property Cnpj: string read FCnpj write FCnpj; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; end; // ************************************************************************ // // XML : ParametroEmbarcadorConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // ParametroEmbarcadorConsulta = class(TRemotable) private FCodigoCliente: Integer; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; end; // ************************************************************************ // // XML : MotoristaConsulta, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // MotoristaConsulta = class(TRemotable) private FCodigoMotorista: Integer; FCpf: string; FNome: string; FRg: string; FCNH: string; FDataVencimentoCNH: TXSDateTime; FRua: string; FComplemento: string; FBairro: string; FCodigoIBGE: Integer; public destructor Destroy; override; published property CodigoMotorista: Integer read FCodigoMotorista write FCodigoMotorista; property Cpf: string read FCpf write FCpf; property Nome: string read FNome write FNome; property Rg: string read FRg write FRg; property CNH: string read FCNH write FCNH; property DataVencimentoCNH: TXSDateTime read FDataVencimentoCNH write FDataVencimentoCNH; property Rua: string read FRua write FRua; property Complemento: string read FComplemento write FComplemento; property Bairro: string read FBairro write FBairro; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; end; // ************************************************************************ // // XML : MotoristaInsert, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // MotoristaInsert = class(TRemotable) private FCodigoCliente: Integer; FNome: string; FCPF: string; FRG: string; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; property Nome: string read FNome write FNome; property CPF: string read FCPF write FCPF; property RG: string read FRG write FRG; end; // ************************************************************************ // // XML : VeiculoInsert, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // VeiculoInsert = class(TRemotable) private FCodigoCliente: Integer; FPlaca: string; FId: Integer; FChassi: string; FRenavan: string; FCodigoIBGE: Integer; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; property Placa: string read FPlaca write FPlaca; property Id: Integer read FId write FId; property Chassi: string read FChassi write FChassi; property Renavan: string read FRenavan write FRenavan; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; end; // ************************************************************************ // // XML : CarretaInsert, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // CarretaInsert = class(TRemotable) private FCodigoCliente: Integer; FPlaca: string; FId: Integer; FChassi: string; FRenavan: string; FCodigoIBGE: Integer; FNumeroANTT: string; FCodigoTipoCarroceria: Integer; published property CodigoCliente: Integer read FCodigoCliente write FCodigoCliente; property Placa: string read FPlaca write FPlaca; property Id: Integer read FId write FId; property Chassi: string read FChassi write FChassi; property Renavan: string read FRenavan write FRenavan; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; property NumeroANTT: string read FNumeroANTT write FNumeroANTT; property CodigoTipoCarroceria: Integer read FCodigoTipoCarroceria write FCodigoTipoCarroceria; end; // ************************************************************************ // // XML : HodometroVeiculo, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // HodometroVeiculo = class(TRemotable) private FPlaca: string; FDataPosicao: TXSDateTime; FLatitude: Double; FLongitude: Double; FVelocidade: Integer; FHodometro: Integer; FIgnicao: string; public destructor Destroy; override; published property Placa: string read FPlaca write FPlaca; property DataPosicao: TXSDateTime read FDataPosicao write FDataPosicao; property Latitude: Double read FLatitude write FLatitude; property Longitude: Double read FLongitude write FLongitude; property Velocidade: Integer read FVelocidade write FVelocidade; property Hodometro: Integer read FHodometro write FHodometro; property Ignicao: string read FIgnicao write FIgnicao; end; // ************************************************************************ // // XML : Entrega, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Entrega = class(TRemotable) private FRazao: string; FCNPJ: string; FEndereco: string; FUF: string; FCidade: string; FCodigoIBGE: Integer; FLatitude: Double; FLongitude: Double; FNotas: string; FRaioEntrega: Integer; FPrevisaoEntrega: TXSDateTime; public destructor Destroy; override; published property Razao: string read FRazao write FRazao; property CNPJ: string read FCNPJ write FCNPJ; property Endereco: string read FEndereco write FEndereco; property UF: string read FUF write FUF; property Cidade: string read FCidade write FCidade; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; property Latitude: Double read FLatitude write FLatitude; property Longitude: Double read FLongitude write FLongitude; property Notas: string read FNotas write FNotas; property RaioEntrega: Integer read FRaioEntrega write FRaioEntrega; property PrevisaoEntrega: TXSDateTime read FPrevisaoEntrega write FPrevisaoEntrega; end; ARRAYTipoCarroceria = array of TipoCarroceria; { "urn:IntegraViagensIntf"[GblCplx] } // ************************************************************************ // // XML : Vinculo, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Vinculo = class(TRemotable) private FCodigo: Integer; FNome: string; published property Codigo: Integer read FCodigo write FCodigo; property Nome: string read FNome write FNome; end; // ************************************************************************ // // XML : TipoCarroceria, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // TipoCarroceria = class(TRemotable) private FCodigoTipoCarroceria: Integer; FNome: string; published property CodigoTipoCarroceria: Integer read FCodigoTipoCarroceria write FCodigoTipoCarroceria; property Nome: string read FNome write FNome; end; // ************************************************************************ // // XML : RetornoInsert, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // RetornoInsert = class(TRemotable) private FCodigo: Integer; FDescricao: string; FDataHora: string; published property Codigo: Integer read FCodigo write FCodigo; property Descricao: string read FDescricao write FDescricao; property DataHora: string read FDataHora write FDataHora; end; // ************************************************************************ // // XML : ClienteInsert, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // ClienteInsert = class(TRemotable) private FRazaoSocial: string; FFantasia: string; FCpfCnpj: string; FEndereco: string; FBairro: string; FCodigoIBGE: Integer; published property RazaoSocial: string read FRazaoSocial write FRazaoSocial; property Fantasia: string read FFantasia write FFantasia; property CpfCnpj: string read FCpfCnpj write FCpfCnpj; property Endereco: string read FEndereco write FEndereco; property Bairro: string read FBairro write FBairro; property CodigoIBGE: Integer read FCodigoIBGE write FCodigoIBGE; end; ARRAYVinculo = array of Vinculo; { "urn:IntegraViagensIntf"[GblCplx] } ARRAYPosicao = array of Posicao; { "urn:IntegraViagensIntf"[GblCplx] } // ************************************************************************ // // XML : Rota, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Rota = class(TRemotable) private FCodigoRota: Integer; FNome: string; FKM: Double; FTempo: Integer; FDescricao: string; FCodigoIBGECidadeOrigem: Integer; FCodigoIBGECidadeDestino: Integer; published property CodigoRota: Integer read FCodigoRota write FCodigoRota; property Nome: string read FNome write FNome; property KM: Double read FKM write FKM; property Tempo: Integer read FTempo write FTempo; property Descricao: string read FDescricao write FDescricao; property CodigoIBGECidadeOrigem: Integer read FCodigoIBGECidadeOrigem write FCodigoIBGECidadeOrigem; property CodigoIBGECidadeDestino: Integer read FCodigoIBGECidadeDestino write FCodigoIBGECidadeDestino; end; // ************************************************************************ // // XML : Posicao, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // Posicao = class(TRemotable) private FPlaca: string; FDataPosicao: TXSDateTime; FLatitude: Double; FLongitude: Double; FVelocidade: Double; FCodigoViagem: Integer; FCodigoRota: Integer; FDescPosicao: string; FAlvoAtual: Integer; public destructor Destroy; override; published property Placa: string read FPlaca write FPlaca; property DataPosicao: TXSDateTime read FDataPosicao write FDataPosicao; property Latitude: Double read FLatitude write FLatitude; property Longitude: Double read FLongitude write FLongitude; property Velocidade: Double read FVelocidade write FVelocidade; property CodigoViagem: Integer read FCodigoViagem write FCodigoViagem; property CodigoRota: Integer read FCodigoRota write FCodigoRota; property DescPosicao: string read FDescPosicao write FDescPosicao; property AlvoAtual: Integer read FAlvoAtual write FAlvoAtual; end; // ************************************************************************ // // XML : StatusColetaEntrega, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // StatusColetaEntrega = class(TRemotable) private FCodColetaEntrega: Integer; FCNPJEmpresa: string; FUsuario: string; FLiberacao: string; published property CodColetaEntrega: Integer read FCodColetaEntrega write FCodColetaEntrega; property CNPJEmpresa: string read FCNPJEmpresa write FCNPJEmpresa; property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; end; // ************************************************************************ // // XML : StatusViagem, global, <complexType> // Namespace : urn:IntegraViagensIntf // ************************************************************************ // StatusViagem = class(TRemotable) private FCodViagem: Integer; FCNPJEmpresa: string; FUsuario: string; FLiberacao: string; published property CodViagem: Integer read FCodViagem write FCodViagem; property CNPJEmpresa: string read FCNPJEmpresa write FCNPJEmpresa; property Usuario: string read FUsuario write FUsuario; property Liberacao: string read FLiberacao write FLiberacao; end; // ************************************************************************ // // Namespace : urn:IntegraViagensIntf-IIntegraViagens // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // use : encoded // binding : IIntegraViagensbinding // service : IIntegraViagensservice // port : IIntegraViagensPort // URL : http://187.121.80.12:12121/soap/IIntegraViagens // ************************************************************************ // IIntegraViagens = interface(IInvokable) ['{E0F670BB-7232-8CF9-41A0-BC853CDB3522}'] function IntegraViagens(const parameters: Viagem): Retorno; stdcall; function CancelaViagem(const parameters: CancelarViagem): Retorno; stdcall; function RotasCliente(const parameters: Permissao): ARRAYRotas; stdcall; function PosicoesVeiculosCliente(const parameters: Permissao): ARRAYPosicao; stdcall; function GetStatusViagem(const parameters: StatusViagem): string; stdcall; function GetStatusColetaEntrega(const parameters: StatusColetaEntrega): string; stdcall; function PosicoesVeiculosCarregados(const parameters: Permissao): ARRAYPosicao; stdcall; function GetVinculos: ARRAYVinculo; stdcall; function GetTipoCarrocerias: ARRAYTipoCarroceria; stdcall; function InserirCliente(const oClienteInsert: ClienteInsert): RetornoInsert; stdcall; function InserirVeiculo(const oVeiculoInsert: VeiculoInsert): RetornoInsert; stdcall; function InserirCarreta(const oCarretaInsert: CarretaInsert): RetornoInsert; stdcall; function InserirMotorista(const oMotoristaInsert: MotoristaInsert): RetornoInsert; stdcall; function PosicoesVeiculosTempo(const parameters: PermissaoPeriodo): ARRAYPosicaoHistorico; stdcall; function PosicoesVeiculosPlaca(const parameters: PermissaoPlaca): ARRAYPosicao; stdcall; function MensagensVeiculo(const parameters: PermissaoPeriodo): ARRAYMensagem; stdcall; function HodometrosVeiculo(const parameters: PermissaoPeriodo): ARRAYHodometroVeiculo; stdcall; function GetClientes: ARRAYClienteConsulta; stdcall; function GetVeiculos(const parameters: ParametroVeiculoConsulta): ARRAYVeiculoConsulta; stdcall; function GetMotoristas(const parameters: ParametroClienteConsulta): ARRAYMotoristaConsulta; stdcall; function GetEmbarcadores(const parameters: ParametroEmbarcadorConsulta): ARRAYEmbarcadorConsulta; stdcall; end; function GetIIntegraViagens(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IIntegraViagens; implementation uses SysUtils; function GetIIntegraViagens(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IIntegraViagens; const defWSDL = 'http://187.121.80.12:12121/wsdl/IIntegraViagens?wsdl'; defURL = 'http://187.121.80.12:12121/soap/IIntegraViagens'; defSvc = 'IIntegraViagensservice'; defPrt = 'IIntegraViagensPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as IIntegraViagens); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor PosicaoHistorico.Destroy; begin SysUtils.FreeAndNil(FDataPosicao); inherited Destroy; end; destructor RetornoMensagem.Destroy; begin SysUtils.FreeAndNil(FData); inherited Destroy; end; destructor Viagem.Destroy; var I: Integer; begin for I := 0 to System.Length(FEntregas)-1 do SysUtils.FreeAndNil(FEntregas[I]); System.SetLength(FEntregas, 0); SysUtils.FreeAndNil(FOrigem); SysUtils.FreeAndNil(FDestino); SysUtils.FreeAndNil(FDataSaida); SysUtils.FreeAndNil(FDataChegadaPrev); inherited Destroy; end; destructor MotoristaConsulta.Destroy; begin SysUtils.FreeAndNil(FDataVencimentoCNH); inherited Destroy; end; destructor HodometroVeiculo.Destroy; begin SysUtils.FreeAndNil(FDataPosicao); inherited Destroy; end; destructor Entrega.Destroy; begin SysUtils.FreeAndNil(FPrevisaoEntrega); inherited Destroy; end; destructor Posicao.Destroy; begin SysUtils.FreeAndNil(FDataPosicao); inherited Destroy; end; initialization { IIntegraViagens } InvRegistry.RegisterInterface(TypeInfo(IIntegraViagens), 'urn:IntegraViagensIntf-IIntegraViagens', ''); InvRegistry.RegisterAllSOAPActions(TypeInfo(IIntegraViagens), '|urn:IntegraViagensIntf-IIntegraViagens#IntegraViagens' +'|urn:IntegraViagensIntf-IIntegraViagens#CancelaViagem' +'|urn:IntegraViagensIntf-IIntegraViagens#RotasCliente' +'|urn:IntegraViagensIntf-IIntegraViagens#PosicoesVeiculosCliente' +'|urn:IntegraViagensIntf-IIntegraViagens#GetStatusViagem' +'|urn:IntegraViagensIntf-IIntegraViagens#GetStatusColetaEntrega' +'|urn:IntegraViagensIntf-IIntegraViagens#PosicoesVeiculosCarregados' +'|urn:IntegraViagensIntf-IIntegraViagens#GetVinculos' +'|urn:IntegraViagensIntf-IIntegraViagens#GetTipoCarrocerias' +'|urn:IntegraViagensIntf-IIntegraViagens#InserirCliente' +'|urn:IntegraViagensIntf-IIntegraViagens#InserirVeiculo' +'|urn:IntegraViagensIntf-IIntegraViagens#InserirCarreta' +'|urn:IntegraViagensIntf-IIntegraViagens#InserirMotorista' +'|urn:IntegraViagensIntf-IIntegraViagens#PosicoesVeiculosTempo' +'|urn:IntegraViagensIntf-IIntegraViagens#PosicoesVeiculosPlaca' +'|urn:IntegraViagensIntf-IIntegraViagens#MensagensVeiculo' +'|urn:IntegraViagensIntf-IIntegraViagens#HodometrosVeiculo' +'|urn:IntegraViagensIntf-IIntegraViagens#GetClientes' +'|urn:IntegraViagensIntf-IIntegraViagens#GetVeiculos' +'|urn:IntegraViagensIntf-IIntegraViagens#GetMotoristas' +'|urn:IntegraViagensIntf-IIntegraViagens#GetEmbarcadores' ); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYMensagem), 'urn:IntegraViagensIntf', 'ARRAYMensagem'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYHodometroVeiculo), 'urn:IntegraViagensIntf', 'ARRAYHodometroVeiculo'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYPosicaoHistorico), 'urn:IntegraViagensIntf', 'ARRAYPosicaoHistorico'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYMotoristaConsulta), 'urn:IntegraViagensIntf', 'ARRAYMotoristaConsulta'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYEmbarcadorConsulta), 'urn:IntegraViagensIntf', 'ARRAYEmbarcadorConsulta'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYClienteConsulta), 'urn:IntegraViagensIntf', 'ARRAYClienteConsulta'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYVeiculoConsulta), 'urn:IntegraViagensIntf', 'ARRAYVeiculoConsulta'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYRotas), 'urn:IntegraViagensIntf', 'ARRAYRotas'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYEntregas), 'urn:IntegraViagensIntf', 'ARRAYEntregas'); RemClassRegistry.RegisterXSClass(Permissao, 'urn:IntegraViagensIntf', 'Permissao'); RemClassRegistry.RegisterXSClass(PermissaoPeriodo, 'urn:IntegraViagensIntf', 'PermissaoPeriodo'); RemClassRegistry.RegisterXSClass(PermissaoPlaca, 'urn:IntegraViagensIntf', 'PermissaoPlaca'); RemClassRegistry.RegisterXSClass(PosicaoHistorico, 'urn:IntegraViagensIntf', 'PosicaoHistorico'); RemClassRegistry.RegisterXSClass(RetornoMensagem, 'urn:IntegraViagensIntf', 'RetornoMensagem'); RemClassRegistry.RegisterXSClass(Viagem, 'urn:IntegraViagensIntf', 'Viagem'); RemClassRegistry.RegisterXSClass(CancelarViagem, 'urn:IntegraViagensIntf', 'CancelarViagem'); RemClassRegistry.RegisterXSClass(Retorno, 'urn:IntegraViagensIntf', 'Retorno'); RemClassRegistry.RegisterXSClass(VeiculoConsulta, 'urn:IntegraViagensIntf', 'VeiculoConsulta'); RemClassRegistry.RegisterXSClass(ParametroVeiculoConsulta, 'urn:IntegraViagensIntf', 'ParametroVeiculoConsulta'); RemClassRegistry.RegisterXSClass(ClienteConsulta, 'urn:IntegraViagensIntf', 'ClienteConsulta'); RemClassRegistry.RegisterXSClass(ParametroClienteConsulta, 'urn:IntegraViagensIntf', 'ParametroClienteConsulta'); RemClassRegistry.RegisterXSClass(EmbarcadorConsulta, 'urn:IntegraViagensIntf', 'EmbarcadorConsulta'); RemClassRegistry.RegisterXSClass(ParametroEmbarcadorConsulta, 'urn:IntegraViagensIntf', 'ParametroEmbarcadorConsulta'); RemClassRegistry.RegisterXSClass(MotoristaConsulta, 'urn:IntegraViagensIntf', 'MotoristaConsulta'); RemClassRegistry.RegisterXSClass(MotoristaInsert, 'urn:IntegraViagensIntf', 'MotoristaInsert'); RemClassRegistry.RegisterXSClass(VeiculoInsert, 'urn:IntegraViagensIntf', 'VeiculoInsert'); RemClassRegistry.RegisterXSClass(CarretaInsert, 'urn:IntegraViagensIntf', 'CarretaInsert'); RemClassRegistry.RegisterXSClass(HodometroVeiculo, 'urn:IntegraViagensIntf', 'HodometroVeiculo'); RemClassRegistry.RegisterXSClass(Entrega, 'urn:IntegraViagensIntf', 'Entrega'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYTipoCarroceria), 'urn:IntegraViagensIntf', 'ARRAYTipoCarroceria'); RemClassRegistry.RegisterXSClass(Vinculo, 'urn:IntegraViagensIntf', 'Vinculo'); RemClassRegistry.RegisterXSClass(TipoCarroceria, 'urn:IntegraViagensIntf', 'TipoCarroceria'); RemClassRegistry.RegisterXSClass(RetornoInsert, 'urn:IntegraViagensIntf', 'RetornoInsert'); RemClassRegistry.RegisterXSClass(ClienteInsert, 'urn:IntegraViagensIntf', 'ClienteInsert'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYVinculo), 'urn:IntegraViagensIntf', 'ARRAYVinculo'); RemClassRegistry.RegisterXSInfo(TypeInfo(ARRAYPosicao), 'urn:IntegraViagensIntf', 'ARRAYPosicao'); RemClassRegistry.RegisterXSClass(Rota, 'urn:IntegraViagensIntf', 'Rota'); RemClassRegistry.RegisterXSClass(Posicao, 'urn:IntegraViagensIntf', 'Posicao'); RemClassRegistry.RegisterXSClass(StatusColetaEntrega, 'urn:IntegraViagensIntf', 'StatusColetaEntrega'); RemClassRegistry.RegisterXSClass(StatusViagem, 'urn:IntegraViagensIntf', 'StatusViagem'); end.
{ PROGRAMME AlgoTP1_TD1_Boucle_Tavares_Léo // g: convertir un nombre de la base 10 à la base 2 // i: un nombre en base 10 choisi par l'utilisateur // o: le nombre converti en base 2. VAR nombreEntre, dividende : ENTIER chaineBinaire : CHAINE DEBUT ECRIRE "Bienvenue dans le programme pour convertir une valeur de la base 10 a la base 2." ECRIRE "--------------------------------------------------------------------------------" ECRIRE "Entrez une valeur decimale, comme par exemple 258." LIRE nombreEntre // on lit le nombre entre en decimale dividende <- nombreEntre REPETER SI (dividende MOD 2 = 1) ALORS // le SI test le reste grace au modulo, dans un cas ca sera 1 dans l'autre chaineBinaire <- '1' + chaineBinaire // ca sera 0, il l'inscrit donc devant la chaine chaineBinaire SINON chaineBinaire <- '0' + chaineBinaire FINSI dividende <- dividende div 2 // division entiere JUSQU'A (nb = 0) ECRIRE "Votre nombre " &nombreEntre & " donne " &chaineBinaire & " en binaire !" ECRIRE "Merci d'avoir utilise le programme de conversion base 10 a base 2 !" FIN } // JEU D'ESSAI : { nombreEntre <- 16 chaineBinaire <- '' dividende <- 16 Boucle : 1) chaineBinaire : 0 & dividende : 8 2) chaineBinaire : 00 & dividende : 4 3) chaineBinaire : 000 & dividende : 2 4) chaineBinaire : 0000 & dividende : 1 5) chaineBinaire : 10000 & dividende : 0 Sortie Boucle Affiche : 10000 } program Algo_TD1_Boucle_Leo_TAVARES; uses crt; var nombreEntre, dividende : integer; chaineBinaire : string; BEGIN clrscr; writeln('Bienvenue dans le programme pour convertir une valeur de la base 10 a la base 2.'); writeln('--------------------------------------------------------------------------------'); write('Entrez le nombre que vous voulez convertir en base 2 : '); readln(nombreEntre); writeln('--------------------------------------------------------------------------------'); write('Traitement du nombre ', nombreEntre, ', en binaire cela donne : '); chaineBinaire := ''; dividende := nombreEntre; repeat begin if (dividende mod 2 = 1) then begin chaineBinaire := '1' + chaineBinaire; end else begin chaineBinaire := '0' + chaineBinaire; end; dividende := dividende div 2; end; until (dividende = 0); writeln(chaineBinaire); readln; END. // Leo TAVARES F1B : 2016/11/22 : TD1 BOUCLES, ALGOTP1 : Algorithme, jeu d'essai et programme pascal
Unit Randomize; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {$mode objfpc}{$H+} {$macro on} {$inline on} interface uses CoreTypes, Math, SysUtils; function RandomTPA(Amount:Integer; MinX,MinY,MaxX,MaxY:Integer): TPointArray; ////StdCall; function RandomCenterTPA(Amount:Integer; CX,CY,RadX,RadY:Integer): TPointArray; //StdCall; function RandomTIA(Amount:Integer; Low,Hi:Integer): TIntArray; //StdCall; //-------------------------------------------------- implementation (* Simple random tpa, with some extra parameters compared to what SCAR offers. *) function RandomTPA(Amount:Integer; MinX,MinY,MaxX,MaxY:Integer): TPointArray; //StdCall; var i:Integer; begin SetLength(Result, Amount); for i:=0 to Amount-1 do Result[i] := Point(RandomRange(MinX, MaxX), RandomRange(MinY, MaxY)); end; (* TPA with a "gravity" that goes towards the mean (center). Similar to gaussian distribution of the TPoints. *) function RandomCenterTPA(Amount:Integer; CX,CY,RadX,RadY:Integer): TPointArray; //StdCall; var i:Integer; x,y,xstep,ystep: Single; begin SetLength(Result, Amount); xstep := RadX / Amount; ystep := RadY / Amount; x:=0; y:=0; for i:=0 to Amount-1 do begin x := x + xstep; y := y + ystep; Result[i].x := RandomRange(Round(CX-x), Round(CX+x)); Result[i].y := RandomRange(Round(CY-y), Round(CY+y)); end; end; (* Simple random TIA, with some extra parameters compared to what SCAR offers. *) function RandomTIA(Amount:Integer; Low,Hi:Integer): TIntArray; //StdCall; var i:Integer; begin SetLength(Result, Amount); for i:=0 to Amount-1 do Result[i] := RandomRange(Low,Hi); end; end.
{***************************************************************************} { TEllipsLabel component } { for Delphi & C++Builder } { } { written by } { TMS Software } { copyright © 2001-2012 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The complete } { source code remains property of the author and may not be distributed, } { published, given or sold in any form as such. No parts of the source } { code can be included in any other component or application without } { written authorization of the author. } {***************************************************************************} unit EllipsLabel; {$I TMSDEFS.INC} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; const MAJ_VER = 1; // Major version nr. MIN_VER = 0; // Minor version nr. REL_VER = 0; // Release nr. BLD_VER = 0; // Build nr. // version history // v1.0.0.0 : First release type TEllipsType = (etNone, etEndEllips, etPathEllips); {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TEllipsLabel = class(TLabel) private FEllipsType: TEllipsType; procedure SetEllipsType(const Value: TEllipsType); function GetVersion: string; procedure SetVersion(const Value: string); { Private declarations } protected { Protected declarations } function GetVersionNr: Integer; virtual; procedure Paint; override; public { Public declarations } published { Published declarations } property EllipsType: TEllipsType read FEllipsType write SetEllipsType; property Version: string read GetVersion write SetVersion; end; implementation const ALIGNSTYLE : array[TAlignment] of DWORD = (DT_LEFT, DT_RIGHT, DT_CENTER); WORDWRAPSTYLE : array[Boolean] of DWORD = (DT_SINGLELINE, DT_WORDBREAK); LAYOUTSTYLE : array[TTextLayout] of DWORD = (0,DT_VCENTER,DT_BOTTOM); ELLIPSSTYLE : array[TEllipsType] of DWORD = (0,DT_END_ELLIPSIS,DT_PATH_ELLIPSIS); ACCELSTYLE : array[Boolean] of DWORD = (DT_NOPREFIX,0); { TEllipsLabel } procedure TEllipsLabel.Paint; var R: TRect; DrawStyle: DWORD; begin R := GetClientRect; if not Transparent then begin Canvas.Brush.Color := Color; Canvas.Pen.Color := Color; Canvas.Rectangle(R.Left,R.Top,R.Right,R.Bottom); end; Canvas.Brush.Style := bsClear; DrawStyle := ALIGNSTYLE[Alignment] or WORDWRAPSTYLE[WordWrap] or LAYOUTSTYLE[Layout] or ELLIPSSTYLE[FEllipsType] or ACCELSTYLE[ShowAccelChar]; DrawStyle := DrawTextBiDiModeFlags(DrawStyle); Canvas.Font := Font; if not Enabled then begin OffsetRect(R, 1, 1); Canvas.Font.Color := clBtnHighlight; DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle, nil); OffsetRect(R, -1, -1); Canvas.Font.Color := clBtnShadow; DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle, nil); end else DrawTextEx(Canvas.Handle,PChar(Caption),Length(Caption),R, DrawStyle, nil); end; procedure TEllipsLabel.SetEllipsType(const Value: TEllipsType); begin if FEllipsType <> Value then begin FEllipsType := Value; Invalidate; end; end; function TEllipsLabel.GetVersion: string; var vn: Integer; begin vn := GetVersionNr; Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn))); end; function TEllipsLabel.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TEllipsLabel.SetVersion(const Value: string); begin end; end.
unit FFSPageControl; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, FFSTypes; type TGetTabFontEvent = procedure(Sender: TObject; ATabIndex:integer; AFont:TFont) of object; TFFSPCMode = (pcNormal, pcFlat, pcHideTabs); TFFSPageControl = class(TPageControl) private FOnGetTabFont: TGetTabFontEvent; FOnActivePageUpdate: TNotifyEvent; FMode: TFFSPCMode; procedure SetOnGetTabFont(const Value: TGetTabFontEvent); procedure SetOnActivePageUpdate(const Value: TNotifyEvent); function GetTabCount: integer; procedure SetMode(const Value: TFFSPCMode); procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; { Private declarations } protected { Protected declarations } procedure DrawTab(TabIndex: Integer; const Rect: TRect; Active: Boolean); override; procedure UpdateActivePage; override; procedure WndProc(var Message:TMessage); override; public { Public declarations } property TabCount:integer Read GetTabCount; published { Published declarations } property OnGetTabFont:TGetTabFontEvent read FOnGetTabFont write SetOnGetTabFont; property OnActivePageUpdate:TNotifyEvent read FOnActivePageUpdate write SetOnActivePageUpdate;//(sender:TObject); property Mode:TFFSPCMode read FMode write SetMode; end; procedure Register; implementation uses commctrl; procedure Register; begin RegisterComponents('FFS Common', [TFFSPageControl]); end; { TFFSPageControl } procedure TFFSPageControl.DrawTab(TabIndex: Integer; const Rect: TRect; Active: Boolean); var s : string; x : integer; r : integer; Bounds : TRect; y : integer; begin r := -1; x := 0; y := 0; while (r < tabindex) and (y < self.PageCount) do begin if self.pages[y].tabvisible then inc(r) else inc(x); inc(y); end; if r = tabindex then begin x := x + r; // check for user defined font for the real tab if assigned(OnGetTabFont) then OnGetTabFont(self,x,self.Canvas.Font); // get the caption s := self.Pages[x].Caption; Bounds := Rect; inc(Bounds.Top,2); inc(Bounds.Bottom,2); // draw it DrawText(self.canvas.Handle, PChar(s), Length(s), Bounds, DT_CENTER or DT_VCENTER); end; end; function TFFSPageControl.GetTabCount: integer; begin result := tabs.Count; end; procedure TFFSPageControl.MsgFFSColorChange(var Msg: TMessage); var i: integer; begin Broadcast(Msg); for i := 0 to Self.PageCount - 1 do begin self.Pages[i].Broadcast(Msg); end; end; procedure TFFSPageControl.SetMode(const Value: TFFSPCMode); begin FMode := Value; end; procedure TFFSPageControl.SetOnActivePageUpdate(const Value: TNotifyEvent); begin FOnActivePageUpdate := Value; end; procedure TFFSPageControl.SetOnGetTabFont(const Value: TGetTabFontEvent); begin FOnGetTabFont := Value; end; procedure TFFSPageControl.UpdateActivePage; begin if assigned(OnActivePageUpdate) then OnActivePageUpdate(self); inherited; end; procedure TFFSPageControl.WndProc(var Message: TMessage); begin // Special thanks to Sigbjoern Revheim (Sigbjoern@mad.scientist.com) for the idea behind this portion if(Message.Msg=TCM_ADJUSTRECT) then begin Inherited WndProc(Message); if FMode = pcNormal then exit; if not (csDesigning in ComponentState) then begin PRect(Message.LParam)^.Left:=0; PRect(Message.LParam)^.Right:=ClientWidth; if FMode = pcFlat then PRect(Message.LParam)^.Top:= PRect(Message.LParam)^.Top-4 else PRect(Message.LParam)^.Top := -2; PRect(Message.LParam)^.Bottom:=ClientHeight; end; end else Inherited WndProc(Message); end; end.
unit ScriptDlg; { Inno Setup Copyright (C) 1997-2012 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Custom wizard pages } interface {$I VERSION.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Wizard, NewCheckListBox, NewStaticText, NewProgressBar, PasswordEdit, RichEditViewer, BidiCtrls, TaskbarProgressFunc; type TInputQueryWizardPage = class(TWizardPage) private FEdits: TList; FPromptLabels: TList; FSubCaptionLabel: TNewStaticText; FY: Integer; function GetEdit(Index: Integer): TPasswordEdit; function GetPromptLabel(Index: Integer): TNewStaticText; function GetValue(Index: Integer): String; procedure SetValue(Index: Integer; const Value: String); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Add(const APrompt: String; const APassword: Boolean): Integer; property Edits[Index: Integer]: TPasswordEdit read GetEdit; procedure Initialize(const SubCaption: String); property PromptLabels[Index: Integer]: TNewStaticText read GetPromptLabel; property SubCaptionLabel: TNewStaticText read FSubCaptionLabel; property Values[Index: Integer]: String read GetValue write SetValue; end; TInputOptionWizardPage = class(TWizardPage) private FCheckListBox: TNewCheckListBox; FExclusive: Boolean; FSubCaptionLabel: TNewStaticText; function GetSelectedValueIndex: Integer; function GetValue(Index: Integer): Boolean; procedure SetSelectedValueIndex(Value: Integer); procedure SetValue(Index: Integer; Value: Boolean); public function Add(const ACaption: String): Integer; function AddEx(const ACaption: String; const ALevel: Byte; const AExclusive: Boolean): Integer; property CheckListBox: TNewCheckListBox read FCheckListBox; procedure Initialize(const SubCaption: String; const Exclusive, ListBox: Boolean); property SelectedValueIndex: Integer read GetSelectedValueIndex write SetSelectedValueIndex; property SubCaptionLabel: TNewStaticText read FSubCaptionLabel; property Values[Index: Integer]: Boolean read GetValue write SetValue; end; TInputDirWizardPage = class(TWizardPage) private FAppendDir: Boolean; FButtons: TList; FEdits: TList; FNewFolderName: String; FPromptLabels: TList; FSubCaptionLabel: TNewStaticText; FY: Integer; procedure ButtonClick(Sender: TObject); function GetButton(Index: Integer): TNewButton; function GetEdit(Index: Integer): TEdit; function GetPromptLabel(Index: Integer): TNewStaticText; function GetValue(Index: Integer): String; procedure SetValue(Index: Integer; const Value: String); protected procedure NextButtonClick(var Continue: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Add(const APrompt: String): Integer; property Buttons[Index: Integer]: TNewButton read GetButton; property Edits[Index: Integer]: TEdit read GetEdit; procedure Initialize(const SubCaption: String; const AppendDir: Boolean; const NewFolderName: String); property PromptLabels[Index: Integer]: TNewStaticText read GetPromptLabel; property SubCaptionLabel: TNewStaticText read FSubCaptionLabel; property Values[Index: Integer]: String read GetValue write SetValue; end; TInputFileWizardPage = class(TWizardPage) private FButtons: TList; FEdits: TList; FInputFileDefaultExtensions: TStringList; FInputFileFilters: TStringList; FPromptLabels: TList; FSubCaptionLabel: TNewStaticText; FY: Integer; procedure ButtonClick(Sender: TObject); function GetButton(Index: Integer): TNewButton; function GetEdit(Index: Integer): TEdit; function GetPromptLabel(Index: Integer): TNewStaticText; function GetValue(Index: Integer): String; procedure SetValue(Index: Integer; const Value: String); function GetIsSaveButton(Index: Integer): Boolean; procedure SetIsSaveButton(Index: Integer; const IsSaveButton: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Add(const APrompt, AFilter, ADefaultExtension: String): Integer; property Buttons[Index: Integer]: TNewButton read GetButton; property Edits[Index: Integer]: TEdit read GetEdit; procedure Initialize(const SubCaption: String); property PromptLabels[Index: Integer]: TNewStaticText read GetPromptLabel; property SubCaptionLabel: TNewStaticText read FSubCaptionLabel; property Values[Index: Integer]: String read GetValue write SetValue; property IsSaveButton[Index: Integer]: Boolean read GetIsSaveButton write SetIsSaveButton; end; TOutputMsgWizardPage = class(TWizardPage) private FMsgLabel: TNewStaticText; public procedure Initialize(const Msg: String); property MsgLabel: TNewStaticText read FMsgLabel; end; TOutputMsgMemoWizardPage = class(TWizardPage) private FRichEditViewer: TRichEditViewer; FSubCaptionLabel: TNewStaticText; public procedure Initialize(const SubCaption: String; const Msg: AnsiString); property RichEditViewer: TRichEditViewer read FRichEditViewer; property SubCaptionLabel: TNewStaticText read FSubCaptionLabel; end; TOutputProgressWizardPage = class(TWizardPage) private FMsg1Label: TNewStaticText; FMsg2Label: TNewStaticText; FProgressBar: TNewProgressBar; FSavePageID: Integer; procedure ProcessMsgs; public constructor Create(AOwner: TComponent); override; procedure Hide; procedure Initialize; property Msg1Label: TNewStaticText read FMsg1Label; property Msg2Label: TNewStaticText read FMsg2Label; property ProgressBar: TNewProgressBar read FProgressBar; procedure SetProgress(const Position, Max: Longint); procedure SetText(const Msg1, Msg2: String); procedure Show; end; implementation uses Struct, Main, SelFolderForm, Msgs, MsgIDs, PathFunc, CmnFunc, CmnFunc2, BrowseFunc; const DefaultLabelHeight = 14; DefaultBoxTop = 24; { relative to top of InnerNotebook } DefaultBoxBottom = DefaultBoxTop + 205; {------} procedure SetCtlParent(const AControl, AParent: TWinControl); { Like assigning to AControl.Parent, but puts the control at the *bottom* of the z-order instead of the top, for MSAA compatibility. } var OldVisible: Boolean; begin { Hide the control so the handle won't be created yet, so that unnecessary "OBJ_REORDER" MSAA events don't get sent } OldVisible := AControl.Visible; AControl.Visible := False; AControl.Parent := AParent; AControl.SendToBack; AControl.Visible := OldVisible; end; {--- InputQuery ---} constructor TInputQueryWizardPage.Create(AOwner: TComponent); begin inherited; FEdits := TList.Create; FPromptLabels := TList.Create; end; destructor TInputQueryWizardPage.Destroy; begin FPromptLabels.Free; FEdits.Free; inherited; end; procedure TInputQueryWizardPage.Initialize(const SubCaption: String); begin FSubCaptionLabel := TNewStaticText.Create(Self); with FSubCaptionLabel do begin AutoSize := False; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := SubCaption; Parent := Surface; end; FY := WizardForm.AdjustLabelHeight(FSubCaptionLabel) + WizardForm.ScalePixelsY(DefaultBoxTop); end; function TInputQueryWizardPage.Add(const APrompt: String; const APassword: Boolean): Integer; var PromptLabel: TNewStaticText; Edit: TPasswordEdit; begin if APrompt <> '' then begin PromptLabel := TNewStaticText.Create(Self); with PromptLabel do begin AutoSize := False; Top := FY; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := APrompt; end; SetCtlParent(PromptLabel, Surface); Inc(FY, WizardForm.AdjustLabelHeight(PromptLabel) + WizardForm.ScalePixelsY(16)); end else PromptLabel := nil; Edit := TPasswordEdit.Create(Self); with Edit do begin Password := APassword; Top := FY; Width := SurfaceWidth; end; SetCtlParent(Edit, Surface); Inc(FY, WizardForm.ScalePixelsY(36)); if PromptLabel <> nil then PromptLabel.FocusControl := Edit; FPromptLabels.Add(PromptLabel); Result := FEdits.Add(Edit); end; function TInputQueryWizardPage.GetEdit(Index: Integer): TPasswordEdit; begin Result := TPasswordEdit(FEdits[Index]); end; function TInputQueryWizardPage.GetPromptLabel(Index: Integer): TNewStaticText; begin Result := TNewStaticText(FPromptLabels[Index]); end; function TInputQueryWizardPage.GetValue(Index: Integer): String; begin Result := GetEdit(Index).Text; end; procedure TInputQueryWizardPage.SetValue(Index: Integer; const Value: String); begin GetEdit(Index).Text := Value; end; {--- InputOption ---} procedure TInputOptionWizardPage.Initialize(const SubCaption: String; const Exclusive, ListBox: Boolean); var CaptionYDiff: Integer; begin FSubCaptionLabel := TNewStaticText.Create(Self); with SubCaptionLabel do begin AutoSize := False; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := SubCaption; Parent := Surface; end; CaptionYDiff := WizardForm.AdjustLabelHeight(SubCaptionLabel); FCheckListBox := TNewCheckListBox.Create(Self); with FCheckListBox do begin Top := CaptionYDiff + WizardForm.ScalePixelsY(DefaultBoxTop); Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultBoxBottom) - Top; Flat := ListBox and (shFlatComponentsList in SetupHeader.Options); end; SetCtlParent(FCheckListBox, Surface); FExclusive := Exclusive; if not ListBox then begin FCheckListBox.BorderStyle := bsNone; FCheckListBox.Color := clBtnFace; FCheckListBox.MinItemHeight := WizardForm.ScalePixelsY(22); FCheckListBox.WantTabs := True; end; end; function TInputOptionWizardPage.Add(const ACaption: String): Integer; begin Result := AddEx(ACaption, 0, FExclusive); end; function TInputOptionWizardPage.AddEx(const ACaption: String; const ALevel: Byte; const AExclusive: Boolean): Integer; begin if AExclusive then Result := FCheckListBox.AddRadioButton(ACaption, '', ALevel, False, True, nil) else Result := FCheckListBox.AddCheckBox(ACaption, '', ALevel, False, True, True, True, nil); end; function TInputOptionWizardPage.GetSelectedValueIndex: Integer; var I: Integer; begin for I := 0 to FCheckListBox.Items.Count-1 do if (FCheckListBox.ItemLevel[I] = 0) and FCheckListBox.Checked[I] then begin Result := I; Exit; end; Result := -1; end; function TInputOptionWizardPage.GetValue(Index: Integer): Boolean; begin Result := FCheckListBox.Checked[Index]; end; procedure TInputOptionWizardPage.SetSelectedValueIndex(Value: Integer); var I: Integer; begin for I := 0 to FCheckListBox.Items.Count-1 do if FCheckListBox.ItemLevel[I] = 0 then FCheckListBox.Checked[I] := (I = Value); end; procedure TInputOptionWizardPage.SetValue(Index: Integer; Value: Boolean); begin FCheckListBox.Checked[Index] := Value; end; {--- InputDir ---} constructor TInputDirWizardPage.Create(AOwner: TComponent); begin inherited; FButtons := TList.Create; FEdits := TList.Create; FPromptLabels := TList.Create; end; destructor TInputDirWizardPage.Destroy; begin FPromptLabels.Free; FEdits.Free; FButtons.Free; inherited; end; procedure TInputDirWizardPage.ButtonClick(Sender: TObject); var I: Integer; Edit: TEdit; S: String; begin I := FButtons.IndexOf(Sender); if I <> -1 then begin Edit := TEdit(FEdits[I]); S := Edit.Text; if ShowSelectFolderDialog(False, FAppendDir, S, FNewFolderName) then Edit.Text := S; end; end; procedure TInputDirWizardPage.NextButtonClick(var Continue: Boolean); var I: Integer; Edit: TEdit; begin for I := 0 to FEdits.Count-1 do begin Edit := FEdits[I]; if not ValidateCustomDirEdit(Edit, True, True, True) then begin if WizardForm.Visible then Edit.SetFocus; Continue := False; Exit; end; end; inherited; end; procedure TInputDirWizardPage.Initialize(const SubCaption: String; const AppendDir: Boolean; const NewFolderName: String); begin FSubCaptionLabel := TNewStaticText.Create(Self); with FSubCaptionLabel do begin AutoSize := False; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := SubCaption; Parent := Surface; end; FY := WizardForm.AdjustLabelHeight(FSubCaptionLabel) + WizardForm.ScalePixelsY(DefaultBoxTop); FAppendDir := AppendDir; FNewFolderName := NewFolderName; end; function TInputDirWizardPage.Add(const APrompt: String): Integer; var ButtonWidth: Integer; PromptLabel: TNewStaticText; Edit: TEdit; Button: TNewButton; begin ButtonWidth := WizardForm.CalculateButtonWidth([msgButtonWizardBrowse]); if APrompt <> '' then begin PromptLabel := TNewStaticText.Create(Self); with PromptLabel do begin AutoSize := False; Top := FY; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := APrompt; end; SetCtlParent(PromptLabel, Surface); Inc(FY, WizardForm.AdjustLabelHeight(PromptLabel) + WizardForm.ScalePixelsY(16)); end else PromptLabel := nil; Edit := TEdit.Create(Self); with Edit do begin Top := FY; Width := SurfaceWidth-ButtonWidth-WizardForm.ScalePixelsX(10); end; SetCtlParent(Edit, Surface); TryEnableAutoCompleteFileSystem(Edit.Handle); if PromptLabel <> nil then PromptLabel.FocusControl := Edit; Button := TNewButton.Create(Self); with Button do begin Left := SurfaceWidth-ButtonWidth; Top := Edit.Top-1; Width := ButtonWidth; Height := WizardForm.NextButton.Height; if FEdits.Count = 0 then Caption := SetupMessages[msgButtonWizardBrowse] else { Can't use the same accel key for secondary buttons... } Caption := RemoveAccelChar(SetupMessages[msgButtonWizardBrowse]); OnClick := ButtonClick; end; SetCtlParent(Button, Surface); Inc(FY, WizardForm.ScalePixelsY(36)); FButtons.Add(Button); FPromptLabels.Add(PromptLabel); Result := FEdits.Add(Edit); end; function TInputDirWizardPage.GetButton(Index: Integer): TNewButton; begin Result := TNewButton(FButtons[Index]); end; function TInputDirWizardPage.GetEdit(Index: Integer): TEdit; begin Result := TEdit(FEdits[Index]); end; function TInputDirWizardPage.GetPromptLabel(Index: Integer): TNewStaticText; begin Result := TNewStaticText(FPromptLabels[Index]); end; function TInputDirWizardPage.GetValue(Index: Integer): String; begin Result := GetEdit(Index).Text; end; procedure TInputDirWizardPage.SetValue(Index: Integer; const Value: String); begin GetEdit(Index).Text := RemoveBackslashUnlessRoot(PathExpand(Value)); end; {--- InputFile ---} constructor TInputFileWizardPage.Create(AOwner: TComponent); begin inherited; FButtons := TList.Create; FEdits := TList.Create; FInputFileDefaultExtensions := TStringList.Create; FInputFileFilters := TStringList.Create; FPromptLabels := TList.Create; end; destructor TInputFileWizardPage.Destroy; begin FPromptLabels.Free; FInputFileFilters.Free; FInputFileDefaultExtensions.Free; FEdits.Free; FButtons.Free; inherited; end; procedure TInputFileWizardPage.ButtonClick(Sender: TObject); var I: Integer; Edit: TEdit; FileName: String; begin I := FButtons.IndexOf(Sender); if I <> -1 then begin Edit := TEdit(FEdits[I]); FileName := Edit.Text; if (not IsSaveButton[I] and NewGetOpenFileName(RemoveAccelChar(SetupMessages[msgButtonWizardBrowse]), FileName, PathExtractPath(FileName), FInputFileFilters[I], FInputFileDefaultExtensions[I], Surface.Handle)) or (IsSaveButton[I] and NewGetSaveFileName(RemoveAccelChar(SetupMessages[msgButtonWizardBrowse]), FileName, PathExtractPath(FileName), FInputFileFilters[I], FInputFileDefaultExtensions[I], Surface.Handle)) then Edit.Text := FileName; end; end; procedure TInputFileWizardPage.Initialize(const SubCaption: String); begin FSubCaptionLabel := TNewStaticText.Create(Self); with FSubCaptionLabel do begin AutoSize := False; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := SubCaption; Parent := Surface; end; FY := WizardForm.AdjustLabelHeight(FSubCaptionLabel) + WizardForm.ScalePixelsY(DefaultBoxTop); end; function TInputFileWizardPage.Add(const APrompt, AFilter, ADefaultExtension: String): Integer; var ButtonWidth: Integer; PromptLabel: TNewStaticText; Edit: TEdit; Button: TNewButton; begin ButtonWidth := WizardForm.CalculateButtonWidth([msgButtonWizardBrowse]); if APrompt <> '' then begin PromptLabel := TNewStaticText.Create(Self); with PromptLabel do begin AutoSize := False; Top := FY; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := APrompt; end; SetCtlParent(PromptLabel, Surface); Inc(FY, WizardForm.AdjustLabelHeight(PromptLabel) + WizardForm.ScalePixelsY(16)); end else PromptLabel := nil; Edit := TEdit.Create(Self); with Edit do begin Top := FY; Width := SurfaceWidth-ButtonWidth-WizardForm.ScalePixelsX(10); end; SetCtlParent(Edit, Surface); TryEnableAutoCompleteFileSystem(Edit.Handle); if PromptLabel <> nil then PromptLabel.FocusControl := Edit; Button := TNewButton.Create(Self); with Button do begin Left := SurfaceWidth-ButtonWidth; Top := Edit.Top-1; Width := ButtonWidth; Height := WizardForm.NextButton.Height; if FButtons.Count = 0 then Caption := SetupMessages[msgButtonWizardBrowse] else { Can't use the same accel key for secondary buttons... } Caption := RemoveAccelChar(SetupMessages[msgButtonWizardBrowse]); OnClick := ButtonClick; end; SetCtlParent(Button, Surface); Inc(FY, WizardForm.ScalePixelsY(36)); FInputFileFilters.Add(AFilter); FInputFileDefaultExtensions.Add(ADefaultExtension); FButtons.Add(Button); FPromptLabels.Add(PromptLabel); Result := FEdits.Add(Edit); end; function TInputFileWizardPage.GetButton(Index: Integer): TNewButton; begin Result := TNewButton(FButtons[Index]); end; function TInputFileWizardPage.GetEdit(Index: Integer): TEdit; begin Result := TEdit(FEdits[Index]); end; function TInputFileWizardPage.GetPromptLabel(Index: Integer): TNewStaticText; begin Result := TNewStaticText(FPromptLabels[Index]); end; function TInputFileWizardPage.GetValue(Index: Integer): String; begin Result := GetEdit(Index).Text; end; procedure TInputFileWizardPage.SetValue(Index: Integer; const Value: String); begin GetEdit(Index).Text := Value; end; function TInputFileWizardPage.GetIsSaveButton(Index: Integer): Boolean; begin Result := GetButton(Index).Tag = 1; end; procedure TInputFileWizardPage.SetIsSaveButton(Index: Integer; const IsSaveButton: Boolean); begin if IsSaveButton then GetButton(Index).Tag := 1 else GetButton(Index).Tag := 0; end; {--- OutputMsg ---} procedure TOutputMsgWizardPage.Initialize(const Msg: String); begin FMsgLabel := TNewStaticText.Create(Self); with FMsgLabel do begin AutoSize := False; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := Msg; Parent := Surface; end; WizardForm.AdjustLabelHeight(MsgLabel); end; {--- OutputMsgMemo ---} procedure TOutputMsgMemoWizardPage.Initialize(const SubCaption: String; const Msg: AnsiString); var Y: Integer; begin Y := 0; if SubCaption <> '' then begin FSubCaptionLabel := TNewStaticText.Create(Self); with FSubCaptionLabel do begin AutoSize := False; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultLabelHeight); WordWrap := True; Caption := SubCaption; Parent := Surface; end; Inc(Y, WizardForm.ScalePixelsY(DefaultBoxTop) + WizardForm.AdjustLabelHeight(FSubCaptionLabel)); end else FSubCaptionLabel := nil; FRichEditViewer := TRichEditViewer.Create(Self); with FRichEditViewer do begin Top := Y; Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(DefaultBoxBottom) - Y; ReadOnly := True; ScrollBars := ssVertical; WantReturns := False; end; SetCtlParent(FRichEditViewer, Surface); with FRichEditViewer do begin UseRichEdit := True; RTFText := Msg; end; end; {--- OutputProgress ---} constructor TOutputProgressWizardPage.Create(AOwner: TComponent); begin inherited; Style := Style + [psAlwaysSkip, psNoButtons]; end; procedure TOutputProgressWizardPage.Initialize; begin FMsg1Label := TNewStaticText.Create(Self); with FMsg1Label do begin AutoSize := False; ShowAccelChar := False; Width := SurfaceWidth; Height := WizardForm.StatusLabel.Height; WordWrap := WizardForm.StatusLabel.WordWrap; Parent := Surface; end; FMsg2Label := TNewStaticText.Create(Self); with FMsg2Label do begin AutoSize := False; ForceLTRReading := True; ShowAccelChar := False; Top := WizardForm.ScalePixelsY(16); Width := SurfaceWidth; Height := WizardForm.FileNameLabel.Height; end; SetCtlParent(FMsg2Label, Surface); FProgressBar := TNewProgressBar.Create(Self); with FProgressBar do begin Top := WizardForm.ScalePixelsY(42); Width := SurfaceWidth; Height := WizardForm.ScalePixelsY(21); Visible := False; end; SetCtlParent(FProgressBar, Surface); end; procedure TOutputProgressWizardPage.Hide; begin if (WizardForm.CurPageID = ID) and (FSavePageID <> 0) then begin SetMessageBoxCallbackFunc(nil, 0); SetAppTaskbarProgressState(tpsNoProgress); WizardForm.SetCurPage(FSavePageID); FSavePageID := 0; end; end; procedure TOutputProgressWizardPage.ProcessMsgs; { Process messages to repaint and keep Windows from thinking the process is hung. This is safe; due to the psNoButtons style the user shouldn't be able to cancel or do anything else during this time. } begin if WizardForm.CurPageID = ID then Application.ProcessMessages; end; procedure TOutputProgressWizardPage.SetProgress(const Position, Max: Longint); begin if Max > 0 then begin FProgressBar.Max := Max; FProgressBar.Position := Position; FProgressBar.Visible := True; SetAppTaskbarProgressState(tpsNormal); SetAppTaskbarProgressValue(Position, Max); end else begin FProgressBar.Visible := False; SetAppTaskbarProgressState(tpsNoProgress); end; ProcessMsgs; end; procedure TOutputProgressWizardPage.SetText(const Msg1, Msg2: String); begin FMsg1Label.Caption := Msg1; FMsg2Label.Caption := MinimizePathName(Msg2, FMsg2Label.Font, FMsg2Label.Width); ProcessMsgs; end; procedure OutputProgressWizardPageMessageBoxCallback(const Flags: LongInt; const After: Boolean; const Param: LongInt); const States: array [TNewProgressBarState] of TTaskbarProgressState = (tpsNormal, tpsError, tpsPaused); var OutputProgressWizardPage: TOutputProgressWizardPage; NewState: TNewProgressBarState; begin OutputProgressWizardPage := TOutputProgressWizardPage(Param); if After then NewState := npbsNormal else if (Flags and MB_ICONSTOP) <> 0 then NewState := npbsError else NewState := npbsPaused; with OutputProgressWizardPage.ProgressBar do begin State := NewState; Invalidate; end; SetAppTaskbarProgressState(States[NewState]); end; procedure TOutputProgressWizardPage.Show; begin if WizardForm.CurPageID <> ID then begin FSavePageID := WizardForm.CurPageID; WizardForm.SetCurPage(ID); SetMessageBoxCallbackFunc(OutputProgressWizardPageMessageBoxCallback, LongInt(Self)); ProcessMsgs; end; end; end.
unit ChatHandlerPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Protocol; type TOnMessageComposed = procedure( Msg : string ) of object; TOnMessageCompositionChanged = procedure( State : TMsgCompositionState ) of object; type TChatHandlerPanel = class( TCustomPanel ) public constructor Create( anOwner : TComponent ); override; private fChatLines : TMemo; fTextInput : TMemo; fSplitter : TSplitter; public procedure DisplayMsg( From, Msg : string ); private fOnMessageComposed : TOnMessageComposed; fOnMessageCompositionChanged : TOnMessageCompositionChanged; public property OnMessageComposed : TOnMessageComposed write fOnMessageComposed; property OnMessageCompositionChanged : TOnMessageCompositionChanged write fOnMessageCompositionChanged; private procedure OnKeyUp( Sender: TObject; var Key: Word; Shift : TShiftState ); end; implementation // TChatHandlerPanel constructor TChatHandlerPanel.Create( anOwner : TComponent ); const BackgroundColor = $99BBBB; var Panel : TPanel; begin inherited; BevelInner := bvNone; BevelOuter := bvNone; Color := BackgroundColor; BorderWidth := 0; // Create TextInput memo fTextInput := TMemo.Create( self ); fTextInput.BorderStyle := bsNone; fTextInput.Color := $BBDDDD; fTextInput.ParentCtl3D := false; fTextInput.Ctl3D := false; fTextInput.Font.Name := 'Verdana'; fTextInput.Font.Size := 10; fTextInput.Height := 60; fTextInput.Align := alBottom; fTextInput.Alignment := taCenter; fTextInput.OnKeyUp := OnKeyUp; InsertControl( fTextInput ); // Crete Splitter fSplitter := TSplitter.Create( self ); fSplitter.Beveled := false; fSplitter.Color := BackgroundColor; fSplitter.Height := 3; fSplitter.Align := alBottom; fSplitter.Cursor := crHSplit; InsertControl( fSplitter ); // Create ChatLines border panel Panel := TPanel.Create( self ); Panel.Align := alClient; Panel.BevelInner := bvNone; Panel.BevelOuter := bvNone; Panel.Color := BackgroundColor; Panel.BorderWidth := 7; InsertControl( Panel ); // Create ChatLines memo fChatLines := TMemo.Create( self ); fChatLines.BorderStyle := bsNone; fChatLines.Color := BackgroundColor; fChatLines.Font.Name := 'Verdana'; fChatLines.Font.Size := 10; fChatLines.Height := 3; fChatLines.Align := alClient; Panel.InsertControl( fChatLines ); end; procedure TChatHandlerPanel.DisplayMsg( From, Msg : string ); begin fChatLines.Lines.Add( From + ': ' + Msg ); end; procedure TChatHandlerPanel.OnKeyUp( Sender: TObject; var Key: Word; Shift : TShiftState ); var text : string; p : integer; begin if Key = vk_Return then begin text := fTextInput.Text; p := pos( #$D#$A, text ); if p > 0 then delete( text, p, 2 ); if assigned(fOnMessageComposed) then fOnMessageComposed( text ); fTextInput.Clear; end; end; end.
PROGRAM Prime(INPUT, OUTPUT); { Программа находит простые числа в заданном диапазоне } CONST MinNumber = 2; MaxNumber = 100; TYPE Numbers = SET OF MinNumber .. MaxNumber; VAR NumberInSieve, Prime: INTEGER; Sieve: Numbers; BEGIN {Prime} Sieve := [MinNumber .. MaxNumber]; Prime := MinNumber; // First prime WRITELN('Primes in range up to ', MaxNumber, ' will be: '); WHILE Sieve <> [] DO BEGIN IF Prime IN Sieve THEN BEGIN WRITE(Prime, ' '); NumberInSieve := Prime; // Init number WHILE NumberInSieve <= MaxNumber DO BEGIN Sieve := Sieve - [NumberInSieve]; NumberInSieve := NumberInSieve + Prime; // Number is already multiple to Prime END END; Prime := Prime + 1 END; WRITELN END. {Prime}
unit uMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, BaseForms, StdCtrls, ExtCtrls; type TMainForm = class(TBaseForm) btnNewModalForm: TButton; lblModalResult: TLabel; btnNewFormWithFreeOnClose: TButton; btnTestAutoFree: TButton; memAutoFreeObjsLog: TMemo; btnTestAutoFree2: TButton; Bevel1: TBevel; procedure btnNewModalFormClick(Sender: TObject); procedure btnNewFormWithFreeOnCloseClick(Sender: TObject); procedure btnTestAutoFreeClick(Sender: TObject); procedure btnTestAutoFree2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; procedure LogAF(const Msg: string); implementation {$R *.dfm} uses uSomeForm, uAutoFreeObjsForm; procedure LogAF(const Msg: string); begin MainForm.memAutoFreeObjsLog.Lines.Add(Msg); end; procedure TMainForm.btnNewModalFormClick(Sender: TObject); var Result: TModalResult; begin with TSomeForm.Create(Self) do try Result := ShowModal; lblModalResult.Caption := 'ModalResult = ' + IntToStr(Result); finally Free; end; end; procedure TMainForm.btnTestAutoFree2Click(Sender: TObject); begin memAutoFreeObjsLog.Lines.Clear; TTestAutoFree.Create(Self).ShowModal; end; procedure TMainForm.btnTestAutoFreeClick(Sender: TObject); begin memAutoFreeObjsLog.Lines.Clear; TTestAutoFree.Create(Self).Show; end; procedure TMainForm.btnNewFormWithFreeOnCloseClick(Sender: TObject); begin with TSomeForm.Create(Self) do begin FreeOnClose := True; Show; end; end; end.
unit glr_mesh; {$i defines.inc} interface uses glr_render, glr_scene, glr_utils; {$REGION ' .OBJ mesh file format specific types '} type TglrObjFace = record v, vt, vn: array[0..2] of LongWord; end; TglrObjFaceList = TglrList<TglrObjFace>; TglrObjIndex = record v, vn, vt: LongWord; end; TglrObjIndexList = TglrList<TglrObjIndex>; TglrObjRawSubMeshData = class Name: AnsiString; f: TglrObjFaceList; constructor Create(); virtual; destructor Destroy(); override; end; TglrObjRawSubMeshDataList = TglrObjectList<TglrObjRawSubMeshData>; TglrObjRawMeshData = class public v, vn: TglrVec3fList; vt: TglrVec2fList; subs: TglrObjRawSubMeshDataList; constructor Create(); virtual; destructor Destroy(); override; end; { TglrMeshData } {$ENDREGION} {$REGION ' Mesh '} TglrSubMeshData = record name: AnsiString; start, count: LongWord; end; TglrMeshData = record vBuffer: TglrVertexBuffer; iBuffer: TglrIndexBuffer; vData, iData: Pointer; vLength, iLength: LongWord; subMeshes: array of TglrSubMeshData; procedure FreeMemory(); end; // RawGlr - Internal framework format // Obj - Wavefront .obj format TglrMeshFormat = (mfRawGlr, mfObj); TglrMesh = class (TglrNode) public Data: TglrMeshData; constructor Create(aStream: TglrStream; aFormat: TglrMeshFormat; aFreeStreamOnFinish: Boolean = True); virtual; overload; constructor Create(); override; overload; destructor Destroy(); override; end; {$ENDREGION} implementation uses glr_resload; { TglrObjRawSubMeshData } constructor TglrObjRawSubMeshData.Create; begin inherited; Name := ''; f := TglrObjFaceList.Create(32); end; destructor TglrObjRawSubMeshData.Destroy; begin f.Free(); inherited Destroy; end; { TglrObjRawMeshData } constructor TglrObjRawMeshData.Create; begin inherited; v := TglrVec3fList.Create(32); vn := TglrVec3fList.Create(32); vt := TglrVec2fList.Create(32); subs := TglrObjRawSubMeshDataList.Create(1); end; destructor TglrObjRawMeshData.Destroy; begin v.Free(); vn.Free(); vt.Free(); inherited Destroy; end; { TglrMeshData } procedure TglrMeshData.FreeMemory; begin if (vData <> nil) then FreeMem(vData); if (iData <> nil) then FreeMem(iData); vData := nil; iData := nil; end; { TglrMesh } constructor TglrMesh.Create(aStream: TglrStream; aFormat: TglrMeshFormat; aFreeStreamOnFinish: Boolean); begin inherited Create(); Data := LoadMesh(aStream, aFormat); if aFreeStreamOnFinish then aStream.Free(); end; constructor TglrMesh.Create; begin inherited Create; FillChar(Data, SizeOf(TglrMeshData), 0); end; destructor TglrMesh.Destroy; begin Data.FreeMemory(); if Assigned(Data.vBuffer) then Data.vBuffer.Free(); if Assigned(Data.iBuffer) then Data.iBuffer.Free(); inherited Destroy; end; end.
program FeldSort3 (input, output); { sortiert ein einzulesendes Feld von integer-Zahlen } const MAX = 100; type tIndex = 1..MAX; tFeld = array[tIndex] of integer; var EingabeFeld : tFeld; idx : tIndex; Groesse : integer; procedure FeldSortieren (inSortLaenge : tIndex; var ioSortFeld : tFeld); var MinPos, i : tIndex; function FeldMinimumPos (Feld : tFeld; von, bis : tIndex) : tIndex; var MinimumPos, j : tIndex; begin MinimumPos := von; for j := von + 1 to bis do if Feld[j] < Feld[MinimumPos] then MinimumPos := j; FeldMinimumPos := MinimumPos; end; { FeldMinimumPos } procedure vertauschen (var ioHin, ioHer : integer); var Tausch : integer; begin Tausch := ioHin; ioHin := ioHer; ioHer := Tausch end; { vertauschen } begin for i := 1 to inSortLaenge - 1 do begin MinPos := FeldMinimumPos(ioSortFeld, i, inSortLaenge); vertauschen (ioSortFeld[MinPos], ioSortFeld[i]); end end; { FeldSortieren } begin { Feld einlesen } repeat write ('Anzahl Werte: (max. 100) '); readln(Groesse); until (1 <= Groesse) and (Groesse <= MAX); for idx := 1 to Groesse do begin write (idx, '. Wert: '); readln (EingabeFeld[idx]); end; { Feld sortieren } FeldSortieren (Groesse, EingabeFeld); { sortiertes Feld ausgeben } for idx := 1 to Groesse do write (EingabeFeld[idx]:6); writeln; end. { FeldSort3 }
unit Animations; interface uses Windows, Classes, TimerTypes, ShutDown, VCLUtils; type IAnimationTarget = interface function IsCyclic : boolean; function CurrentFrame : integer; function FrameCount : integer; function FrameDelay(frame : integer) : integer; procedure AnimationTick(frame : integer); function IsEqualTo(const AnimTarget : IAnimationTarget) : boolean; function GetObject : TObject; end; type IAnimationCache = interface ['{F0ECCE60-881C-11d4-9147-0048546B6CD9}'] procedure StartCaching; procedure StopCaching; procedure AddAnimationRect(const which : TRect); end; type TAnimManagerNotification = procedure of object; type TTargetCheck = function (const Target : IAnimationTarget; info : array of const) : boolean; type TAnimationManager = class(TInterfacedObject, IShutDownTarget, ITickeable) public constructor Create; destructor Destroy; override; procedure DestroyAll; private fCache : IAnimationCache; fOnAnimationCycleStart : TAnimManagerNotification; fOnAnimationCycleEnd : TAnimManagerNotification; fEnabled : boolean; public property Cache : IAnimationCache read fCache write fCache; private // IShutDownTarget procedure IShutDownTarget.OnSuspend = Suspend; procedure IShutDownTarget.OnResume = Resume; function GetPriority : integer; procedure OnShutDown; private function Enabled : boolean; function Tick : integer; public procedure AddTargets(const which : array of IAnimationTarget); procedure RemoveTargets(const which : array of IAnimationTarget); procedure CheckRemoveTargets(Check : TTargetCheck; info : array of const); procedure Clear; procedure DeleteAll(const _class : array of TClass); procedure Suspend; procedure Resume; public property OnAnimationCycleStart : TAnimManagerNotification write fOnAnimationCycleStart; property OnAnimationCycleEnd : TAnimManagerNotification write fOnAnimationCycleEnd; private fTargets : TList; function SearchTarget(const which : IAnimationTarget) : pointer; // TTargetInfo end; implementation uses SysUtils, TimerTicker; type TTargetInfo = class public constructor Create(Owner : TAnimationManager; const target : IAnimationTarget; StartTick : integer); private fOwner : TAnimationManager; fTarget : IAnimationTarget; fHighFrame : integer; fStartFrame : integer; fCurrentFrame : integer; fLastUpdate : integer; fEnabled : boolean; //fVisible : boolean; //*** function Tick(CurrentTick : integer) : integer; end; // Utils procedure FreeObject(var which); var aux : TObject; begin aux := TObject(which); TObject(which) := nil; aux.Free; end; // TTargetInfo constructor TTargetInfo.Create(Owner : TAnimationManager; const target : IAnimationTarget; StartTick : integer); begin inherited Create; fOwner := Owner; fTarget := target; fHighFrame := pred(target.FrameCount); fStartFrame := target.CurrentFrame; if (fStartFrame < 0) or (fStartFrame > fHighFrame) then raise Exception.Create('(fStartFrame < 0) or (fStartFrame > fHighFrame)'); fCurrentFrame := fStartFrame; fLastUpdate := StartTick; fEnabled := true; end; function TTargetInfo.Tick(CurrentTick : integer) : integer; var ElapsedTicks : integer; FrameDelay : integer; begin ElapsedTicks := CurrentTick - fLastUpdate; FrameDelay := fTarget.FrameDelay(fCurrentFrame); if ElapsedTicks >= FrameDelay then begin if fCurrentFrame < fHighFrame then inc(fCurrentFrame) else fCurrentFrame := 0; try fTarget.AnimationTick(fCurrentFrame); except end; fLastUpdate := CurrentTick; if (fCurrentFrame = fHighFrame) and not fTarget.IsCyclic then begin fEnabled := false; Result := high(Result); end else Result := fTarget.FrameDelay(fCurrentFrame); end else Result := FrameDelay - ElapsedTicks; end; // TAnimationManager const cAnimTimerInterval = 60; constructor TAnimationManager.Create; begin inherited Create; fTargets := TList.Create; AttachTickeable(Self); Shutdown.AttachTarget(Self); end; destructor TAnimationManager.Destroy; begin DestroyAll; inherited; end; procedure TAnimationManager.DestroyAll; begin if fTargets<>nil then begin Clear; FreeAndNil(fTargets); Shutdown.DetachTarget(Self); fCache := nil; DetachTickeable(Self); end; end; function TAnimationManager.GetPriority : integer; begin Result := 100; end; procedure TAnimationManager.OnShutDown; begin fEnabled := false; end; function TAnimationManager.Enabled : boolean; begin Result := fEnabled; end; function TAnimationManager.Tick : integer; var aux : TTargetInfo; mininterval : integer; desinterval : integer; i : integer; begin if assigned(fCache) then fCache.StartCaching; if assigned(fOnAnimationCycleStart) then fOnAnimationCycleStart; try mininterval := high(mininterval); for i := 0 to pred(fTargets.Count) do begin aux := TTargetInfo(fTargets[i]); if (aux <> nil) and aux.fEnabled then begin try desinterval := aux.Tick(GetTickCount); except end; if desinterval < mininterval then mininterval := desinterval; end; end; if (mininterval > 0) and (mininterval < 2*cTimerInterval) then Result := mininterval else Result := cAnimTimerInterval; finally fTargets.Pack; if Assigned(fOnAnimationCycleEnd) then fOnAnimationCycleEnd; if assigned(fCache) then fCache.StopCaching; end; end; procedure TAnimationManager.AddTargets(const which : array of IAnimationTarget); var i : integer; begin for i := low(which) to high(which) do fTargets.Add(TTargetInfo.Create(Self, which[i], GetTickCount)); fEnabled := fTargets.Count > 0; end; procedure TAnimationManager.RemoveTargets(const which : array of IAnimationTarget); var i : integer; aux : TTargetInfo; begin for i := low(which) to high(which) do begin aux := TTargetInfo(SearchTarget(which[i])); if aux <> nil then begin fTargets.Remove(aux); aux.Free; end; end; end; procedure TAnimationManager.CheckRemoveTargets(Check : TTargetCheck; info : array of const); var i : integer; aux : TTargetInfo; begin for i := 0 to pred(fTargets.Count) do begin aux := TTargetInfo(fTargets[i]); if (aux <> nil) and Check(aux.fTarget, info) then aux.fEnabled := false; end; end; procedure TAnimationManager.Clear; var i : integer; aux : TTargetInfo; begin fEnabled := false; for i := pred(fTargets.Count) downto 0 do begin aux := TTargetInfo(fTargets[i]); if aux <> nil then begin fTargets[i] := nil; aux.Free; end; end; fTargets.Pack; end; procedure TAnimationManager.DeleteAll(const _class : array of TClass); var i : integer; aux : TTargetInfo; lclass : TClass; j : integer; begin fEnabled := false; try for i := pred(fTargets.Count) downto 0 do begin aux := TTargetInfo(fTargets[i]); if (aux <> nil) then begin lclass := aux.fTarget.GetObject.ClassType; j := low(_class); while j<high(_class) do begin if _class[j]=lclass then begin fTargets[i] := nil; aux.Free; j := high(_class); end else inc(j); end; end; end; except end; fTargets.Pack; end; procedure TAnimationManager.Suspend; begin fEnabled := false; end; procedure TAnimationManager.Resume; begin fEnabled := fTargets.Count > 0; end; function TAnimationManager.SearchTarget(const which : IAnimationTarget) : pointer; // TTargetInfo var res : TTargetInfo absolute Result; i : integer; begin assert(fTargets.Count > 0); i := 0; res := nil; while (i < fTargets.Count) and (res = nil) do begin res := TTargetInfo(fTargets[i]); if (res <> nil) and (res.fTarget <> which) then begin res := nil; inc(i); end; end; end; end.
unit myIntegerListTests; interface uses TestFramework ; type TmyIntegerListTests = class(TTestCase) published procedure ListAdd; procedure ListInsert; procedure ListDelete; procedure ListCount; procedure ListItem; procedure QCTicket1; end;//TmyIntegerListTests implementation uses System.SysUtils, myIntegerList ; procedure TmyIntegerListTests.ListAdd; var l_List : TmyIntegerList; begin l_List := TmyIntegerList.Create; try l_List.Add(Random(1000)); finally FreeAndNil(l_List); end;//try..finally end; procedure TmyIntegerListTests.ListInsert; var l_List : TmyIntegerList; begin l_List := TmyIntegerList.Create; try l_List.Insert(0, Random(1000)); finally FreeAndNil(l_List); end;//try..finally end; procedure TmyIntegerListTests.ListDelete; var l_List : TmyIntegerList; begin l_List := TmyIntegerList.Create; try l_List.Delete(0); finally FreeAndNil(l_List); end;//try..finally end; procedure TmyIntegerListTests.ListCount; var l_List : TmyIntegerList; begin l_List := TmyIntegerList.Create; try Check(l_List.Count = 0, 'Пустой список должен содержать 0 элементов'); finally FreeAndNil(l_List); end;//try..finally end; procedure TmyIntegerListTests.ListItem; var l_List : TmyIntegerList; begin l_List := TmyIntegerList.Create; try l_List.Item[0]; finally FreeAndNil(l_List); end;//try..finally end; procedure TmyIntegerListTests.QCTicket1; var l_List : TmyIntegerList; begin l_List := TmyIntegerList.Create; try l_List.Add(Random(54365)); l_List.Delete(0); finally FreeAndNil(l_List); end;//try..finally end; initialization TestFramework.RegisterTest(TmyIntegerListTests.Suite); end.
unit email_validator_adapter; interface uses RegularExpressions, email_validator_intf; type TEmailValidatorAdapter = class(TInterfacedObject, IEmailValidator) function isValid(const email: String): Boolean; public class function New: IEmailValidator; end; implementation function TEmailValidatorAdapter.isValid(const email: String): Boolean; var RegEx: TRegEx; begin RegEx := TRegEx.Create('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]*[a-zA-Z0-9]+$'); Result := RegEx.Match(email).Success; end; class function TEmailValidatorAdapter.New: IEmailValidator; begin Result := Self.Create; end; end.
unit GX_ePopupMenu; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, GX_BaseForm, GX_BaseExpert; type TfmEditorPopupMenuExpertConfig = class(TfmBaseForm) pc_Main: TPageControl; ts_Experts: TTabSheet; ts_EditorExperts: TTabSheet; lb_EditorExperts: TListBox; lb_Experts: TListBox; lv_Selected: TListView; b_Ok: TButton; b_Cancel: TButton; b_Add: TButton; b_Remove: TButton; l_DuplicateShortcuts: TLabel; b_Default: TButton; b_ClearShortcut: TButton; chk_FocusEditor: TCheckBox; procedure b_AddClick(Sender: TObject); procedure b_RemoveClick(Sender: TObject); procedure lb_EditorExpertsDblClick(Sender: TObject); procedure lb_ExpertsDblClick(Sender: TObject); procedure lv_SelectedEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure lv_SelectedEdited(Sender: TObject; Item: TListItem; var s: string); procedure lv_SelectedDblClick(Sender: TObject); procedure lv_SelectedKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure lv_SelectedChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure b_DefaultClick(Sender: TObject); procedure b_ClearShortcutClick(Sender: TObject); private function GetExpertIndex(const _ListView: TListView; const _Expert: TGX_BaseExpert): Integer; procedure CheckForDuplicates; procedure GetData(_sl: TStringList; out _ForceEdiorActive: Boolean); procedure SetData(_sl: TStringList; _ForceEdiorActive: Boolean); procedure AddExpert(const _Key: string; const _ExpName: string; _Expert: TGX_BaseExpert); procedure RemoveExpert; procedure AddSelectedExpert; procedure AddSelectedEditorExpert; procedure EnableOKCancel; public constructor Create(_Owner: TComponent); override; end; implementation {$R *.dfm} uses Menus, StrUtils, GX_EditorExpert, GX_ConfigurationInfo, GX_dzVclUtils, GX_GExperts, GX_EditorExpertManager, GX_Experts, GX_MessageBox, GX_OtaUtils; type TGxEditorPopupMenuExpert = class(TEditorExpert) private FFormHeight: Integer; FGExpertsShortcutMenu: TPopupMenu; FShortcuts: TStringList; FForceEditorActive: Boolean; procedure ShowConfigForm(_Sender: TObject); class procedure SetDefaults(_sl: TStringList); function IsEditorActive(out ctl: TWinControl): Boolean; protected function GetDisplayName: string; override; class function GetName: string; override; public constructor Create; override; destructor Destroy; override; procedure Configure; override; procedure Execute(Sender: TObject); override; function GetDefaultShortCut: TShortCut; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; end; { TGxEditorPopupMenuExpert } procedure TGxEditorPopupMenuExpert.Configure; var frm: TfmEditorPopupMenuExpertConfig; begin frm := TfmEditorPopupMenuExpertConfig.Create(nil); try frm.SetData(FShortcuts, FForceEditorActive); frm.Height := FFormHeight; if frm.ShowModal <> mrok then Exit; frm.GetData(FShortcuts, FForceEditorActive); FFormHeight := frm.Height; finally FreeAndNil(frm); end; end; constructor TGxEditorPopupMenuExpert.Create; begin inherited; FShortcuts := TStringList.Create; FForceEditorActive := True; end; destructor TGxEditorPopupMenuExpert.Destroy; begin FreeAndNil(FGExpertsShortcutMenu); FreeAndNil(FShortcuts); inherited; end; function TGxEditorPopupMenuExpert.IsEditorActive(out ctl: TWinControl): Boolean; begin ctl := Screen.ActiveControl; Result := Assigned(ctl) and (ctl.Name = 'Editor') and ctl.ClassNameIs('TEditControl'); end; procedure TGxEditorPopupMenuExpert.Execute(Sender: TObject); var ctl: TWinControl; pnt: TPoint; i: Integer; Key: string; idx: Integer; ExpName: string; Expert: TGX_BaseExpert; EditorForm: TCustomForm; EditorControl: TComponent; begin if not IsEditorActive(ctl) then begin if not FForceEditorActive then Exit; EditorForm := GxOtaGetTopMostEditView.GetEditWindow.Form; if Assigned(EditorForm) then begin EditorControl := EditorForm.FindComponent('Editor'); if Assigned(EditorControl) and EditorControl.ClassNameIs('TEditControl') then TWinControl_SetFocus(EditorControl as TWinControl); end; end; if not IsEditorActive(ctl) then Exit; if Assigned(FGExpertsShortcutMenu) then FreeAndNil(FGExpertsShortcutMenu); FGExpertsShortcutMenu := TPopupMenu.Create(nil); for i := 0 to FShortcuts.Count - 1 do begin Key := FShortcuts.Names[i]; ExpName := FShortcuts.Values[Key]; if (Key <> '') and (Key <> 'X') then begin if GExpertsInst.EditorExpertManager.FindExpert(ExpName, idx) then begin Expert := GExpertsInst.EditorExpertManager.EditorExpertList[idx]; TPopupMenu_AppendMenuItem(FGExpertsShortcutMenu, '&' + Key + ' ' + Expert.GetDisplayName, Expert.Execute); end else if GExpertsInst.FindExpert(ExpName, idx) then begin Expert := GExpertsInst.ExpertList[idx]; TPopupMenu_AppendMenuItem(FGExpertsShortcutMenu, '&' + Key + ' ' + Expert.GetDisplayName, Expert.Execute); end; end; end; TPopupMenu_AppendMenuItem(FGExpertsShortcutMenu, '&' + 'X' + ' ' + 'Configure', ShowConfigForm); pnt := ctl.ClientToScreen(Point(0, 0)); FGExpertsShortcutMenu.Popup(pnt.X, pnt.Y); end; procedure TGxEditorPopupMenuExpert.ShowConfigForm(_Sender: TObject); begin GExpertsInst.ShowConfigurationForm; end; function TGxEditorPopupMenuExpert.GetDefaultShortCut: TShortCut; begin Result := scCtrl + Ord('H'); end; function TGxEditorPopupMenuExpert.GetDisplayName: string; resourcestring SDisplayName = 'Editor Popup Menu'; begin Result := SDisplayName; end; function TGxEditorPopupMenuExpert.GetHelpString: string; resourcestring SGxEditorPopupMenuExpertHelp = 'Adds a new shortcut to the editor that shows a configurable popup menu ' + 'as an alternative to the GExperts main menu.'; begin Result := SGxEditorPopupMenuExpertHelp; end; class function TGxEditorPopupMenuExpert.GetName: string; const SName = 'EditorPopupMenu'; begin Result := SName; end; function TGxEditorPopupMenuExpert.HasConfigOptions: Boolean; begin Result := True; end; procedure TGxEditorPopupMenuExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited; Settings.ReadBool('ForceEditorActive', FForceEditorActive); FShortcuts.Clear; if Settings.SectionExists('menu') then begin Settings.ReadSectionValues('menu', FShortcuts); end else begin SetDefaults(FShortcuts); end; FFormHeight := Settings.ReadInteger('FormHeight', FFormHeight); end; procedure TGxEditorPopupMenuExpert.InternalSaveSettings(Settings: TExpertSettings); var i: Integer; s: string; MnuSettings: TExpertSettings; begin inherited; Settings.WriteBool('ForceEditorActive', FForceEditorActive); Settings.EraseSection('menu'); MnuSettings := Settings.CreateExpertSettings('menu'); try for i := 0 to FShortcuts.Count - 1 do begin s := FShortcuts.Names[i]; MnuSettings.WriteString(s, FShortcuts.Values[s]); end; finally FreeAndNil(MnuSettings); end; Settings.WriteInteger('FormHeight', FFormHeight); end; class procedure TGxEditorPopupMenuExpert.SetDefaults(_sl: TStringList); begin _sl.Add('A=Align'); _sl.Add('B=BookmarksExpert'); _sl.Add('C=ClassBrowser'); _sl.Add('D=DateTime'); _sl.Add('E=EditorExpertsMenu'); _sl.Add('F=CodeFormatter'); _sl.Add('G=GrepSearch'); _sl.Add('H=ClipboardHistory'); _sl.Add('I=SelectIdent'); _sl.Add('J=SortLines'); _sl.Add('L=CodeLibrarian'); _sl.Add('M=MacroLibrary'); _sl.Add('O=OpenFile'); _sl.Add('P=ProcedureList'); _sl.Add('R=ReverseStatement'); _sl.Add('S=MessageDialog'); _sl.Add('T=MacroTemplates'); _sl.Add('U=UsesClauseMgr'); _sl.Add('X=Configure'); end; { TfmEditorPopupMenuExpertConfig } constructor TfmEditorPopupMenuExpertConfig.Create(_Owner: TComponent); var i: Integer; EdExpManager: TGxEditorExpertManager; Expert: TGX_BaseExpert; begin inherited; TControl_SetMinConstraints(Self); Self.Constraints.MaxWidth := Self.Width; for i := 0 to GExpertsInst.ExpertCount - 1 do begin Expert := GExpertsInst.ExpertList[i]; lb_Experts.Items.AddObject(Expert.GetDisplayName, Expert); end; EdExpManager := GExpertsInst.EditorExpertManager; for i := 0 to EdExpManager.EditorExpertCount - 1 do begin Expert := EdExpManager.EditorExpertList[i]; if not (Expert is TGxEditorPopupMenuExpert) then lb_EditorExperts.Items.AddObject(Expert.GetDisplayName, Expert); end; end; procedure TfmEditorPopupMenuExpertConfig.EnableOKCancel; begin b_Ok.Enabled := True; b_Cancel.Enabled := True; end; procedure TfmEditorPopupMenuExpertConfig.AddSelectedEditorExpert; var ExpName: string; Ex: TEditorExpert; begin TListBox_GetSelectedObject(lb_EditorExperts, Pointer(Ex)); ExpName := Ex.GetName; AddExpert('', ExpName, Ex); end; procedure TfmEditorPopupMenuExpertConfig.AddSelectedExpert; var ExpName: string; Ex: TGX_Expert; begin TListBox_GetSelectedObject(lb_Experts, Pointer(Ex)); ExpName := Ex.GetName; AddExpert('', ExpName, Ex); end; procedure TfmEditorPopupMenuExpertConfig.b_AddClick(Sender: TObject); begin if pc_Main.ActivePage = ts_Experts then begin AddSelectedExpert; end else begin AddSelectedEditorExpert; end; end; // --------------------------------------------- type TClearIndividualShortcutMessage = class(TGxQuestionBoxAdaptor) protected function GetMessage: string; override; end; { TClearIndividualShortcutMessage } function TClearIndividualShortcutMessage.GetMessage: string; resourcestring SClearIndividualShortcut = 'This will remove the shortcut assigned to the individual expert. So this expert can ' + 'only be called via the GExperts main menu and via this editor menu. ' + 'Do you want to clear the shortcut?'; begin Result := SClearIndividualShortcut; end; procedure TfmEditorPopupMenuExpertConfig.b_ClearShortcutClick(Sender: TObject); var li: TListItem; Ex: TGX_BaseExpert; begin if ShowGxMessageBox(TClearIndividualShortcutMessage) <> mrYes then Exit; if not TListView_TryGetSelected(lv_Selected, li) then Exit; Ex := TGX_BaseExpert(li.Data); Ex.ShortCut := 0 end; procedure TfmEditorPopupMenuExpertConfig.b_RemoveClick(Sender: TObject); begin RemoveExpert; end; procedure TfmEditorPopupMenuExpertConfig.b_DefaultClick(Sender: TObject); var sl: TStringList; begin sl := TStringList.Create; try TGxEditorPopupMenuExpert.SetDefaults(sl); SetData(sl, True); finally FreeAndNil(sl); end; end; procedure TfmEditorPopupMenuExpertConfig.CheckForDuplicates; var i: Integer; sl: TStringList; DupeFound: Boolean; Dummy: Boolean; begin sl := TStringList.Create; try GetData(sl, Dummy); sl.Sort; DupeFound := False; for i := 1 to sl.Count - 1 do if sl.Names[i] = sl.Names[i - 1] then begin DupeFound := True; break; end; l_DuplicateShortcuts.Visible := DupeFound; finally FreeAndNil(sl); end; end; function TfmEditorPopupMenuExpertConfig.GetExpertIndex( const _ListView: TListView; const _Expert: TGX_BaseExpert): Integer; var i: Integer; begin Result := -1; if not Assigned(_ListView) then Exit; if not Assigned(_Expert) then Exit; for i := 0 to _ListView.Items.Count - 1 do begin if _ListView.Items[i].Data = _Expert then begin Result := i; break; end; end; end; procedure TfmEditorPopupMenuExpertConfig.AddExpert(const _Key: string; const _ExpName: string; _Expert: TGX_BaseExpert); var li: TListItem; begin if GetExpertIndex(lv_Selected, _Expert) >= 0 then begin Exit; // expert is already in "lv_Selected" end; li := lv_Selected.Items.Add; if _Key <> '' then li.Caption := _Key else li.Caption := LeftStr(_ExpName, 1); li.Data := _Expert; li.SubItems.Add(_Expert.GetDisplayName); CheckForDuplicates; end; procedure TfmEditorPopupMenuExpertConfig.GetData(_sl: TStringList; out _ForceEdiorActive: Boolean); var i: Integer; li: TListItem; begin _ForceEdiorActive := chk_FocusEditor.Checked; _sl.Clear; for i := 0 to lv_Selected.Items.Count - 1 do begin li := lv_Selected.Items[i]; if Assigned(li.Data) then begin if TObject(li.Data) is TGX_BaseExpert then _sl.Add(li.Caption + '=' + TGX_BaseExpert(li.Data).GetName); end; end; end; procedure TfmEditorPopupMenuExpertConfig.lb_EditorExpertsDblClick(Sender: TObject); begin AddSelectedEditorExpert; end; procedure TfmEditorPopupMenuExpertConfig.lb_ExpertsDblClick(Sender: TObject); begin AddSelectedExpert; end; procedure TfmEditorPopupMenuExpertConfig.lv_SelectedChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin case Change of ctState, ctText: EnableOKCancel; end; CheckForDuplicates; end; procedure TfmEditorPopupMenuExpertConfig.lv_SelectedDblClick(Sender: TObject); begin RemoveExpert; end; procedure TfmEditorPopupMenuExpertConfig.lv_SelectedEdited(Sender: TObject; Item: TListItem; var s: string); begin EnableOKCancel; CheckForDuplicates; end; procedure TfmEditorPopupMenuExpertConfig.lv_SelectedEditing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); begin b_Ok.Enabled := False; b_Cancel.Enabled := False; end; procedure TfmEditorPopupMenuExpertConfig.lv_SelectedKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var li: TListItem; begin if Key = VK_F2 then begin li := lv_Selected.Selected; if Assigned(li) then li.EditCaption; Key := 0; end; end; procedure TfmEditorPopupMenuExpertConfig.RemoveExpert; begin if lv_Selected.ItemIndex = -1 then Exit; lv_Selected.DeleteSelected; CheckForDuplicates; end; procedure TfmEditorPopupMenuExpertConfig.SetData(_sl: TStringList; _ForceEdiorActive: Boolean); var i: Integer; Key: string; ExpName: string; idx: Integer; begin chk_FocusEditor.Checked := _ForceEdiorActive; lv_Selected.OnChange := nil; lv_Selected.Items.BeginUpdate; try lv_Selected.Clear; for i := 0 to _sl.Count - 1 do begin Key := _sl.Names[i]; ExpName := _sl.Values[Key]; if GExpertsInst.FindExpert(ExpName, idx) then begin AddExpert(Key, ExpName, GExpertsInst.ExpertList[idx]); end else if GExpertsInst.EditorExpertManager.FindExpert(ExpName, idx) then begin AddExpert(Key, ExpName, GExpertsInst.EditorExpertManager.EditorExpertList[idx]); end; end; finally lv_Selected.Items.EndUpdate; lv_Selected.OnChange := lv_SelectedChange; end; end; initialization RegisterEditorExpert(TGxEditorPopupMenuExpert); end.
unit UClasses; interface uses Classes; type TOwnedPersistent = class(TPersistent) private fOwner: TPersistent; protected function GetOwner: TPersistent; override; procedure CheckOwnerType(aOwner: TPersistent; const Allowed: array of TClass); function FindOwner(aClass: TClass): TPersistent; function GetMaster: TPersistent; public constructor Create(aOwner: TPersistent); property Owner: TPersistent read fOwner; end; implementation uses (*ULog,*) UMisc; { TOwnedPersistent } procedure TOwnedPersistent.CheckOwnerType(aOwner: TPersistent; const Allowed: array of TClass); var i: integer; OK: boolean; S: string; begin OK := False; for i := 0 to Length(Allowed) - 1 do begin if Allowed[i] <> nil then OK := OK or (aOwner is Allowed[i]) else OK := True; if OK then Break; end; if not OK then begin if aOwner <> nil then S := aOwner.ClassName else S := 'nil'; AppErrorFmt('CheckOwnerType: %s is een ongeldig Owner type',[S], Self); end; end; constructor TOwnedPersistent.Create(aOwner: TPersistent); begin fOwner := aOwner; end; function TOwnedPersistent.GetOwner: TPersistent; begin Result := fOwner; end; type THackedPersistent = class(TPersistent); function TOwnedPersistent.FindOwner(aClass: TClass): TPersistent; var O: TPersistent; begin O := Self; Result := nil; while O <> nil do begin O := THackedPersistent(O).GetOwner; if O = nil then Exit; if O is aClass then begin Result := O; Exit; end; end; end; function TOwnedPersistent.GetMaster: TPersistent; var O: TPersistent; begin Result := nil; O := Self; while O <> nil do begin O := THackedPersistent(O).GetOwner; if O <> nil then Result := O else Exit; end; Result := nil; end; {procedure TOwnedPersistent.Changed; begin if Assigned(fOnChange) then fOnChange(Self); end; procedure TOwnedPersistent.Change(Sender: TObject); begin Changed; end;} end.
unit SingleDriverRoundTripGenericRequestUnit; interface uses REST.Json.Types, AddressUnit, RouteParametersUnit, GenericParametersUnit; type TSingleDriverRoundTripGenericRequest = class(TGenericParameters) private [JSONNameAttribute('addresses')] FAddresses: TAddressesArray; [JSONNameAttribute('parameters')] FParameters: TRouteParameters; public property Parameters: TRouteParameters read FParameters write FParameters; property Addresses: TAddressesArray read FAddresses write FAddresses; end; implementation end.
{******************************************************************************} {* *} {* TelemetryLog *} {* *} {* Class designed to imitate behavior of telemetry log example *} {* from SCS SDK 1.2 *} {* *} {* ©František Milt 2014-09-29 *} {* *} {* Version 1.0a *} {* *} {******************************************************************************} unit TelemetryLog; interface uses SysUtils, SCS_Telemetry_Condensed, TelemetryCommon, TelemetryIDs, TelemetryStrings, TelemetryRecipient, TelemetryRecipientBinder, SimpleLog; type TTelemetryState = record Timestamp: scs_timestamp_t; RawRenderingTimestamp: scs_timestamp_t; RawSimulationTimestamp: scs_timestamp_t; RawPausedSimulationTimestamp: scs_timestamp_t; OrientationAvailable: Boolean; Heading: Single; Pitch: Single; Roll: Single; Speed: Single; RPM: Single; Gear: Integer; end; {==============================================================================} { TTelemetryLog // Class declaration } {==============================================================================} TTelemetryLog = class(TTelemetryRecipientBinder) private fFormatSettings: TFormatSettings; fLog: TSimpleLog; fOutputPaused: Boolean; fPrintHeader: Boolean; fLastTimestamp: scs_timestamp_t; fTelemetry: TTelemetryState; protected Function InitLog: Boolean; virtual; procedure FinishLog; virtual; public constructor Create(Recipient: TTelemetryRecipient); destructor Destroy; override; procedure LogHandler(Sender: TObject; LogType: scs_log_type_t; const LogText: String); override; procedure EventRegisterHandler(Sender: TObject; Event: scs_event_t); override; procedure EventUnregisterHandler(Sender: TObject; Event: scs_event_t); override; procedure EventHandler(Sender: TObject; Event: scs_event_t; Data: Pointer); override; procedure ChannelRegisterHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t); override; procedure ChannelUnregisterHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t); override; procedure ChannelHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t); override; procedure ConfigHandler(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t); override; published end; implementation uses Windows; {==============================================================================} { TTelemetryLog // Class implementation } {==============================================================================} {------------------------------------------------------------------------------} { TTelemetryLog // Protected routines } {------------------------------------------------------------------------------} Function TTelemetryLog.InitLog: Boolean; begin try fLog.InMemoryLog := False; fLog.StreamFileName := ExtractFilePath(GetModuleName(hInstance)) + 'telemetry.log'; fLog.StreamToFile := True; fLog.AddLogNoTime('Log opened'); Result := True; except Result := False; end; end; //------------------------------------------------------------------------------ procedure TTelemetryLog.FinishLog; begin fLog.AddLogNoTime('Log ended'); end; {------------------------------------------------------------------------------} { TTelemetryLog // Public routines } {------------------------------------------------------------------------------} constructor TTelemetryLog.Create(Recipient: TTelemetryRecipient); begin inherited Create(Recipient); GetLocaleFormatSettings(LOCALE_USER_DEFAULT,fFormatSettings); fFormatSettings.DecimalSeparator := '.'; Recipient.KeepUtilityEvents := False; Recipient.StoreConfigurations := False; Recipient.EventUnregisterAll; fLog := TSimpleLog.Create; If not InitLog then begin Recipient.Log(SCS_LOG_TYPE_error,'Unable to initialize the log file'); raise Exception.Create('TTelemetryLog.Create: Log initialization failed.'); end; fLog.AddLogNoTime('Game ''' + TelemetryStringDecode(Recipient.GameID) + ''' ' + IntToStr(SCSGetMajorVersion(Recipient.GameVersion)) + '.' + IntToStr(SCSGetMinorVersion(Recipient.GameVersion))); If not TelemetrySameStr(Recipient.GameID, SCS_GAME_ID_EUT2) then begin fLog.AddLogNoTime('WARNING: Unsupported game, some features or values might behave incorrectly'); end else begin If Recipient.GameVersion < SCS_TELEMETRY_EUT2_GAME_VERSION_1_00 then fLog.AddLogNoTime('WARNING: Too old version of the game, some features might behave incorrectly'); If Recipient.GameVersion > SCS_TELEMETRY_EUT2_GAME_VERSION_CURRENT then fLog.AddLogNoTime('WARNING: Too new major version of the game, some features might behave incorrectly'); end; If not (Recipient.EventRegister(SCS_TELEMETRY_EVENT_frame_start) and Recipient.EventRegister(SCS_TELEMETRY_EVENT_frame_end) and Recipient.EventRegister(SCS_TELEMETRY_EVENT_paused) and Recipient.EventRegister(SCS_TELEMETRY_EVENT_started)) then begin Recipient.Log(SCS_LOG_TYPE_error,'Unable to register events'); raise Exception.Create('TTelemetryLog.Create: Events registration failed.'); end; Recipient.EventRegister(SCS_TELEMETRY_EVENT_configuration); Recipient.ChannelRegister(SCS_TELEMETRY_TRUCK_CHANNEL_world_placement,SCS_U32_NIL,SCS_VALUE_TYPE_euler,SCS_TELEMETRY_CHANNEL_FLAG_no_value); Recipient.ChannelRegister(SCS_TELEMETRY_TRUCK_CHANNEL_speed,SCS_U32_NIL,SCS_VALUE_TYPE_float); Recipient.ChannelRegister(SCS_TELEMETRY_TRUCK_CHANNEL_engine_rpm,SCS_U32_NIL,SCS_VALUE_TYPE_float); Recipient.ChannelRegister(SCS_TELEMETRY_TRUCK_CHANNEL_engine_gear,SCS_U32_NIL,SCS_VALUE_TYPE_s32); Recipient.Log('Initializing telemetry log'); ZeroMemory(@fTelemetry,SizeOf(TTelemetryState)); fPrintHeader := True; fLastTimestamp := scs_timestamp_t(-1); fOutputPaused := True; end; //------------------------------------------------------------------------------ destructor TTelemetryLog.Destroy; begin FinishLog; fLog.Free; inherited; end; //------------------------------------------------------------------------------ procedure TTelemetryLog.LogHandler(Sender: TObject; LogType: scs_log_type_t; const LogText: String); begin // nothing to do here end; //------------------------------------------------------------------------------ procedure TTelemetryLog.EventRegisterHandler(Sender: TObject; Event: scs_event_t); begin // nothing to do here end; //------------------------------------------------------------------------------ procedure TTelemetryLog.EventUnregisterHandler(Sender: TObject; Event: scs_event_t); begin // nothing to do here end; //------------------------------------------------------------------------------ procedure TTelemetryLog.EventHandler(Sender: TObject; Event: scs_event_t; Data: Pointer); procedure WriteDataToLog; var TempStr: String; begin TempStr := IntToStr(fTelemetry.Timestamp) + ';' + IntToStr(fTelemetry.RawRenderingTimestamp) + ';' + IntToStr(fTelemetry.RawSimulationTimestamp) + ';' + IntToStr(fTElemetry.RawPausedSimulationTimestamp); If fTelemetry.OrientationAvailable then TempStr := TempStr + ';' + FloatToStrF(fTelemetry.Heading,ffFixed,6,6,fFormatSettings) + ';' + FloatToStrF(fTelemetry.Pitch,ffFixed,6,6,fFormatSettings) + ';' + FloatToStrF(fTelemetry.Roll,ffFixed,6,6,fFormatSettings) else TempStr := TempStr + ';---;---;---'; TempStr := TempStr + ';' + FloatToStrF(fTelemetry.Speed,ffFixed,6,6,fFormatSettings) + ';' + FloatToStrF(fTelemetry.RPM,ffFixed,6,6,fFormatSettings) + ';' + IntToStr(fTelemetry.Gear); fLog.AddLogNoTime(TempStr); end; procedure WriteConfigToLog(Config: scs_telemetry_configuration_t); var TempStr: String; TempAttr: p_scs_named_value_t; begin TempStr := 'Configuration: ' + TelemetryStringDecode(APIStringToTelemetryString(Config.id)); TempAttr := Config.attributes; while Assigned(TempAttr^.name) do begin TempStr := TempStr + sLineBreak + ' ' + TelemetryStringDecode(APIStringToTelemetryString(TempAttr^.name)); If TempAttr^.index <> SCS_U32_NIL then TempStr := TempStr + '[' + IntToStr(TempAttr^.index) + ']'; TempStr := TempStr + ' : '; case TempAttr^.value._type of SCS_VALUE_TYPE_INVALID: TempStr := TempStr + 'none'; SCS_VALUE_TYPE_bool: TempStr := TempStr + 'bool = ' + BoolToStr(TempAttr^.value.value_bool.value <> 0,True); SCS_VALUE_TYPE_s32: TempStr := TempStr + 's32 = ' + IntToStr(TempAttr^.value.value_s32.value); SCS_VALUE_TYPE_u32: TempStr := TempStr + 'u32 = ' + IntToStr(TempAttr^.value.value_u32.value); SCS_VALUE_TYPE_u64: TempStr := TempStr + 'u64 = ' + IntToStr(TempAttr^.value.value_u64.value); SCS_VALUE_TYPE_float: TempStr := TempStr + 'float = ' + FloatToStrF(TempAttr^.value.value_float.value,ffFixed,6,6,fFormatSettings); SCS_VALUE_TYPE_double: TempStr := TempStr + 'double = ' + FloatToStrF(TempAttr^.value.value_double.value,ffFixed,6,6,fFormatSettings); SCS_VALUE_TYPE_fvector: TempStr := TempStr + 'fvector = (' + FloatToStrF(TempAttr^.value.value_fvector.x,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_fvector.y,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_fvector.z,ffFixed,6,6,fFormatSettings) + ')'; SCS_VALUE_TYPE_dvector: TempStr := TempStr + 'dvector = (' + FloatToStrF(TempAttr^.value.value_dvector.x,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_dvector.y,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_dvector.z,ffFixed,6,6,fFormatSettings) + ')'; SCS_VALUE_TYPE_euler: TempStr := TempStr + 'euler = h:' + FloatToStrF(TempAttr^.value.value_euler.heading * 360,ffFixed,6,6,fFormatSettings) + ' p:' + FloatToStrF(TempAttr^.value.value_euler.pitch * 360,ffFixed,6,6,fFormatSettings) + ' r:' + FloatToStrF(TempAttr^.value.value_euler.roll * 360,ffFixed,6,6,fFormatSettings); SCS_VALUE_TYPE_fplacement: TempStr := TempStr + 'fplacement = (' + FloatToStrF(TempAttr^.value.value_fplacement.position.x ,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_fplacement.position.y,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_fplacement.position.z,ffFixed,6,6,fFormatSettings) + ') h:' + FloatToStrF(TempAttr^.value.value_fplacement.orientation.heading * 360,ffFixed,6,6,fFormatSettings) + ' p:' + FloatToStrF(TempAttr^.value.value_fplacement.orientation.pitch * 360,ffFixed,6,6,fFormatSettings) + ' r:' + FloatToStrF(TempAttr^.value.value_fplacement.orientation.roll * 360,ffFixed,6,6,fFormatSettings); SCS_VALUE_TYPE_dplacement: TempStr := TempStr + 'dplacement = (' + FloatToStrF(TempAttr^.value.value_dplacement.position.x ,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_dplacement.position.y,ffFixed,6,6,fFormatSettings) + ',' + FloatToStrF(TempAttr^.value.value_dplacement.position.z,ffFixed,6,6,fFormatSettings) + ') h:' + FloatToStrF(TempAttr^.value.value_dplacement.orientation.heading * 360,ffFixed,6,6,fFormatSettings) + ' p:' + FloatToStrF(TempAttr^.value.value_dplacement.orientation.pitch * 360,ffFixed,6,6,fFormatSettings) + ' r:' + FloatToStrF(TempAttr^.value.value_dplacement.orientation.roll * 360,ffFixed,6,6,fFormatSettings); SCS_VALUE_TYPE_string: TempStr := TempStr + 'string = ' + TelemetryStringDecode(APIStringToTelemetryString(TempAttr^.value.value_string.value)); else TempStr := TempStr + 'unknown'; end; Inc(TempAttr); end; fLog.AddLogNoTime(TempStr); end; begin case Event of SCS_TELEMETRY_EVENT_frame_start: begin If fLastTimeStamp = scs_timestamp_t(-1) then fLastTimeStamp := scs_telemetry_frame_start_t(Data^).paused_simulation_time; If (scs_telemetry_frame_start_t(Data^).flags and SCS_TELEMETRY_FRAME_START_FLAG_timer_restart) <> 0 then fLastTimeStamp := 0; fTelemetry.Timestamp := fTelemetry.Timestamp + (scs_telemetry_frame_start_t(Data^).paused_simulation_time - fLastTimestamp); fLastTimestamp := scs_telemetry_frame_start_t(Data^).paused_simulation_time; fTelemetry.RawRenderingTimestamp := scs_telemetry_frame_start_t(Data^).render_time; fTelemetry.RawSimulationTimestamp := scs_telemetry_frame_start_t(Data^).simulation_time; fTelemetry.RawPausedSimulationTimestamp := scs_telemetry_frame_start_t(Data^).paused_simulation_time; end; SCS_TELEMETRY_EVENT_frame_end: begin If fOutputPaused then Exit; If fPrintHeader then begin fPrintHeader := False; fLog.AddLogNoTime('timestamp[us];raw rendering timestamp[us];raw simulation timestamp[us];raw paused simulation timestamp[us];heading[deg];pitch[deg];roll[deg];speed[m/s];rpm;gear'); end; WriteDataToLog; end; SCS_TELEMETRY_EVENT_paused, SCS_TELEMETRY_EVENT_started: begin fOutputPaused := Event = SCS_TELEMETRY_EVENT_paused; If fOutputPaused then fLog.AddLogNoTime('Telemetry paused') else fLog.AddLogNoTime('Telemetry unpaused'); fPrintHeader := True; end; SCS_TELEMETRY_EVENT_configuration: begin WriteConfigToLog(scs_telemetry_configuration_t(Data^)); end; end; end; //------------------------------------------------------------------------------ procedure TTelemetryLog.ChannelRegisterHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t; Flags: scs_u32_t); begin // nothing to do here end; //------------------------------------------------------------------------------ procedure TTelemetryLog.ChannelUnregisterHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; ValueType: scs_value_type_t); begin // nothing to do here end; //------------------------------------------------------------------------------ procedure TTelemetryLog.ChannelHandler(Sender: TObject; const Name: TelemetryString; ID: TChannelID; Index: scs_u32_t; Value: p_scs_value_t); begin If ID = SCS_TELEMETRY_TRUCK_CHANNEL_ID_world_placement then begin If not Assigned(Value) then fTelemetry.OrientationAvailable := False else begin If scs_value_t(Value^)._type = SCS_VALUE_TYPE_euler then begin fTelemetry.OrientationAvailable := True; fTelemetry.Heading := scs_value_t(Value^).value_euler.heading * 360; fTelemetry.Pitch := scs_value_t(Value^).value_euler.pitch * 360; fTelemetry.Roll := scs_value_t(Value^).value_euler.roll * 360; end; end; end else If ID = SCS_TELEMETRY_TRUCK_CHANNEL_ID_speed then begin If Assigned(Value) and (scs_value_t(Value^)._type = SCS_VALUE_TYPE_float) then fTelemetry.Speed := scs_value_t(Value^).value_float.value; end else If ID = SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_rpm then begin If Assigned(Value) and (scs_value_t(Value^)._type = SCS_VALUE_TYPE_float) then fTelemetry.RPM := scs_value_t(Value^).value_float.value; end else If ID = SCS_TELEMETRY_TRUCK_CHANNEL_ID_engine_gear then begin If Assigned(Value) and (scs_value_t(Value^)._type = SCS_VALUE_TYPE_s32) then fTelemetry.Gear := scs_value_t(Value^).value_s32.value; end end; //------------------------------------------------------------------------------ procedure TTelemetryLog.ConfigHandler(Sender: TObject; const Name: TelemetryString; ID: TConfigID; Index: scs_u32_t; Value: scs_value_localized_t); begin // nothing to do here end; end.
(*Programma per l'analisi di una funzione matematica - Marco Olivo, 1998*) (*Versione 4.0*) (*Questo programma ? liberamente distribuibile e modificabile, a patto che rimanga il mio nome nei crediti e a patto che non venga utilizzato per scopi di lucro e/o commerciali*) (*Contiene parti Copyright (c) 1985, 1990 by Borland International, Inc.*) (*In nessun caso sar? responsabile per i danni (inclusi, senza limitazioni, il danno per perdita mancato guadagno, interruzione dell'attivit?, perdita di informazioni o altre perdite economiche) derivanti dall'uso del prodotto "Grafico", anche nel caso io sia stato avvertito dalla possibilit? di danni.*) (*Per la compilazione utilizzare il comando: make -fgrafico.mak *) (*Impostiamo alcune "Switch directives"; la prima ({$A+}) serve per velocizzare l'esecuzione del programma sulle CPU 80x86; la seconda ({$G-}) per far funzionare il programma anche sugli 8086; la terza ({$N+}) e la quarta ({$E+}) servono per rendere il programma portabile su macchine senza il coprocessore numerico 8087 e la quinta ({$S-}) per non permettere al programma di dare eventuali errori di "stack overflow"*) {$A+,G-,N+,E+,S-} program Analizza_Funzione; (******************************************************************** * Dichiarazione "uses" ********************************************************************) uses Crt, Graph, BGIDriv, BGIFont; (******************************************************************** * Dichiarazione "type" ********************************************************************) type coordxy=record x,y:Integer; end; (******************************************************************** * Variabili globali del programma ********************************************************************) var vertici:array[1..4] of coordxy; (*Array per il riempimento della grafica 3D*) funzione:string; (*Variabile temporanea per la nostra funzione*) numero,array_funzione:array[1..100] of string; (*Variabili per valutare l'equazione*) lista_funzioni:array[1..16] of string; (*Contiene le ultime 16 funzioni*) array_x,array_y:array[1..500] of real; (*Arrays per la rotazione della curva*) num_valori:Integer; (*Per il conteggio dei valori presenti negli array sopra*) numero_funzioni:Integer; (*Numero di funzioni correntemente salvate*) funzione_corrente:Integer; (*Numero della funzione correntemente selezionata*) lunghezza:Integer; (*Lunghezza della nostra funzione*) decrementa:Integer; (*Variabile per l'analisi dei dati immessi*) i,oparen,cparen:Integer; (*Variabili per l'analisi dei dati immessi*) OrigMode:Integer; (*Contiene modalit? di testo iniziale*) grDriver:Integer; (*Per la grafica*) grMode:Integer; (*Per la grafica*) ErrCode:Integer; (*Per la grafica*) AsseXx1, AsseXy1, AsseXx2, AsseXy2, AsseYx1, AsseYy1, AsseYx2, AsseYy2:Integer; (*Posizioni degli assi cartesiani*) risoluzione,scala:Integer; (*Fattori per la precisione del grafico*) lunghezza_funzione:Integer; (*Variabile temporanea*) PuntiSx,PuntiDx:Integer; (*Punti principali tracciati a sinistra ed a destra dell'origine*) Linee:Boolean; (*Grafico per linee o per punti?*) Limita:Boolean; (*Per la limitazione del dominio*) x_precedente,y_precedente:Longint; (*Per unire il punto precedente del grafico con quello corrente con una linea*) sx,dx:extended; (*Se il dominio ? limitato, allora queste variabili contengono limitazione*) Disegna,Errore:Boolean; (*Per disegnare correttamente la funzione quando ci sono errori*) Grafico_Rotazione:Boolean; (*Grafico (True) o rotazione (False)?*) Griglia:Boolean; (*Per la griglia*) FuoriDominio:Boolean; (*Per il dominio*) FileDelleFunzioni:string; (*Nome del file che contiene la lista delle funzioni*) errore_da,errore_a:extended; (*Per il dominio*) Dominio:Boolean; (*Dobbiamo disegnare il dominio?*) h:real; (*Incremento tra due valori consecutivi di X*) path:string; (*Percorso BGI*) InizializzatoX,InizializzatoY:Boolean; (*Per vedere se abbiamo inizializzato correttamente le posizioni degli assi*) Radianti:Boolean; (*Punti sul grafico in interi od in radianti?*) DisegnaDerivata:Boolean; (*Dobbiamo disegnare la derivata della funzione?*) (******************************************************************** * Prototipi di funzioni e procedure di tutto il programma ********************************************************************) function Power(x:extended;y:extended):extended; forward; function sinh(x:extended):extended; forward; function cosh(x:extended):extended; forward; function tanh(x:extended):extended; forward; function sgn(x:extended):extended; forward; function asinh(x:extended):extended; forward; function acosh(x:extended):extended; forward; function atanh(x:extended):extended; forward; function ArcSen(x:extended):extended; forward; function ArcCos(x:extended):extended; forward; function ArcCotan(x:extended):extended; forward; function ControllaSintassi:Boolean; forward; function TrovaPrimoTermine(pos:Integer):Integer; forward; function TrovaSecondoTermine(pos:Integer):Integer; forward; procedure CalcolaPrecedenze; forward; procedure AnalizzaDati; forward; function CalcolaParentesi(da,a:Integer):extended; forward; procedure Scrivi(valore:extended;da,a:Integer); forward; function CalcolaValore(da,a:Integer):extended; forward; procedure LeggiFunzione; forward; procedure Abort(Msg:string); forward; procedure DisegnaTitolo(titolo:string); forward; procedure DisegnaMascherinaInformazioni; forward; procedure DisegnaMascherinaTasti; forward; procedure DisegnaGriglia; forward; procedure DisegnaAssi; forward; procedure DisegnaAssiSussidiari; forward; procedure DisegnaNumeri; forward; procedure DisegnaValore(x,y:Longint;color:Integer); forward; procedure Sostituisci(x:real); forward; procedure DisegnaDominio; forward; procedure DisegnaGrafico(flag:Boolean); forward; procedure DisegnaMascherinaRotazione; forward; procedure VisualizzaGrafico; forward; procedure Grafico; forward; procedure Rotazione; forward; procedure Derivata; forward; procedure RuotaCurva; forward; function ReadChar:Char; forward; procedure Beep; forward; procedure SchermataDiBenvenuto; forward; procedure Messaggio(testo:string); forward; procedure MenuPrincipale; forward; procedure InserisciFunzione(espressione:string); forward; procedure EstrapolaPunti; forward; procedure LimitaDominio; forward; procedure Informazioni_Guida; forward; function Conferma(testo:string):Boolean; forward; function ConfermaUscita:Boolean; forward; procedure ImpostaValoriDiDefault; forward; procedure ImpostaDefault; forward; function FileExists(FileName:string):Boolean; forward; procedure CaricaListaFunzioni(FileName:string); forward; procedure SalvaListaFunzioni(FileName:string); forward; procedure MostraListaFunzioni; forward; procedure SelezionaFunzione(da_selezionare,precedente:Integer); forward; procedure ChiediNomeFile; forward; procedure FinestraPrincipale; forward; (******************************************************************** * Funzioni e procedure per il calcolo dei valori della funzione ********************************************************************) function Power(x:extended;y:extended):extended; begin if (x=0) AND (y=0) then begin Power:=0; Errore:=True; Disegna:=False; end else if (x>0) then Power:=Exp(y*ln(x)) else if (x<0) then begin if ((1/y)>1) then begin if (Odd(Round(1/y))) then Power:=-Exp(y*ln(-x)) else if (NOT (Odd(Round(1/y)))) then begin if (y>1) then Power:=Exp(y*ln(-x)) else if (y<1) then begin Power:=0; Errore:=True; end else if (y=1) then Power:=x; end; end else begin if (Odd(Round(y))) then Power:=-Exp(y*ln(-x)) else if (NOT (Odd(Round(y)))) then begin if (y>1) then Power:=Exp(y*ln(-x)) else if (y<1) then begin Power:=0; Errore:=True; end else if (y=1) then Power:=x; end; end; end else if (x=0) AND (y>0) then Power:=0 else if (x=0) AND (y<0) then begin Errore:=True; Power:=0; end else Power:=1; end; (*******************************************************************) function sinh(x:extended):extended; begin sinh:=(exp(x)-exp(-x))/2; end; (*******************************************************************) function cosh(x:extended):extended; begin cosh:=(exp(x)+exp(-x))/2; end; (*******************************************************************) function tanh(x:extended):extended; begin tanh:=(exp(2*x)-1)/(exp(2*x)+1) end; (*******************************************************************) function sgn(x:extended):extended; begin if (x>0) then sgn:=1 else if (x<0) then sgn:=-1 else (*x=0*) sgn:=0; end; (*******************************************************************) function asinh(x:extended):extended; begin asinh:=ln(x+sqrt(sqr(x)+1)); end; (*******************************************************************) function acosh(x:extended):extended; begin if (x>=1) then acosh:=ln(x+sqrt(sqr(x)-1)) else begin acosh:=0; Errore:=True; end; end; (*******************************************************************) function atanh(x:extended):extended; begin if (x>-1) AND (x<1) then atanh:=ln(sqrt((1+x)/(1-x))) else begin atanh:=0; Errore:=True; end; end; (*******************************************************************) function ArcSen(x:extended):extended; begin if (x>-1) AND (x<1) then ArcSen:=ArcTan(x/sqrt(1-sqr(x))) else begin ArcSen:=0; Errore:=True; end; end; (*******************************************************************) function ArcCos(x:extended):extended; begin if (x>-1) AND (x<1) then ArcCos:=Pi/2-ArcTan(x/sqrt(1-sqr(x))) else begin ArcCos:=0; Errore:=True; end; end; (*******************************************************************) function ArcCotan(x:extended):extended; begin ArcCotan:=Pi/2-ArcTan(x); end; (*******************************************************************) function ControllaSintassi:Boolean; var k,i:Integer; posizione_parentesi:Integer; testo:string; begin ControllaSintassi:=True; if (oparen<>cparen) then begin Messaggio('Errore di sintassi: parentesi aperte e chiuse in numero diverso'); ControllaSintassi:=False; end; for i:=1 to lunghezza do begin if (array_funzione[i]<>'(') AND (array_funzione[i]<>')') AND (array_funzione[i]<>'+') AND (array_funzione[i]<>'-') AND (array_funzione[i]<>'*') AND (array_funzione[i]<>'^') AND (array_funzione[i]<>'/') AND (array_funzione[i]<>'SIN') AND (array_funzione[i]<>'COS') AND (array_funzione[i]<>'TAN') AND (array_funzione[i]<>'ATAN') AND (array_funzione[i]<>'COTAN') AND (array_funzione[i]<>'LOG') AND (array_funzione[i]<>'ABS') AND (array_funzione[i]<>'SQR') AND (array_funzione[i]<>'SQRT') AND (array_funzione[i]<>'X') AND (array_funzione[i]<>'ARCSIN') AND (array_funzione[i]<>'ARCCOS') AND (array_funzione[i]<>'ARCCOTAN') AND (array_funzione[i]<>'SINH') AND (array_funzione[i]<>'ASINH') AND (array_funzione[i]<>'COSH') AND (array_funzione[i]<>'ACOSH') AND (array_funzione[i]<>'TANH') AND (array_funzione[i]<>'ATANH') AND (array_funzione[i]<>'SGN') AND (array_funzione[i]<>'INT')then begin if (array_funzione[i][1]='0') OR (array_funzione[i][1]='1') OR (array_funzione[i][1]='2') OR (array_funzione[i][1]='3') OR (array_funzione[i][1]='4') OR (array_funzione[i][1]='5') OR (array_funzione[i][1]='6') OR (array_funzione[i][1]='7') OR (array_funzione[i][1]='8') OR (array_funzione[i][1]='9') then begin for k:=2 to Length(array_funzione[i]) do begin if (array_funzione[i][k]<>'0') AND (array_funzione[i][k]<>'1') AND (array_funzione[i][k]<>'2') AND (array_funzione[i][k]<>'3') AND (array_funzione[i][k]<>'4') AND (array_funzione[i][k]<>'5') AND (array_funzione[i][k]<>'6') AND (array_funzione[i][k]<>'7') AND (array_funzione[i][k]<>'8') AND (array_funzione[i][k]<>'9') then begin Messaggio('Errore di sintassi: carattere non valido'); ControllaSintassi:=False; end; end; end else if (array_funzione[i]='E') then begin Str(Exp(1.0),array_funzione[i]); (*Sostituiamo "e" con il suo valore, dal momento che non lo abbiamo fatto prima per poter controllare la sintassi*) end else begin Messaggio('Errore di sintassi: carattere non valido'); ControllaSintassi:=False; end; end; end; for i:=1 to lunghezza do begin if (array_funzione[i]='(') then begin if (array_funzione[i+1]=')') then begin Messaggio('Errore di sintassi: nessun argomento nella parentesi'); ControllaSintassi:=False; end; end; end; oparen:=0; cparen:=0; for i:=1 to lunghezza do begin if (array_funzione[i]='(') then Inc(oparen) else if (array_funzione[i]=')') then Inc(cparen); if cparen>oparen then begin Messaggio('Errore di sintassi: parentesi chiusa prima di parentesi aperta'); ControllaSintassi:=False; end; end; for i:=1 to lunghezza do begin if (array_funzione[i]='SIN') OR (array_funzione[i]='COS') OR (array_funzione[i]='TAN') OR (array_funzione[i]='ATAN') OR (array_funzione[i]='COTAN') OR (array_funzione[i]='LOG') OR (array_funzione[i]='ABS') OR (array_funzione[i]='SQR') OR (array_funzione[i]='SQRT') OR (array_funzione[i]='ARCSIN') OR (array_funzione[i]='ARCCOS') OR (array_funzione[i]='ARCCOTAN') OR (array_funzione[i]='SINH') OR (array_funzione[i]='ASINH') OR (array_funzione[i]='COSH') OR (array_funzione[i]='ACOSH') OR (array_funzione[i]='TANH') OR (array_funzione[i]='ATANH') OR (array_funzione[i]='SGN') OR (array_funzione[i]='INT') then begin if (array_funzione[i+1]<>'(') then begin testo:=Concat('Errore di sintassi: nessun argomento di ',array_funzione[i]); Messaggio(testo); ControllaSintassi:=False; end; end; end; end; (*******************************************************************) function TrovaPrimoTermine(pos:Integer):Integer; var i:Integer; paren:Integer; begin paren:=0; for i:=pos downto 1 do begin (*Se la posizione dell'array ? un numero oppure una parentesi, l'abbiamo trovato e ritorniamo la posizione; non ammettiamo errori, dato che abbiamo gi? controllato la sintassi precedentemente*) if (array_funzione[i]<>')') AND (array_funzione[i]<>'+') AND (array_funzione[i]<>'-') AND (array_funzione[i]<>'*') AND (array_funzione[i]<>'^') AND (array_funzione[i]<>'/') AND (paren=0) then begin TrovaPrimoTermine:=i; i:=1; (*Usciamo dal ciclo*) end else if (array_funzione[i]=')') then inc(paren) else if (array_funzione[i]='(') AND (paren>0) then begin dec(paren); if (paren=0) then begin TrovaPrimoTermine:=i; i:=1; end; end; end; end; (*******************************************************************) function TrovaSecondoTermine(pos:Integer):Integer; var i:Integer; paren:Integer; begin paren:=0; for i:=pos to lunghezza do begin (*Se la posizione dell'array ? un numero oppure una parentesi, l'abbiamo trovato e ritorniamo la posizione; non ammettiamo errori, dato che abbiamo gi? controllato la sintassi precedentemente*) if (array_funzione[i]<>'(') AND (array_funzione[i]<>'+') AND (array_funzione[i]<>'-') AND (array_funzione[i]<>'*') AND (array_funzione[i]<>'^') AND (array_funzione[i]<>'/') AND (array_funzione[i]<>'SIN') AND (array_funzione[i]<>'COS') AND (array_funzione[i]<>'TAN') AND (array_funzione[i]<>'ATAN') AND (array_funzione[i]<>'COTAN') AND (array_funzione[i]<>'LOG') AND (array_funzione[i]<>'ABS') AND (array_funzione[i]<>'SQR') AND (array_funzione[i]<>'SQRT') AND (array_funzione[i]<>'ARCSIN') AND (array_funzione[i]<>'ARCCOS') AND (array_funzione[i]<>'ARCCOTAN') AND (array_funzione[i]<>'SINH') AND (array_funzione[i]<>'ASINH') AND (array_funzione[i]<>'COSH') AND (array_funzione[i]<>'ACOSH') AND (array_funzione[i]<>'TANH') AND (array_funzione[i]<>'ATANH') AND (array_funzione[i]<>'SGN') AND (array_funzione[i]<>'INT') AND (paren=0) then begin TrovaSecondoTermine:=i; i:=lunghezza; (*Usciamo dal ciclo*) end else if (array_funzione[i]='(') then inc(paren) else if (array_funzione[i]=')') AND (paren>0) then begin dec(paren); if (paren=0) then begin TrovaSecondoTermine:=i-1; i:=lunghezza; end; end; end; end; (*******************************************************************) procedure CalcolaPrecedenze; var n,f:Integer; primo_termine,secondo_termine:Integer; begin for f:=1 to 100 do begin if (array_funzione[f]='SIN') OR (array_funzione[f]='COS') OR (array_funzione[f]='TAN') OR (array_funzione[f]='ATAN') OR (array_funzione[f]='LOG') OR (array_funzione[f]='COTAN') OR (array_funzione[f]='ABS') OR (array_funzione[f]='SQR') OR (array_funzione[f]='SQRT') OR (array_funzione[f]='ARCSIN') OR (array_funzione[f]='ARCCOS') OR (array_funzione[f]='ARCCOTAN') OR (array_funzione[f]='SINH') OR (array_funzione[f]='ASINH') OR (array_funzione[f]='COSH') OR (array_funzione[f]='ACOSH') OR (array_funzione[f]='TANH') OR (array_funzione[f]='ATANH') OR (array_funzione[f]='INT') OR (array_funzione[f]='SGN') then begin primo_termine:=f; secondo_termine:=TrovaSecondoTermine(f); for n:=lunghezza+1 downto primo_termine do array_funzione[n]:=array_funzione[n-1]; array_funzione[primo_termine]:='('; inc(lunghezza); for n:=lunghezza+1 downto secondo_termine+2 do array_funzione[n]:=array_funzione[n-1]; array_funzione[secondo_termine+2]:=')'; inc(lunghezza); inc(f); (*Evitiamo ripetizioni*) end; end; for f:=1 to 100 do begin if (array_funzione[f]='^') then begin primo_termine:=TrovaPrimoTermine(f); secondo_termine:=TrovaSecondoTermine(f); for n:=lunghezza+1 downto primo_termine do array_funzione[n]:=array_funzione[n-1]; array_funzione[primo_termine]:='('; inc(lunghezza); for n:=lunghezza+1 downto secondo_termine+2 do array_funzione[n]:=array_funzione[n-1]; array_funzione[secondo_termine+2]:=')'; inc(lunghezza); inc(f); (*Evitiamo ripetizioni*) end; end; for f:=1 to 100 do begin if (array_funzione[f]='*') then begin primo_termine:=TrovaPrimoTermine(f); secondo_termine:=TrovaSecondoTermine(f); for n:=lunghezza+1 downto primo_termine do array_funzione[n]:=array_funzione[n-1]; array_funzione[primo_termine]:='('; inc(lunghezza); for n:=lunghezza+1 downto secondo_termine+2 do array_funzione[n]:=array_funzione[n-1]; array_funzione[secondo_termine+2]:=')'; inc(lunghezza); inc(f); (*Evitiamo ripetizioni*) end else if (array_funzione[f]='/') then begin primo_termine:=TrovaPrimoTermine(f); secondo_termine:=TrovaSecondoTermine(f); for n:=lunghezza+1 downto primo_termine do array_funzione[n]:=array_funzione[n-1]; array_funzione[primo_termine]:='('; inc(lunghezza); for n:=lunghezza+1 downto secondo_termine+2 do array_funzione[n]:=array_funzione[n-1]; array_funzione[secondo_termine+2]:=')'; inc(lunghezza); inc(f); (*Evitiamo ripetizioni*) end; end; (*Non ci interessano altri casi*) end; (*******************************************************************) procedure AnalizzaDati; var n,k,i:Integer; IsNumber:Boolean; begin IsNumber:=False; decrementa:=0; for i:=1 to lunghezza do begin if (array_funzione[i]='0') OR (array_funzione[i]='1') OR (array_funzione[i]='2') OR (array_funzione[i]='3') OR (array_funzione[i]='4') OR (array_funzione[i]='5') OR (array_funzione[i]='6') OR (array_funzione[i]='7') OR (array_funzione[i]='8') OR (array_funzione[i]='9') then begin if (IsNumber=False) then IsNumber:=True else (*Accorpiamo la stringa*) begin array_funzione[i-1]:=Concat(array_funzione[i-1], array_funzione[i]); for k:=i to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa); dec(i); end; end else if (array_funzione[i]='X') then IsNumber:=False else if (array_funzione[i]='+') OR (array_funzione[i]='-') OR (array_funzione[i]='*') OR (array_funzione[i]='/') OR (array_funzione[i]='^') then IsNumber:=False else begin IsNumber:=False; if (array_funzione[i]='S') AND (array_funzione[i+1]='I') AND (array_funzione[i+2]='N') AND (array_funzione[i+3]='H') then begin array_funzione[i]:='SINH'; for n:=1 to 3 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,3); dec(i,3); end else if (array_funzione[i]='C') AND (array_funzione[i+1]='O') AND (array_funzione[i+2]='S') AND (array_funzione[i+3]='H') then begin array_funzione[i]:='COSH'; for n:=1 to 3 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,3); dec(i,3); end else if (array_funzione[i]='T') AND (array_funzione[i+1]='A') AND (array_funzione[i+2]='N') AND (array_funzione[i+3]='H') then begin array_funzione[i]:='TANH'; for n:=1 to 3 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,3); dec(i,3); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='S') AND (array_funzione[i+2]='I') AND (array_funzione[i+3]='N') AND (array_funzione[i+4]='H')then begin array_funzione[i]:='ASINH'; for n:=1 to 4 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,4); dec(i,4); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='C') AND (array_funzione[i+2]='O') AND (array_funzione[i+3]='S') AND (array_funzione[i+4]='H')then begin array_funzione[i]:='ACOSH'; for n:=1 to 4 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,4); dec(i,4); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='T') AND (array_funzione[i+2]='A') AND (array_funzione[i+3]='N') AND (array_funzione[i+4]='H')then begin array_funzione[i]:='ATANH'; for n:=1 to 4 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,4); dec(i,4); end else if (array_funzione[i]='S') AND ((array_funzione[i+1]='I') OR (array_funzione[i+1]='E')) AND (array_funzione[i+2]='N') then begin array_funzione[i]:='SIN'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='C') AND (array_funzione[i+1]='O') AND (array_funzione[i+2]='S') then begin array_funzione[i]:='COS'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='L') AND (array_funzione[i+1]='O') AND (array_funzione[i+2]='G') then begin array_funzione[i]:='LOG'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='S') AND (array_funzione[i+1]='G') AND (array_funzione[i+2]='N') then begin array_funzione[i]:='SGN'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='L') AND (array_funzione[i+1]='N') then begin array_funzione[i]:='LOG'; for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa); dec(i,2); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='B') AND (array_funzione[i+2]='S') then begin array_funzione[i]:='ABS'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='C') AND (array_funzione[i+1]='O') AND (array_funzione[i+2]='T') AND (array_funzione[i+3]='G') then begin array_funzione[i]:='COTAN'; for n:=1 to 3 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,3); dec(i,3); end else if (array_funzione[i]='C') AND (array_funzione[i+1]='O') AND (array_funzione[i+2]='T') AND (array_funzione[i+3]='A') AND ((array_funzione[i+4]='G') OR (array_funzione[i+4]='N')) then begin array_funzione[i]:='COTAN'; for n:=1 to 4 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,4); dec(i,4); end else if (array_funzione[i]='T') AND (array_funzione[i+1]='A') AND ((array_funzione[i+2]='G') OR (array_funzione[i+2]='N')) then begin array_funzione[i]:='TAN'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='T') AND (array_funzione[i+1]='G') then begin array_funzione[i]:='TAN'; for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa); dec(i,2); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='R') AND (array_funzione[i+2]='C') AND (array_funzione[i+3]='T') AND (array_funzione[i+4]='A') AND ((array_funzione[i+5]='G') OR (array_funzione[i+5]='N')) then begin array_funzione[i]:='ATAN'; for n:=1 to 5 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,5); dec(i,5); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='R') AND (array_funzione[i+2]='C') AND (array_funzione[i+3]='T') AND (array_funzione[i+4]='G') then begin array_funzione[i]:='ATAN'; for n:=1 to 4 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,4); dec(i,4); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='T') AND (array_funzione[i+2]='A') AND ((array_funzione[i+3]='G') OR (array_funzione[i+3]='N')) then begin array_funzione[i]:='ATAN'; for n:=1 to 3 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,3); dec(i,3); end else if (array_funzione[i]='S') AND (array_funzione[i+1]='Q') AND (array_funzione[i+2]='R') AND (array_funzione[i+3]='T') then begin array_funzione[i]:='SQRT'; for n:=1 to 3 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,3); dec(i,3); end else if (array_funzione[i]='S') AND (array_funzione[i+1]='Q') AND (array_funzione[i+2]='R') then begin array_funzione[i]:='SQR'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='R') AND (array_funzione[i+2]='C') AND (array_funzione[i+3]='S') AND ((array_funzione[i+4]='E') OR (array_funzione[i+4]='I')) AND (array_funzione[i+5]='N') then begin array_funzione[i]:='ARCSIN'; for n:=1 to 5 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,5); dec(i,5); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='R') AND (array_funzione[i+2]='C') AND (array_funzione[i+3]='C') AND (array_funzione[i+4]='O') AND (array_funzione[i+5]='S') then begin array_funzione[i]:='ARCCOS'; for n:=1 to 5 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,5); dec(i,5); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='R') AND (array_funzione[i+2]='C') AND (array_funzione[i+3]='C') AND (array_funzione[i+4]='O') AND (array_funzione[i+5]='T') AND (array_funzione[i+6]='G') then begin array_funzione[i]:='ARCCOTAN'; for n:=1 to 6 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,6); dec(i,6); end else if (array_funzione[i]='I') AND (array_funzione[i+1]='N') AND (array_funzione[i+2]='T') then begin array_funzione[i]:='INT'; for n:=1 to 2 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,2); dec(i,2); end else if (array_funzione[i]='A') AND (array_funzione[i+1]='R') AND (array_funzione[i+2]='C') AND (array_funzione[i+3]='C') AND (array_funzione[i+4]='O') AND (array_funzione[i+5]='T') AND (array_funzione[i+6]='A') AND ((array_funzione[i+7]='G') OR (array_funzione[i+7]='N')) then begin array_funzione[i]:='ARCCOTAN'; for n:=1 to 7 do for k:=i+1 to lunghezza do array_funzione[k]:=array_funzione[k+1]; inc(decrementa,7); dec(i,7); end; end; end; dec(lunghezza,decrementa); end; (*******************************************************************) function CalcolaParentesi(da,a:Integer):extended; var result:extended; i:Integer; sign:string; number:extended; code:Integer; begin result:=0; sign:=''; (*Calcoliamo il valore dell'espressione*) for i:=da to a do begin Val(numero[i],number,code); if (code=0) then begin if (sign='+') then result:=result+number else if (sign='-') then result:=result-number else if (sign='*') then result:=result*number else if (sign='/') then begin if number<>0 then result:=result/number else Errore:=True; end else if (sign='^') then result:=Power(result,number) else if (sign='SIN') then result:=sin(number) else if (sign='COS') then result:=cos(number) else if (sign='LOG') then begin if number>0 then result:=ln(number) else Errore:=True; end else if (sign='TAN') then begin if cos(number)<>0 then result:=sin(number)/cos(number) else Errore:=True; end else if (sign='COTAN') then begin if sin(number)<>0 then result:=cos(number)/sin(number) else Errore:=True; end else if (sign='SINH') then begin result:=sinh(number); end else if (sign='COSH') then begin result:=cosh(number); end else if (sign='TANH') then begin result:=tanh(number); end else if (sign='INT') then begin result:=Int(number); end else if (sign='SGN') then begin result:=sgn(number); end else if (sign='ASINH') then begin result:=asinh(number); end else if (sign='ACOSH') then begin result:=acosh(number); end else if (sign='ATANH') then begin result:=atanh(number); end else if (sign='ATAN') then result:=arctan(number) else if (sign='ABS') then result:=Abs(number) else if (sign='SQR') then result:=Power(number,2) else if (sign='SQRT') then result:=Power(number,1/2) else if (sign='ARCSIN') then result:=ArcSen(number) else if (sign='ARCCOS') then result:=ArcCos(number) else if (sign='ARCCOTAN') then result:=ArcCotan(number) else result:=number; end; sign:=numero[i]; end; CalcolaParentesi:=result; end; (*******************************************************************) procedure Scrivi(valore:extended;da,a:Integer); var i:Integer; begin Str(valore,numero[da]); for i:=da+1 to 100 do numero[i]:=numero[i+a-da]; end; (*******************************************************************) function CalcolaValore(da,a:Integer):extended; var i,k:Integer; number,code:Integer; inizio,fine:Integer; risultato:extended; paren:Integer; IsParen:Boolean; begin risultato:=0; paren:=0; IsParen:=True; (*Togliere il commento alle righe seguenti per mettere in grado il programma di valutare espressioni senza incognite (diventa una sorta di calcolatrice scientifica)*) (* for i:=1 to 100 do numero[i]:=array_funzione[i];*) (*Calcoliamo tutte le parentesi*) for i:=1 to lunghezza do begin if (numero[i]='(') then begin paren:=1; IsParen:=True; inizio:=i+1; for k:=i+1 to lunghezza do begin if (numero[k]=')') then begin fine:=k-1; k:=lunghezza; end else if (numero[k]='(') then begin inc(paren); inizio:=k+1; end; end; risultato:=CalcolaParentesi(inizio,fine); Scrivi(risultato,inizio-1,fine+1); dec(lunghezza,fine-inizio+2); end else IsParen:=False; if (IsParen=True) then i:=1; end; (*Fa le varie operazioni, ormai soltanto tra numeri*) CalcolaValore:=CalcolaParentesi(1,lunghezza); end; (*******************************************************************) procedure LeggiFunzione; var token:string; i:Integer; begin oparen:=0; cparen:=0; for i:=1 to 100 do begin array_funzione[i]:=''; end; for i:=1 to lunghezza do begin token:=Copy(funzione, i, 1); (*Analizza la funzione*) if token='(' then begin inc(oparen); array_funzione[i]:='('; end else if token=')' then begin inc(cparen); array_funzione[i]:=')'; end else if token='+' then array_funzione[i]:='+' else if token='-' then array_funzione[i]:='-' else if token='*' then array_funzione[i]:='*' else if token='/' then array_funzione[i]:='/' else if token='^' then array_funzione[i]:='^' else if (token='0') OR (token='1') OR (token='2') OR (token='3') OR (token='4') OR (token='5') OR (token='6') OR (token='7') OR (token='8') OR (token='9') then array_funzione[i]:=token else if (token='x') OR (token='X') then array_funzione[i]:='X' else array_funzione[i]:=token; end; AnalizzaDati; end; (******************************************************************** * Funzioni e procedure per il grafico della funzione ********************************************************************) procedure Abort(Msg:string); begin (*E' occorso un errore molto grave*) Writeln(Msg,': ',GraphErrorMsg(GraphResult)); Halt(1); end; procedure DisegnaTitolo(titolo:string); begin SetViewPort(5,5,GetMaxX-5,25,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); (*Creiamo la nostra mascherina del titolo*) SetColor(DarkGray); SetBkColor(Black); Line(5,5,GetMaxX-5,5); Line(5,5,5,25); Line(5,25,GetMaxX-5,25); Line(GetMaxX-5,5,GetMaxX-5,25); SetColor(Yellow); titolo:=Concat(titolo,funzione); SetTextStyle(DefaultFont,HorizDir,1); SetTextJustify(CenterText,CenterText); OutTextXY(GetMaxX div 2,15,titolo); end; (*******************************************************************) procedure DisegnaMascherinaInformazioni; var i:Integer; testo:string; begin (*Impostiamo l'area di disegno*) SetViewPort(5,GetMaxY-50,GetMaxX-5,GetMaxY-40,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); (*Iniziamo a disegnare*) SetColor(DarkGray); SetBkColor(Black); Line(5,GetMaxY-50,GetMaxX-5,GetMaxY-50); Line(5,GetMaxY-50,5,GetMaxY-40); Line(5,GetMaxY-40,GetMaxX-5,GetMaxY-40); Line(GetMaxX-5,GetMaxY-50,GetMaxX-5,GetMaxY-40); SetColor(LightGreen); SetTextStyle(DefaultFont,HorizDir,1); SetTextJustify(LeftText,TopText); if (Linee=True) then testo:='Linee' else testo:='Punti'; OutTextXY(7,GetMaxY-48,testo); SetColor(DarkGray); Line(8+TextWidth(testo),GetMaxY-50,8+TextWidth(testo),GetMaxY-40); SetColor(LightBlue); if Dominio then OutTextXY(9+TextWidth(testo),GetMaxY-48,'Dominio'); SetColor(DarkGray); Line(10+TextWidth(testo)+TextWidth('Dominio'),GetMaxY-50,10+TextWidth(testo)+TextWidth('Dominio'),GetMaxY-40); Str(scala*5/2:4:0,testo); testo:=Concat(testo,'%'); SetColor(Red); OutTextXY(GetMaxX-TextWidth(testo)-5,GetMaxY-48,testo); SetColor(DarkGray); Line(12+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti'),GetMaxY-50, 12+TextWidth('Linee')+TextWidth('Dominio')+ TextWidth('Radianti'),GetMaxY-40); Line(14+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti')+TextWidth('Derivata'),GetMaxY-50, 14+TextWidth('Linee')+ TextWidth('Dominio')+TextWidth('Radianti')+TextWidth('Derivata'),GetMaxY-40); Line(16+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti')+TextWidth('Derivata')+TextWidth('Griglia'), GetMaxY-50, 16+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti')+TextWidth('Derivata')+TextWidth('Griglia'), GetMaxY-40); SetColor(Yellow); if Radianti then OutTextXY(12+TextWidth('Linee')+TextWidth('Dominio'),GetMaxY-48,'Radianti'); SetColor(LightMagenta); if DisegnaDerivata then OutTextXY(14+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti'),GetMaxY-48,'Derivata'); SetColor(Red); if Griglia then OutTextXY(16+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti')+TextWidth('Derivata'),GetMaxY-48,'Griglia'); SetColor(Cyan); i:=18+TextWidth('Linee')+TextWidth('Dominio')+TextWidth('Radianti')+TextWidth('Derivata')+TextWidth('Griglia'); while (i<GetMaxX-TextWidth(testo)-5) do begin Line(i,GetMaxY-48,i,GetMaxY-42); Inc(i,risoluzione); end; SetColor(DarkGray); Line(GetMaxX-TextWidth(testo)-4,GetMaxY-50,GetMaxX-TextWidth(testo)-4,GetMaxY-40); end; (*******************************************************************) procedure DisegnaMascherinaTasti; begin SetViewPort(5,GetMaxY-35,GetMaxX-5,GetMaxY,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); SetColor(DarkGray); SetBkColor(Black); Line(5,GetMaxY-35,GetMaxX-5,GetMaxY-35); Line(5,GetMaxY-35,5,GetMaxY-5); Line(GetMaxX-5,GetMaxY-35,GetMaxX-5,GetMaxY-5); Line(5,GetMaxY-5,GetMaxX-5,GetMaxY-5); SetColor(White); SetTextStyle(SmallFont,HorizDir,4); SetTextJustify(LeftText,TopText); OutTextXY(12,GetMaxY-35,'F1/F2 - Zoom +/-'); OutTextXY(12,GetMaxY-20,'F3 - Punti/Linee'); OutTextXY(130,GetMaxY-35,'F4 - Radianti/Interi'); OutTextXY(130,GetMaxY-20,'F5/F6 - Risoluzione +/-'); OutTextXY(273,GetMaxY-35,'F7 - Dominio'); OutTextXY(273,GetMaxY-20,'F8 - Derivata'); OutTextXY(362,GetMaxY-35,'F9 - Torna'); OutTextXY(362,GetMaxY-20,'Cursori - Scorri'); OutTextXY(462,GetMaxY-35,'F10 - Griglia'); OutTextXY(462,GetMaxY-20,'INVIO - Rotazione'); OutTextXY(562,GetMaxY-35,'ESC - Esci'); end; (*******************************************************************) procedure DisegnaGriglia; var row,col:real; fattore:real; begin if NOT Radianti then fattore:=1 else fattore:=Pi/2; if AsseYx1>=GetMaxX-6 then begin row:=AsseYx1; while row>0 do begin col:=AsseXy1; while col<GetMaxY-56 do begin PutPixel(Round(row),Round(col),Red); col:=col+fattore*scala/2; end; row:=row-fattore*scala/2; end; row:=AsseYx1; while row>0 do begin col:=AsseXy1; while col<GetMaxY-56 do begin PutPixel(Round(row),Round(col),Red); col:=col+fattore*scala/2; end; row:=row-fattore*scala/2; end; row:=AsseYx1; while row>0 do begin col:=AsseXy1; while col>0 do begin PutPixel(Round(row),Round(col),Red); col:=col-fattore*scala/2; end; row:=row-fattore*scala/2; end; row:=AsseYx1; while row>0 do begin col:=AsseXy1; while col>0 do begin PutPixel(Round(row),Round(col),Red); col:=col-fattore*scala/2; end; row:=row-fattore*scala/2; end; end else begin row:=AsseYx1; while row<GetMaxX-6 do begin col:=AsseXy1; while col<GetMaxY-56 do begin PutPixel(Round(row),Round(col),Red); col:=col+fattore*scala/2; end; row:=row+fattore*scala/2; end; row:=AsseYx1; while row>0 do begin col:=AsseXy1; while col<GetMaxY-56 do begin PutPixel(Round(row),Round(col),Red); col:=col+fattore*scala/2; end; row:=row-fattore*scala/2; end; row:=AsseYx1; while row<GetMaxX-6 do begin col:=AsseXy1; while col>0 do begin PutPixel(Round(row),Round(col),Red); col:=col-fattore*scala/2; end; row:=row+fattore*scala/2; end; row:=AsseYx1; while row>0 do begin col:=AsseXy1; while col>0 do begin PutPixel(Round(row),Round(col),Red); col:=col-fattore*scala/2; end; row:=row-fattore*scala/2; end; end; end; (*******************************************************************) procedure DisegnaAssi; var i:real; fattore:real; begin SetViewPort(22,30,GetMaxX-5,GetMaxY-72,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); if NOT Radianti then fattore:=1 else fattore:=Pi; (*Creiamo la zona del grafico*) SetColor(DarkGray); SetBkColor(Black); Line(23,30,GetMaxX-5,30); Line(23,30,23,GetMaxY-75); Line(23,GetMaxY-75,GetMaxX-5,GetMaxY-75); Line(GetMaxX-5,30,GetMaxX-5,GetMaxY-75); SetViewPort(24,31,GetMaxX-6,GetMaxY-75,ClipOn); (*Assi cartesiani*) SetColor(White); Line(AsseYx1,AsseYy1,AsseYx2,AsseYy2); Line(AsseXx1,AsseXy1,AsseXx2,AsseXy2); SetColor(Brown); SetLineStyle(SolidLn,1,NormWidth); (*Costruiamo la nostra griglia sull'asse delle X*) i:=AsseYx1; while (i<GetMaxX-6) do begin Line(Round(i),AsseXy1+3,Round(i),AsseXy1-3); i:=i+fattore*scala; end; i:=AsseYx1; while (i<GetMaxX-6) do begin Line(Round(i),AsseXy1+2,Round(i),AsseXy1-2); i:=i+fattore*scala/2; end; i:=AsseYx1; while (i<GetMaxX-6) do begin Line(Round(i),AsseXy1+1,Round(i),AsseXy1-1); i:=i+fattore*scala/4; end; i:=AsseYx1; while (i>0) do begin Line(Round(i),AsseXy1+3,Round(i),AsseXy1-3); i:=i-fattore*scala; end; i:=AsseYx1; while (i>0) do begin Line(Round(i),AsseXy1+2,Round(i),AsseXy1-2); i:=i-fattore*scala/2; end; i:=AsseYx1; while (i>0) do begin Line(Round(i),AsseXy1+1,Round(i),AsseXy1-1); i:=i-fattore*scala/4; end; (*Costruiamo la nostra griglia sull'asse delle Y*) i:=AsseXy1; while (i<GetMaxY-56) do begin Line(AsseYx1+3,Round(i),AsseYx1-3,Round(i)); i:=i+fattore*scala; end; i:=AsseXy1; while (i<GetMaxY-56) do begin Line(AsseYx1-2,Round(i),AsseYx1+2,Round(i)); i:=i+fattore*scala/2; end; i:=AsseXy1; while (i<GetMaxY-56) do begin Line(AsseYx1+1,Round(i),AsseYx1-1,Round(i)); i:=i+fattore*scala/4; end; i:=AsseXy1; while (i>0) do begin Line(AsseYx1+3,Round(i),AsseYx1-3,Round(i)); i:=i-fattore*scala; end; i:=AsseXy1; while (i>0) do begin Line(AsseYx1-2,Round(i),AsseYx1+2,Round(i)); i:=i-fattore*scala/2; end; i:=AsseXy1; while (i>0) do begin Line(AsseYx1+1,Round(i),AsseYx1-1,Round(i)); i:=i-fattore*scala/4; end; if Griglia then DisegnaGriglia; DisegnaAssiSussidiari; end; (*******************************************************************) procedure DisegnaAssiSussidiari; var i:real; fattore:real; begin (*Inizializzazione variabili*) PuntiSx:=0; PuntiDx:=0; if NOT Radianti then fattore:=1 else fattore:=Pi; SetViewPort(5,30,21,GetMaxY-56,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); SetColor(DarkGray); Line(5,30,5,GetMaxY-75); Line(5,30,19,30); Line(19,30,19,GetMaxY-75); Line(5,GetMaxY-75,19,GetMaxY-75); SetViewPort(22,GetMaxY-72,GetMaxX-6,GetMaxY-56,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); Line(23,GetMaxY-72,GetMaxX-5,GetMaxY-72); Line(23,GetMaxY-72,23,GetMaxY-56); Line(23,GetMaxY-56,GetMaxX-5,GetMaxY-56); Line(GetMaxX-5,GetMaxY-72,GetMaxX-5,GetMaxY-56); SetColor(Brown); SetLineStyle(SolidLn,1,NormWidth); (*Costruiamo la nostra griglia sull'asse delle X*) SetViewPort(23,0,GetMaxX-6,GetMaxY,ClipOn); i:=AsseYx1; while (i<GetMaxX-6) do begin Line(Round(i),GetMaxY-64,Round(i),GetMaxY-57); i:=i+fattore*scala; Inc(PuntiDx); end; i:=AsseYx1; while (i<GetMaxX-6) do begin Line(Round(i),GetMaxY-62,Round(i),GetMaxY-57); i:=i+fattore*scala/2; end; i:=AsseYx1; while (i<GetMaxX-6) do begin Line(Round(i),GetMaxY-60,Round(i),GetMaxY-57); i:=i+fattore*scala/4; end; i:=AsseYx1; while (i>0) do begin Line(Round(i),GetMaxY-64,Round(i),GetMaxY-57); i:=i-fattore*scala; Inc(PuntiSx); end; i:=AsseYx1; while (i>0) do begin Line(Round(i),GetMaxY-62,Round(i),GetMaxY-57); i:=i-fattore*scala/2; end; i:=AsseYx1; while (i>0) do begin Line(Round(i),GetMaxY-60,Round(i),GetMaxY-57); i:=i-fattore*scala/4; end; (*Costruiamo la nostra griglia sull'asse delle Y*) SetViewPort(5,30,21,GetMaxY-76,ClipOn); i:=AsseXy1; while (i<GetMaxY) do begin Line(1,Round(i),7,Round(i)); i:=i+fattore*scala; end; i:=AsseXy1; while (i<GetMaxY-85) do begin Line(1,Round(i),5,Round(i)); i:=i+fattore*scala/2; end; i:=AsseXy1; while (i<GetMaxY-85) do begin Line(1,Round(i),3,Round(i)); i:=i+fattore*scala/4; end; i:=AsseXy1; while (i>0) do begin Line(1,Round(i),7,Round(i)); i:=i-fattore*scala; end; i:=AsseXy1; while (i>0) do begin Line(1,Round(i),5,Round(i)); i:=i-fattore*scala/2; end; i:=AsseXy1; while (i>0) do begin Line(1,Round(i),3,Round(i)); i:=i-fattore*scala/4; end; PuntiSx:=PuntiSx*3; PuntiDx:=PuntiDx*3; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); end; (*******************************************************************) procedure DisegnaNumeri; var numero:real; pos:Integer; testo:string; aumento:Integer; posRad:real; begin SetViewPort(23,31,GetMaxX-6,GetMaxY-75,ClipOn); SetColor(Yellow); SetTextStyle(SmallFont,HorizDir,2); SetTextJustify(LeftText,TopText); if NOT Radianti then begin aumento:=2; (*Prima parte: asse delle X*) numero:=0; pos:=AsseYx1+6; while (pos<GetMaxX-6) do begin Str(numero:4:2,testo); if (TextWidth(testo)+pos<(GetMaxX-6)) then OutTextXY(pos,AsseXy1+5,testo); Inc(pos,scala*aumento); numero:=numero+aumento; end; numero:=-aumento; pos:=AsseYx1+6-(aumento-1)*scala; while (pos>6) do begin Str(numero:4:2,testo); if (pos-scala>6) then OutTextXY(pos-scala,AsseXy1+5,testo); Dec(pos,scala*aumento); numero:=numero-aumento; end; (*Seconda parte: asse delle Y*) numero:=aumento; pos:=AsseXy1+3; while (pos>31) do begin Str(numero:4:2,testo); if (TextHeight(testo)+pos-aumento*scala>31) then OutTextXY(AsseYx1-TextWidth(testo)-5,pos-aumento*scala-TextHeight(testo)-5,testo); Dec(pos,scala*aumento); numero:=numero+aumento; end; numero:=aumento; pos:=AsseXy1-3; while (pos<GetMaxY-56) do begin Str(-numero:4:2,testo); if (TextHeight(testo)+pos+aumento*scala<(GetMaxY-56)) then OutTextXY(AsseYx1-TextWidth(testo)-5,pos+aumento*scala+TextHeight(testo)-5,testo); Inc(pos,scala*aumento); numero:=numero+aumento; end; end else begin aumento:=1; (*Prima parte: asse delle X*) numero:=0; posRad:=AsseYx1+3; while (posRad<GetMaxX-6) do begin Str(numero:4:1,testo); testo:=Concat(testo,'?'); if (TextWidth(testo)+Round(posRad)<(GetMaxX-6)) then OutTextXY(Round(posRad),AsseXy1+5,testo); posRad:=posRad+scala*Pi; numero:=numero+aumento; end; numero:=-aumento; posRad:=AsseYx1+3-(Pi-1)*scala; while (posRad>6) do begin Str(numero:4:1,testo); testo:=Concat(testo,'?'); if (Round(posRad)-scala>6) then OutTextXY(Round(posRad)-scala,AsseXy1+5,testo); posRad:=posRad-scala*Pi; numero:=numero-aumento; end; (*Seconda parte: asse delle Y*) numero:=aumento; posRad:=AsseXy1+3-scala*2; while (posRad>31) do begin Str(numero:4:1,testo); testo:=Concat(testo,'?'); if (TextHeight(testo)+Round(posRad)-aumento*scala>31) then OutTextXY(AsseYx1-TextWidth(testo)-5,Round(posRad)-aumento*scala-TextHeight(testo)-5,testo); posRad:=posRad-scala*Pi; numero:=numero+aumento; end; numero:=aumento; posRad:=AsseXy1-3+scala*2; while (posRad<GetMaxY-56) do begin Str(-numero:4:1,testo); testo:=Concat(testo,'?'); if (TextHeight(testo)+Round(posRad)+aumento*scala<(GetMaxY-56)) then OutTextXY(AsseYx1-TextWidth(testo)-5,Round(posRad)+aumento*scala+TextHeight(testo)-5,testo); posRad:=posRad+scala*Pi; numero:=numero+aumento; end; end; end; (*******************************************************************) procedure DisegnaValore(x,y:Longint;color:Integer); begin if Linee then begin SetColor(color); if (x+AsseYx1<32767) AND (x+AsseYx1>-32768) AND (-y+AsseXy1<32767) AND (-y+AsseXy1>-32768) then begin if Disegna then Line(x_precedente+AsseYx1,-y_precedente+AsseXy1,x+AsseYx1,-y+AsseXy1) else Disegna:=True; (*Salviamo i nostri valori correnti*) x_precedente:=x; y_precedente:=y; end; end else begin if (x+AsseYx1<32767) AND (x+AsseYx1>-32768) AND (-y+AsseXy1<32767) AND (-y+AsseXy1>-32768) then PutPixel(x+AsseYx1,-y+AsseXy1,color); end; end; (*******************************************************************) procedure Sostituisci(x:real); var z:Integer; temp: array[1..100] of string; begin for z:=1 to 100 do begin numero[z]:=''; temp[z]:=array_funzione[z]; array_funzione[z]:=''; end; for z:=1 to 100 do begin array_funzione[z]:=temp[z]; end; (*Copiamo il nostro array in un nuovo array*) for z:=1 to lunghezza_funzione do begin numero[z]:=array_funzione[z]; if (numero[z]='X') then Str(x,numero[z]); end; end; (*******************************************************************) procedure DisegnaDominio; var col,row:Integer; begin if (Round(errore_da*scala)+AsseYx1<32767) AND (Round(errore_da*scala)+AsseYx1>-32768) AND (Round(errore_a*scala)+AsseYx1<32767) AND (Round(errore_a*scala)+AsseYx1>-32768) then begin SetColor(LightBlue); Line(Round(errore_da*scala)+AsseYx1,0,Round(errore_da*scala)+AsseYx1,GetMaxY-56); Line(Round(errore_a*scala)+AsseYx1,0,Round(errore_a*scala)+AsseYx1,GetMaxY-56); col:=Round(errore_da*scala)+AsseYx1; if errore_da>errore_a then while col>Round(errore_a*scala)+AsseYx1 do begin row:=0; while row<GetMaxY-56 do begin PutPixel(col,row,LightBlue); Inc(row,5); end; Dec(col,5); end else while col<Round(errore_a*scala)+AsseYx1 do begin row:=0; while row<GetMaxY-56 do begin PutPixel(col,row,LightBlue); Inc(row,5); end; Inc(col,5); end; end; end; (*******************************************************************) procedure DisegnaGrafico(flag:Boolean); var k,z:Integer; x,y:extended; temp:array[1..100] of string; FuoriDominio,NonNelDominio:Boolean; begin (*Copiamo il nostro array in un nuovo array*) for z:=1 to 100 do numero[z]:=array_funzione[z]; (*Inizializzazione di alcune variabili*) lunghezza_funzione:=lunghezza; h:=risoluzione/20; k:=4; (*Impostiamo l'area in cui disegneremo*) SetViewPort(24,31,GetMaxX-6,GetMaxY-75,ClipOn); (*Azzeramento di alcune variabili*) num_valori:=0; for z:=1 to 500 do begin array_x[z]:=0; array_y[z]:=0; end; (*Disegnamo la curva dal centro a sinistra...*) x:=0; Disegna:=False; FuoriDominio:=False; NonNelDominio:=False; while (x>-PuntiSx) do begin Sostituisci(x); lunghezza:=lunghezza_funzione; Errore:=False; y:=CalcolaValore(1,lunghezza); if (y*scala<2147483647.0) AND (y*scala>-2147483648.0) AND NOT Errore then begin if Limita then begin if (x*scala<dx*scala) AND (x*scala>sx*scala) AND flag then DisegnaValore(Round(x*scala),Round(y*scala),LightGreen); end else if NOT Limita AND flag then DisegnaValore(Round(x*scala),Round(y*scala),LightGreen); if (k=4) AND ((Limita AND (x*scala<dx*scala) AND (x*scala>sx*scala)) OR NOT Limita) then begin array_x[num_valori]:=x*scala; if y<0 then y:=-y; array_y[num_valori]:=y*scala; k:=1; Inc(num_valori); end else if k<>4 then Inc(k); end; if Errore then begin if NOT NonNelDominio then begin Disegna:=False; FuoriDominio:=True; errore_da:=x; errore_a:=x; NonNelDominio:=True; end else begin errore_a:=x; end; end else begin if NonNelDominio AND Dominio then DisegnaDominio; FuoriDominio:=False; NonNelDominio:=False; end; x:=x-h; end; if Dominio AND FuoriDominio then DisegnaDominio; (*... e dal centro a destra*) x_precedente:=0; y_precedente:=0; Disegna:=False; FuoriDominio:=False; NonNelDominio:=False; x:=0; while (x<PuntiDx) do begin Sostituisci(x); lunghezza:=lunghezza_funzione; Errore:=False; y:=CalcolaValore(1,lunghezza); if (y*scala<2147483647.0) AND (y*scala>-2147483648.0) AND NOT Errore then begin if Limita then begin if (x*scala<dx*scala) AND (x*scala>sx*scala) AND flag then DisegnaValore(Round(x*scala),Round(y*scala),LightGreen); end else if NOT Limita AND flag then DisegnaValore(Round(x*scala),Round(y*scala),LightGreen); if (k=4) AND ((Limita AND (x*scala<dx*scala) AND (x*scala>sx*scala)) OR NOT Limita) then begin array_x[num_valori]:=x*scala; if y<0 then y:=-y; array_y[num_valori]:=y*scala; k:=1; Inc(num_valori); end else if k<>4 then Inc(k); end; if Errore then begin if NOT NonNelDominio then begin Disegna:=False; FuoriDominio:=True; errore_da:=x; errore_a:=x; NonNelDominio:=True; end else begin errore_a:=x; end; end else begin if NonNelDominio AND Dominio then DisegnaDominio; FuoriDominio:=False; NonNelDominio:=False; end; x:=x+h; end; if Dominio AND FuoriDominio then DisegnaDominio; lunghezza:=lunghezza_funzione; for z:=1 to 100 do begin numero[z]:=''; temp[z]:=array_funzione[z]; array_funzione[z]:=''; end; for z:=1 to 100 do begin array_funzione[z]:=temp[z]; end; x_precedente:=0; y_precedente:=0; Disegna:=False; end; (*******************************************************************) procedure DisegnaMascherinaRotazione; begin SetViewPort(5,GetMaxY-35,GetMaxX-5,GetMaxY,ClipOn); ClearViewPort; SetViewPort(0,0,GetMaxX,GetMaxY,ClipOn); SetColor(DarkGray); SetBkColor(Black); Line(5,GetMaxY-35,GetMaxX-5,GetMaxY-35); Line(5,GetMaxY-35,5,GetMaxY-5); Line(GetMaxX-5,GetMaxY-35,GetMaxX-5,GetMaxY-5); Line(5,GetMaxY-5,GetMaxX-5,GetMaxY-5); SetColor(White); SetTextStyle(SmallFont,HorizDir,4); SetTextJustify(LeftText,TopText); OutTextXY(15,GetMaxY-35,'F1/F2 - Zoom +/-'); OutTextXY(15,GetMaxY-20,'F3 - Punti/Linee'); OutTextXY(160,GetMaxY-35,'F5/F6 - Risoluzione +/-'); OutTextXY(160,GetMaxY-20,'F10 - Griglia'); OutTextXY(325,GetMaxY-35,'INVIO - Grafico'); OutTextXY(325,GetMaxY-20,'ESC - Esci'); end; (*******************************************************************) procedure VisualizzaGrafico; var c:Char; LowMode,HiMode:Integer; begin repeat (*Registrazione dei drivers grafici*) if RegisterBGIdriver(@CGADriverProc)<0 then Abort('CGA'); if RegisterBGIdriver(@EGAVGADriverProc)<0 then Abort('EGA/VGA'); if RegisterBGIdriver(@HercDriverProc)<0 then Abort('Herc'); if RegisterBGIdriver(@ATTDriverProc)<0 then Abort('AT&T'); if RegisterBGIdriver(@PC3270DriverProc)<0 then Abort('PC 3270'); (*Registrazione dei font*) if RegisterBGIfont(@GothicFontProc)<0 then Abort('Gothic'); if RegisterBGIfont(@SansSerifFontProc)<0 then Abort('SansSerif'); if RegisterBGIfont(@SmallFontProc)<0 then Abort('Small'); if RegisterBGIfont(@TriplexFontProc)<0 then Abort('Triplex'); grDriver:=Detect; InitGraph(grDriver,grMode,path); ErrCode:=GraphResult; if ErrCode<>grOK then begin if ErrCode=grFileNotFound then begin (*Creiamo la nostra finestra*) Window(1,1,80,25); TextBackground(Black); TextColor(LightGray); ClrScr; Writeln('Errore grafico: ', GraphErrorMsg(ErrCode)); Writeln; Writeln('Se non si desidera immettere il percorso dei drivers ora, premere Esc'); c:=ReadChar; if ord(c)<>27 then begin Writeln('Inserire il percorso dei drivers BGI:'); WriteLn; Readln(path); end else ErrCode:=grOK; end else begin Writeln('Errore grafico: ', GraphErrorMsg(ErrCode)); Delay(5000); Halt(1); end; end; until ErrCode=grOK; (*Impostiamo alcune caratteristiche della modalit? grafica*) GetModeRange(grDriver,LowMode,HiMode); SetGraphMode(HiMode); if ord(c)<>27 then begin if Grafico_Rotazione then Grafico else Rotazione; end; CloseGraph; end; (*******************************************************************) procedure Grafico; var ch:Char; done:Boolean; begin if NOT InizializzatoX then begin AsseXx1:=0; AsseXy1:=GetMaxY div 2; AsseXx2:=GetMaxX; AsseXy2:=GetMaxY div 2; InizializzatoX:=True; end; if NOT InizializzatoY then begin AsseYx1:=GetMaxX div 2; AsseYy1:=0; AsseYx2:=GetMaxX div 2; AsseYy2:=GetMaxY; InizializzatoY:=True; end; DisegnaAssi; DisegnaNumeri; DisegnaMascherinaInformazioni; DisegnaMascherinaTasti; DisegnaTitolo('Grafico di Y='); DisegnaGrafico(True); Derivata; done:=False; repeat ch:=ReadChar; case ch of #13: (*CR*) begin done:=True; (*Richiamo della procedura*) Rotazione; end; #27: (*ESC*) done:=True; #59: (*F1*) begin if scala<640 then begin scala:=scala*2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end else Beep; end; #60: (*F2*) begin if scala>20 then begin scala:=scala div 2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end else Beep; end; #61: (*F3*) begin Linee:=NOT Linee; DisegnaMascherinaInformazioni; if NOT Linee then begin DisegnaAssi; DisegnaNumeri; end; DisegnaGrafico(True); Derivata; end; #62: (*F4*) begin Radianti:=NOT Radianti; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; #63: (*F5*) begin if risoluzione>1 then begin risoluzione:=risoluzione div 2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end else Beep; end; #64: (*F6*) begin if risoluzione<GetMaxX/40 then begin risoluzione:=risoluzione*2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end else Beep; end; #65: (*F7*) begin Dominio:=NOT Dominio; DisegnaMascherinaInformazioni; if NOT Dominio then begin DisegnaAssi; DisegnaNumeri; end; DisegnaGrafico(True); Derivata; end; #66: (*F8*) begin DisegnaDerivata:=NOT DisegnaDerivata; DisegnaMascherinaInformazioni; if NOT DisegnaDerivata then begin DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); end; Derivata; end; #67: (*F9*) begin (*Assegnazione dei valori standard delle posizioni degli assi*) AsseXx1:=0; AsseXy1:=GetMaxY div 2; AsseXx2:=GetMaxX; AsseXy2:=GetMaxY div 2; AsseYx1:=GetMaxX div 2; AsseYy1:=0; AsseYx2:=GetMaxX div 2; AsseYy2:=GetMaxY; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; #68: (*F10*) begin Griglia:=NOT Griglia; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; #72: (*Freccia in alto*) begin Inc(AsseXy1,30); Inc(AsseXy2,30); DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; #75: (*Freccia a sinistra*) begin Inc(AsseYx1,30); Inc(AsseYx2,30); DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; #77: (*Freccia a destra*) begin Dec(AsseYx1,30); Dec(AsseYx2,30); DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; #80: (*Freccia in basso*) begin Dec(AsseXy1,30); Dec(AsseXy2,30); DisegnaAssi; DisegnaNumeri; DisegnaGrafico(True); Derivata; end; else Beep; end; until done; end; (*******************************************************************) procedure Rotazione; var ch:Char; old_griglia,old_dominio,old_derivata,old_linee,done:Boolean; begin if NOT InizializzatoX then begin AsseXx1:=0; AsseXy1:=GetMaxY div 2; AsseXx2:=GetMaxX; AsseXy2:=GetMaxY div 2; InizializzatoX:=True; end; if NOT InizializzatoY then begin AsseYx1:=GetMaxX div 2; AsseYy1:=0; AsseYx2:=GetMaxX div 2; AsseYy2:=GetMaxY; InizializzatoY:=True; end; (*Salvataggio valori vecchi*) old_griglia:=Griglia; old_dominio:=Dominio; old_derivata:=DisegnaDerivata; old_linee:=Linee; (*Assegnazione dei nuovi valori (provvisori)*) Griglia:=False; Dominio:=False; DisegnaDerivata:=False; Linee:=True; (*Assegnazione dei valori standard delle posizioni degli assi*) AsseXx1:=0; AsseXy1:=GetMaxY div 2; AsseXx2:=GetMaxX; AsseXy2:=GetMaxY div 2; AsseYx1:=GetMaxX div 2; AsseYy1:=0; AsseYx2:=GetMaxX div 2; AsseYy2:=GetMaxY; DisegnaAssi; DisegnaMascherinaInformazioni; DisegnaMascherinaRotazione; DisegnaTitolo('Grafico di rotazione di Y='); DisegnaGrafico(False); RuotaCurva; done:=False; repeat ch:=ReadChar; case ch of #13: (*CR*) begin done:=True; (*Ripristino dei valori vecchi*) Griglia:=old_griglia; Dominio:=old_dominio; DisegnaDerivata:=old_derivata; Linee:=old_linee; (*Richiamo della procedura*) Grafico; end; #27: (*ESC*) done:=True; #59: (*F1*) begin if scala<640 then begin scala:=scala*2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaGrafico(False); RuotaCurva; end else Beep; end; #60: (*F2*) begin if scala>20 then begin scala:=scala div 2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaGrafico(False); RuotaCurva; end else Beep; end; #61: (*F3*) begin Linee:=NOT Linee; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaGrafico(False); RuotaCurva; end; #63: (*F5*) begin if risoluzione>1 then begin risoluzione:=risoluzione div 2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaGrafico(False); RuotaCurva; end else Beep; end; #64: (*F6*) begin if risoluzione<GetMaxX/40 then begin risoluzione:=risoluzione*2; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaGrafico(False); RuotaCurva; end else Beep; end; #68: (*F10*) begin Griglia:=NOT Griglia; DisegnaMascherinaInformazioni; DisegnaAssi; DisegnaGrafico(False); RuotaCurva; end; else Beep; end; until done; (*Ripristino dei valori vecchi*) Griglia:=old_griglia; Dominio:=old_dominio; DisegnaDerivata:=old_derivata; Linee:=old_linee; end; (*******************************************************************) procedure Derivata; var x,y,y1,y2:extended; old_linee,return_value:Boolean; z:Integer; temp:array[1..100] of string; begin if DisegnaDerivata then begin (*Salviamo alcuni valori*) old_linee:=Linee; Linee:=False; (*Copiamo il nostro array in un nuovo array*) for z:=1 to 100 do numero[z]:=array_funzione[z]; lunghezza_funzione:=lunghezza; (*Impostiamo l'area di disegno*) SetViewPort(24,31,GetMaxX-6,GetMaxY-75,ClipOn); (*Disegnamo la derivata dal centro a destra...*) Disegna:=False; x_precedente:=0; y_precedente:=0; x:=0; h:=1/100; while x<PuntiDx do begin Errore:=False; Sostituisci(x+0.01); lunghezza:=lunghezza_funzione; y1:=CalcolaValore(1,lunghezza); if Errore then begin Disegna:=False; Errore:=False; Sostituisci(x); lunghezza:=lunghezza_funzione; y:=CalcolaValore(1,lunghezza); if NOT Errore then begin PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala),White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala),White); end; end else if NOT Errore then begin Sostituisci(x-0.01); lunghezza:=lunghezza_funzione; y2:=CalcolaValore(1,lunghezza); y:=(y1-y2)/0.02; if (Errore) OR ((y*scala<2147483647.0) AND (y*scala>-2147483648.0) AND (Round(y*scala)=0)) then begin Disegna:=False; Errore:=False; Sostituisci(x); lunghezza:=lunghezza_funzione; y:=CalcolaValore(1,lunghezza); if NOT Errore then begin PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala),White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala),White); end; end else if (y*scala<2147483647.0) AND (y*scala>-2147483648.0) AND NOT Errore then begin if Limita then begin if (x*scala<dx*scala) AND (x*scala>sx*scala) then DisegnaValore(Round(x*scala),Round(y*scala),LightMagenta); end else if NOT Limita then DisegnaValore(Round(x*scala),Round(y*scala),LightMagenta) end else if Errore then Disegna:=False; end else Disegna:=False; x:=x+h; end; (*... e dal centro a sinistra*) Disegna:=False; x_precedente:=0; y_precedente:=0; x:=0; while x>-PuntiSx do begin Disegna:=False; Errore:=False; Sostituisci(x+0.01); lunghezza:=lunghezza_funzione; y1:=CalcolaValore(1,lunghezza); if Errore then begin Errore:=False; Sostituisci(x); lunghezza:=lunghezza_funzione; y:=CalcolaValore(1,lunghezza); if NOT Errore then begin PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala),White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala),White); end; end else if NOT Errore then begin Sostituisci(x-0.01); lunghezza:=lunghezza_funzione; y2:=CalcolaValore(1,lunghezza); y:=(y1-y2)/0.02; if (Errore) OR ((y*scala<2147483647.0) AND (y*scala>-2147483648.0) AND (Round(y*scala)=0)) then begin Disegna:=False; Errore:=False; Sostituisci(x); lunghezza:=lunghezza_funzione; y:=CalcolaValore(1,lunghezza); if NOT Errore then begin PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala),White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala),AsseXy1-Round(y*scala)-1,White); PutPixel(AsseYx1+Round(x*scala)-1,AsseXy1-Round(y*scala),White); end; end else if (y*scala<2147483647.0) AND (y*scala>-2147483648.0) AND NOT Errore then begin if Limita then begin if (x*scala<dx*scala) AND (x*scala>sx*scala) then DisegnaValore(Round(x*scala),Round(y*scala),LightMagenta); end else if NOT Limita then DisegnaValore(Round(x*scala),Round(y*scala),LightMagenta) end else if Errore then Disegna:=False; end else Disegna:=False; x:=x-h; end; lunghezza:=lunghezza_funzione; for z:=1 to 100 do begin numero[z]:=''; temp[z]:=array_funzione[z]; array_funzione[z]:=''; end; for z:=1 to 100 do begin array_funzione[z]:=temp[z]; end; x_precedente:=0; y_precedente:=0; (*Ripristiniamo i valori salvati*) Linee:=old_linee; end; end; (*******************************************************************) procedure RuotaCurva; var theta,alpha,n,i,k:Integer; x_succ1,y_succ1,x_succ2,y_succ2,x_prec,y_prec,x,y:extended; sin_look,cos_look:array[1..360] of real; temp:real; Congiungi:Boolean; begin (*Preparazione delle SIN e COS lookup tables*) for i:=1 to 360 do begin sin_look[i]:=sin(i*Pi/180); cos_look[i]:=cos(i*Pi/180); end; (*Inizializzazione di alcune variabili*) alpha:=330; theta:=1; x_prec:=0; y_prec:=0; Congiungi:=False; (*Impostiamo il colore ed il tipo di fill*) SetColor(Yellow); SetFillStyle(SolidFill,LightBlue); (*Impostiamo la zona di schermo in cui disegneremo*) SetViewPort(24,31,GetMaxX-6,GetMaxY-76,ClipOn); (*Ordiniamo i nostri arrays di valori (in base alla x, ordine crescente)*) for i:=1 to num_valori-1 do begin for k:=i+1 to num_valori-1 do if array_x[i]>array_x[k] then begin temp:=array_x[i]; array_x[i]:=array_x[k]; array_x[k]:=temp; temp:=array_y[i]; array_y[i]:=array_y[k]; array_y[k]:=temp; end; end; (*Controllo sui valori immagazzinati*) k:=num_valori-1; for i:=1 to k do begin if (AsseXy1-array_y[i]<0) OR (AsseXy1-array_y[i]>GetMaxY) OR (AsseYx1-array_x[i]<0) OR (AsseYx1-array_x[i]>GetMaxX) then begin for n:=i to k do begin array_x[n]:=array_x[n+1]; array_y[n]:=array_y[n+1]; end; Dec(num_valori); Dec(i); end; end; (*Avevamo incrementato di un valore in pi? la variabile "num_valori" durante il salvataggio dei punti*) Dec(num_valori); (*Ciclo per il calcolo ed il disegno dei punti sullo schermo*) while alpha>=180 do begin for i:=1 to num_valori do begin x:=array_x[i]-array_y[i]*sin_look[alpha]*sin_look[theta]; y:=array_y[i]*cos_look[alpha]-array_y[i]*sin_look[alpha]*cos_look[theta]; if (AsseXy1-Round(y)>-32768) AND (AsseXy1-Round(y)<32767) then begin if NOT Linee then begin PutPixel(AsseYx1+Round(x),AsseXy1-Round(y),Yellow); end else begin if Congiungi then begin if (AsseXy1-Round(y_prec)>-32768) AND (AsseXy1-Round(y_prec)<32767) then begin vertici[1].x:=AsseYx1+Round(x); vertici[1].y:=AsseXy1-Round(y); vertici[2].x:=AsseYx1+Round(x_prec); vertici[2].y:=AsseXy1-Round(y_prec); if (i>0) then begin x_succ1:=array_x[i]-array_y[i]*sin_look[alpha-5]*sin_look[theta]; y_succ1:=array_y[i]*cos_look[alpha-5]-array_y[i]*sin_look[alpha-5] *cos_look[theta]; x_succ2:=array_x[i-1]-array_y[i-1]*sin_look[alpha-5] *sin_look[theta]; y_succ2:=array_y[i-1]*cos_look[alpha-5]-array_y[i-1] *sin_look[alpha-5]*cos_look[theta]; if (x_succ1>-32768) AND (x_succ1<32767) AND (y_succ1>-32768) AND (y_succ1<32767) AND (x_succ2>-32768) AND (x_succ2<32767) AND (y_succ2>-32768) AND (y_succ2<32767) then begin vertici[3].x:=AsseYx1+Round(x_succ2); vertici[3].y:=AsseXy1-Round(y_succ2); vertici[4].x:=AsseYx1+Round(x_succ1); vertici[4].y:=AsseXy1-Round(y_succ1); FillPoly(4,vertici); end; end; end else Congiungi:=False; end else Congiungi:=True; end; end; x_prec:=x; y_prec:=y; end; Dec(alpha,5); Congiungi:=False; end; end; (******************************************************************** * Funzioni e procedure per le finestre del programma ********************************************************************) function ReadChar:Char; var ch:Char; begin ch:=ReadKey; if ch=#0 then ch:=ReadKey; ReadChar:=ch; end; (*******************************************************************) procedure Beep; begin NoSound; Sound(2000); Delay(150); NoSound; end; (*******************************************************************) procedure SchermataDiBenvenuto; var c:Char; begin (*Creiamo la nostra finestra*) Window(1,1,80,25); TextBackground(Black); TextColor(LightBlue); ClrScr; Writeln(' ANALIZZATORE DI FUNZIONI MATEMATICHE - 4'); Writeln(' di Marco Olivo, 1998,1999'); Writeln; Writeln; TextColor(Yellow); Writeln(' Questo programma ? in grado di tracciare il grafico approssimato di una'); Writeln(' qualsiasi funzione. Queste sono le funzioni permesse dal programma:'); Writeln; TextColor(White); Writeln(' arcsen/arcsin(x) ????????> arco-seno di x'); Writeln(' arccos(x) ????????> arco-coseno di x'); Writeln(' arccotg/arccotag/arccotan(x) ????????> arco-cotangente di x'); Writeln(' sen/sin(x) ????????> seno di x'); Writeln(' cos(x) ????????> coseno di x'); Writeln(' tan/tag/tg(x) ????????> tangente di x'); Writeln(' arctan/arctag/atag/atan ????????> arco-tangente di x'); Writeln(' cotan/cotag/cotg(x) ????????> cotangente di x'); Writeln(' log/ln(x) ????????> logaritmo naturale di x'); Writeln(' a^x,e^x ????????> elevamento ad esponente x'); Writeln(' abs,sgn(x) ????????> valore assoluto, segno di x'); Writeln(' sqr,sqrt(x) ????????> quadrato, radice quadrata'); Writeln(' sinh,cosh,tanh(x) ????????> sin, cos, tan iperbolici'); Writeln(' asinh,acosh,atanh(x) ????????> asin, acos, atan iperbolici'); Writeln(' int(x) ????????> parte intera di x'); Writeln; TextColor(LightCyan+Blink); Writeln(' Premere un tasto per iniziare il programma'); Beep; c:=ReadKey; end; (*******************************************************************) procedure Messaggio(testo:string); var lunghezza_messaggio:Integer; k:Integer; begin TextColor(Yellow); TextBackground(Blue); Window(2,24,79,25); GotoXY(1,1); Write(' '); lunghezza_messaggio:=Length(testo); if (lunghezza_messaggio<=75) then begin Write(testo); for k:=1+lunghezza_messaggio to 77 do Write(' '); end; end; (*******************************************************************) procedure MenuPrincipale; begin TextBackground(Black); TextColor(Yellow); Window(1,1,80,25); GotoXY(25,4); Write('Men? principale'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextBackground(Black); ClrScr; (*Scriviamo nella nostra finestra*) TextColor(LightGreen); GotoXY(12,17); Write('Freccia Su/Gi?: cambiamento funzione'); TextColor(White); GotoXY(10,2); Write('nserimento della funzione'); GotoXY(10,4); Write('isualizzazione del grafico della funzione'); GotoXY(10,5); Write('strapolazione dei punti dal grafico'); GotoXY(10,6); Write('imitazione del dominio'); GotoXY(10,7); Write('otazione della curva'); GotoXY(9,9); Write('Informazioni/ uida'); GotoXY(9,10); Write('V lori di default'); GotoXY(10,12); Write('alvare lista funzioni'); GotoXY(10,13); Write('aricare lista funzioni'); GotoXY(10,15); Write('scita'); TextColor(LightRed); GotoXY(9,2); Write('I'); GotoXY(9,4); Write('V'); GotoXY(9,5); Write('E'); GotoXY(9,6); Write('L'); GotoXY(9,7); Write('R'); GotoXY(22,9); Write('g'); GotoXY(10,10); Write('a'); GotoXY(9,12); Write('S'); GotoXY(9,13); Write('C'); GotoXY(9,15); Write('U'); end; (*******************************************************************) procedure InserisciFunzione(espressione:string); var i:Integer; posizione:Integer; ch:Char; done:Boolean; funzione_inserita,tasto:string; begin TextBackground(Black); TextColor(Yellow); Window(1,1,80,25); GotoXY(22,4); Write('Inserimento funzione'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextBackground(Black); ClrScr; TextColor(White); (*Richiediamo la funzione*) Writeln; Writeln('Immettere la funzione y=f(x) da valutare:'); Writeln; TextColor(LightGray); Writeln('y='); TextColor(LightGreen); GotoXY(15,16); Writeln('Freccia Su/Gi?: cambiamento funzione'); GotoXY(25,17); Write('Esc: esci'); TextColor(LightGray); GotoXY(3,4); funzione:=''; funzione_inserita:=espressione; if espressione<>'' then Write(espressione) else begin Write(lista_funzioni[funzione_corrente]); funzione_inserita:=lista_funzioni[funzione_corrente]; end; posizione:=Length(funzione_inserita)+2; done:=False; GotoXY(1+posizione,4); repeat ch:=ReadChar; case ch of #8: (*BS*) begin if posizione>2 then begin tasto:=''; for i:=1 to (posizione-3) do tasto:=Concat(tasto,funzione_inserita[i]); funzione_inserita:=tasto; (*Creiamo la nostra finestra*) Window(4,5,58,21); TextColor(LightGray); TextBackground(Black); GotoXY(posizione,4); Write(' '); Dec(posizione); GotoXY(1+posizione,4); end; if posizione=2 then funzione_inserita:=''; end; #13: (*CR*) done:=True; #27: (*ESC*) begin done:=True; funzione_inserita:=''; end; #72: (*Freccia in alto*) begin if funzione_corrente>1 then begin SelezionaFunzione(funzione_corrente-1,funzione_corrente); Dec(funzione_corrente); if lista_funzioni[funzione_corrente]<>'' then Messaggio(lista_funzioni[funzione_corrente]) else Messaggio('Consultare la guida in linea per maggiori informazioni sul programma'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextColor(LightGray); TextBackground(Black); for i:=3 to 57 do begin GotoXY(i,4); Write(' '); end; GotoXY(3,4); Write(lista_funzioni[funzione_corrente]); funzione_inserita:=lista_funzioni[funzione_corrente]; posizione:=Length(funzione_inserita)+2; GotoXY(1+posizione,4); end else Beep; end; #75,#77: (*Freccia a sinistra, freccia a destra*) Beep; #80: (*Freccia in basso*) begin if funzione_corrente<16 then begin SelezionaFunzione(funzione_corrente+1,funzione_corrente); Inc(funzione_corrente); if lista_funzioni[funzione_corrente]<>'' then Messaggio(lista_funzioni[funzione_corrente]) else Messaggio('Consultare la guida in linea per maggiori informazioni sul programma'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextColor(LightGray); TextBackground(Black); for i:=3 to 57 do begin GotoXY(i,4); Write(' '); end; GotoXY(3,4); Write(lista_funzioni[funzione_corrente]); funzione_inserita:=lista_funzioni[funzione_corrente]; posizione:=Length(funzione_inserita)+2; GotoXY(1+posizione,4); end else Beep; end; else case ch of 'A'..'Z','a'..'z','0'..'9','+', '-', '*', '/','^','(',')': begin if posizione<54 then begin tasto:=ch; funzione_inserita:=Concat(funzione_inserita,tasto); Inc(posizione); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextColor(LightGray); TextBackground(Black); GotoXY(posizione,4); Write(tasto); end else Beep; end; else Beep; end; end; until done; if funzione_inserita='' then funzione_inserita:=lista_funzioni[funzione_corrente]; lunghezza:=Length(funzione_inserita); funzione:=funzione_inserita; if lunghezza>0 then begin (*Facciamo di modo che la nostra stringa sia tutta in maiuscolo*) for i:=1 to lunghezza do funzione[i]:=UpCase(funzione_inserita[i]); LeggiFunzione; if (ControllaSintassi=True) then begin CalcolaPrecedenze; (*Scriviamo la funzione nel nostro array delle ultime 16 funzioni*) lista_funzioni[funzione_corrente]:=funzione_inserita; if numero_funzioni<funzione_corrente then numero_funzioni:=funzione_corrente; Messaggio('E'' ora possibile visualizzare il grafico'); end else InserisciFunzione(funzione_inserita); end else begin funzione_inserita:=lista_funzioni[funzione_corrente]; (*Facciamo di modo che la nostra stringa sia tutta in maiuscolo*) for i:=1 to lunghezza do funzione[i]:=UpCase(funzione_inserita[i]); LeggiFunzione; if (ControllaSintassi=True) then begin CalcolaPrecedenze; (*Scriviamo la funzione nel nostro array delle ultime 16 funzioni*) lista_funzioni[funzione_corrente]:=funzione_inserita; if numero_funzioni<funzione_corrente then numero_funzioni:=funzione_corrente; Messaggio('E'' ora possibile visualizzare il grafico'); end else InserisciFunzione(funzione_inserita); end; end; (*******************************************************************) procedure EstrapolaPunti; var ascissa:string; number:real; code:Integer; c:Char; valore:extended; begin TextBackground(Black); TextColor(Yellow); Window(1,1,80,25); GotoXY(22,4); Write('Estrapolazione punti'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextBackground(Black); ClrScr; TextColor(White); Writeln; Writeln('Inserire l''ascissa del punto (INVIO=nessuna):'); Writeln; TextColor(LightGray); Write('x='); GotoXY(3,4); Readln(ascissa); if ascissa<>'' then begin Val(ascissa,number,code); if code=0 then begin lunghezza_funzione:=lunghezza; Sostituisci(number); TextColor(Red); Writeln; Errore:=False; lunghezza_funzione:=lunghezza; valore:=CalcolaValore(1,lunghezza); if NOT Errore then Writeln('L''ordinata del punto scelto ?: ',valore:8:8) else Writeln('Il valore scelto non appartiene al dominio'); lunghezza:=lunghezza_funzione; end else begin TextColor(Yellow+Blink); TextBackground(Red); Writeln; Writeln(' Errore: il valore inserito non ? un numero reale '); end; c:=ReadKey; end; end; (*******************************************************************) procedure LimitaDominio; var margine_dx,margine_sx:string; code1,code2:Integer; c:Char; begin TextBackground(Black); TextColor(Yellow); Window(1,1,80,25); GotoXY(20,4); Write('Limitazione del dominio'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextBackground(Black); ClrScr; TextColor(White); if Conferma('Si ? proprio sicuri di voler limitare il dominio?') then begin ClrScr; Writeln; Writeln('Inserire l''estremo sinistro:'); Writeln; TextColor(LightGray); Readln(margine_sx); Writeln; TextColor(White); Writeln('Inserire l''estremo destro:'); Writeln; TextColor(LightGray); Readln(margine_dx); Val(margine_sx,sx,code1); Val(margine_dx,dx,code2); if (code1=0) AND (code2=0) then begin if sx>dx then begin TextColor(Yellow+Blink); TextBackground(Red); Writeln; Writeln(' Errore: il margine SX ? maggiore del margine DX '); Limita:=False; c:=ReadKey; end else Limita:=True; end else begin TextColor(Yellow+Blink); TextBackground(Red); Writeln; Writeln(' Errore: il valore non ? reale '); Limita:=False; c:=ReadKey; end; end else Limita:=False; end; (*******************************************************************) procedure Informazioni_Guida; begin SchermataDiBenvenuto; end; (*******************************************************************) function Conferma(testo:string):Boolean; var ch:Char; done,scelta:Boolean; begin (*Creiamo la nostra finestra*) Window(4,5,58,21); TextBackground(Black); ClrScr; TextColor(LightGray); (*Scriviamo nella nostra finestra*) Writeln; Writeln(testo); TextBackground(Red); TextColor(Black); GotoXY(18,6); Write(' S? '); TextBackground(Black); TextColor(White); GotoXY(32,6); Write(' No '); done:=False; scelta:=True; repeat ch:=ReadChar; case ch of #13: (*CR*) begin done:=True; scelta:=scelta; end; #27: (*ESC*) begin done:=True; scelta:=False; end; 's','S': begin done:=True; scelta:=True; end; 'n','N': begin done:=True; scelta:=False; end; #75: (*Freccia a sinistra*) begin scelta:=True; TextBackground(Red); TextColor(Black); GotoXY(18,6); Write(' S? '); TextBackground(Black); TextColor(White); GotoXY(32,6); Write(' No '); end; #77: (*Freccia a destra*) begin scelta:=False; TextBackground(Black); TextColor(White); GotoXY(18,6); Write(' S? '); TextBackground(Red); TextColor(Black); GotoXY(32,6); Write(' No '); end; else Beep; end; until done; Conferma:=scelta; end; (*******************************************************************) function ConfermaUscita:Boolean; begin if (Conferma('Si ? proprio sicuri di voler uscire dal programma?')=True) then ConfermaUscita:=True else ConfermaUscita:=False; end; (*******************************************************************) procedure ImpostaValoriDiDefault; begin (*Assegnazione dei valori standard delle posizioni degli assi*) AsseXx1:=0; AsseXy1:=GetMaxY div 2; AsseXx2:=GetMaxX; AsseXy2:=GetMaxY div 2; AsseYx1:=GetMaxX div 2; AsseYy1:=0; AsseYx2:=GetMaxX div 2; AsseYy2:=GetMaxY; risoluzione:=1; (*Vicinanza dei punti del grafico*) scala:=40; (*Scala del grafico (100%)*) Linee:=False; (*Grafico a punti o linee (punti)*) Dominio:=True; (*Disegnamo il dominio*) Radianti:=False; (*Numeri interi sul grafico*) Limita:=False; (*Dominio non limitato*) DisegnaDerivata:=False; (*Non disegnamo la derivata*) path:='a:\'; (*Directory dei drivers BGI*) Grafico_Rotazione:=True; (*Visualizziamo il grafico e non la rotazione*) Griglia:=True; (*Visualizziamo la griglia*) end; (*******************************************************************) procedure ImpostaDefault; begin TextBackground(Black); TextColor(Yellow); Window(1,1,80,25); GotoXY(20,4); Write('Impostazione valori di default'); if (Conferma('Con questa operazione si elimineranno tutti i settaggi correnti. Continuare?')=True) then begin (*Imposta i valori di default*) ImpostaValoriDiDefault; end; end; (*******************************************************************) function FileExists(FileName:string):Boolean; var f:file; begin (*"Input/Output Checking Switch": attiva la generazione di codice che controlla i risultati delle chiamate a procedure di I/O*) {$I-} Assign(f, FileName); Reset(f); Close(f); (*"Input/Output Checking Switch": (ri)attiva la generazione di codice che controlla i risultati delle chiamate a procedure di I/O*) {$I+} FileExists:=(IOResult=0) AND (FileName<>''); end; (*******************************************************************) procedure CaricaListaFunzioni(FileName:string); var f:Text; i:Integer; str:string; begin i:=1; TextColor(LightRed); if FileExists(FileName) then begin for i:=1 to 16 do lista_funzioni[i]:=''; funzione_corrente:=1; numero_funzioni:=0; Assign(f,FileName); Reset(f); Readln(f,str); lista_funzioni[funzione_corrente]:=str; Inc(funzione_corrente); Inc(numero_funzioni); while NOT Eof(f) do begin Readln(f,str); if (funzione_corrente<17) AND (numero_funzioni<17) then begin lista_funzioni[funzione_corrente]:=str; Inc(funzione_corrente); Inc(numero_funzioni); end; end; Close(f); end else FileDelleFunzioni:=''; end; (*******************************************************************) procedure SalvaListaFunzioni(FileName:string); var f:Text; i:Integer; begin Assign(f,FileName); Rewrite(f); for i:=1 to numero_funzioni do if lista_funzioni[i]<>'' then Writeln(f,lista_funzioni[i]); Close(f); end; (*******************************************************************) procedure MostraListaFunzioni; var n,k,i:Integer; begin (*Creiamo la nostra finestra*) Window(63,5,77,22); TextBackground(Black); TextColor(LightGray); ClrScr; for i:=5 to 20 do begin GotoXY(68,i); TextColor(White); Write('y=?(x):'); TextColor(DarkGray); GotoXY(73,i); Write(' -------'); end; i:=1; TextColor(LightCyan); while (i<numero_funzioni+1) do begin if (Length(lista_funzioni[i])<8) AND (lista_funzioni[i]<>'') then begin GotoXY(9,i); Write(lista_funzioni[i]); for k:=Length(lista_funzioni[i]) to 6 do begin GotoXY(9+k,i); Write(' '); end; end else if (Length(lista_funzioni[i])>=8) AND (lista_funzioni[i]<>'') then begin for k:=1 to 7 do begin GotoXY(8+k,i); Write(lista_funzioni[i][k]); end; end; Inc(i); end; end; (*******************************************************************) procedure SelezionaFunzione(da_selezionare,precedente:Integer); var k:Integer; begin (*Creiamo la nostra finestra*) Window(1,1,80,25); TextBackground(Black); TextColor(White); (*Togliamo la vecchia selezione...*) GotoXY(63,precedente+4); Write('y=?(x):'); TextColor(DarkGray); GotoXY(70,precedente+4); Write(' -------'); TextColor(LightCyan); if (Length(lista_funzioni[precedente])<8) AND (lista_funzioni[precedente]<>'') then begin GotoXY(71,precedente+4); Write(lista_funzioni[precedente]); for k:=Length(lista_funzioni[precedente]) to 6 do begin GotoXY(71+k,precedente+4); Write(' '); end; end else if (Length(lista_funzioni[precedente])>=8) AND (lista_funzioni[precedente]<>'') then begin for k:=1 to 7 do begin GotoXY(70+k,precedente+4); Write(lista_funzioni[precedente][k]); end; end; (*... e mostriamo la nuova*) TextBackground(Red); TextColor(White); GotoXY(63,da_selezionare+4); Write('y=?(x):'); TextColor(DarkGray); GotoXY(70,da_selezionare+4); Write(' -------'); TextColor(Yellow); if (Length(lista_funzioni[da_selezionare])<8) AND (lista_funzioni[da_selezionare]<>'') then begin GotoXY(71,da_selezionare+4); Write(lista_funzioni[da_selezionare]); for k:=Length(lista_funzioni[da_selezionare]) to 6 do begin GotoXY(71+k,da_selezionare+4); Write(' '); end; end else if (Length(lista_funzioni[da_selezionare])>=8) AND (lista_funzioni[da_selezionare]<>'') then begin for k:=1 to 7 do begin GotoXY(70+k,da_selezionare+4); Write(lista_funzioni[da_selezionare][k]); end; end; end; (*******************************************************************) procedure ChiediNomeFile; var done:Boolean; ch:Char; posizione:Integer; tasto,precedente:string; begin TextBackground(Black); TextColor(Yellow); Window(1,1,80,25); GotoXY(21,4); Write('File delle funzioni'); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextBackground(Black); ClrScr; TextColor(White); Writeln; Writeln('Inserire il nome ed il percorso completo del file:'); Writeln; TextColor(LightGreen); GotoXY(25,17); Write('Esc: esci'); TextColor(LightGray); GotoXY(1,4); done:=False; Write(FileDelleFunzioni); posizione:=Length(FileDelleFunzioni); GotoXY(1+posizione,4); precedente:=FileDelleFunzioni; repeat ch:=ReadChar; case ch of #8: begin if posizione>0 then begin tasto:=''; for i:=1 to (posizione-1) do tasto:=Concat(tasto,FileDelleFunzioni[i]); FileDelleFunzioni:=tasto; (*Creiamo la nostra finestra*) Window(4,5,58,21); TextColor(LightGray); TextBackground(Black); GotoXY(posizione,4); Write(' '); Dec(posizione); GotoXY(1+posizione,4); end; if posizione=0 then FileDelleFunzioni:=''; end; #13: done:=True; #27: begin done:=True; FileDelleFunzioni:=precedente; end; #72: Beep; #75,#77: Beep; #80: Beep; else begin if posizione<54 then begin tasto:=ch; Delete(FileDelleFunzioni,posizione+1,1); Insert(tasto,FileDelleFunzioni,posizione+1); Inc(posizione); (*Creiamo la nostra finestra*) Window(4,5,58,21); TextColor(LightGray); TextBackground(Black); GotoXY(posizione,4); Write(tasto); end else Beep; end; end; until done; end; (*******************************************************************) procedure FinestraPrincipale; var ch:Char; done:Boolean; begin (*Creiamo la nostra finestra*) Window(1,1,80,25); TextBackground(Black); ClrScr; TextColor(LightBlue); Writeln(' ANALIZZATORE DI FUNZIONI MATEMATICHE - 4'); Writeln(' di Marco Olivo, 1998,1999'); Writeln; TextColor(DarkGray); Writeln(' ????????????????????????????????????????????????????????????????????????????'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ? ?? ?'); Writeln(' ????????????????????????????????????????????????????????????????????????????'); Messaggio('Consultare la guida in linea per maggiori informazioni sul programma'); MenuPrincipale; MostraListaFunzioni; SelezionaFunzione(funzione_corrente,funzione_corrente); if lista_funzioni[funzione_corrente]<>'' then Messaggio(lista_funzioni[funzione_corrente]); done:=False; repeat ch:=ReadChar; case ch of 'i','I': begin done:=True; InserisciFunzione(''); FinestraPrincipale; end; 'v','V': begin done:=True; if lunghezza>0 then begin Grafico_Rotazione:=True; VisualizzaGrafico; end else Beep; FinestraPrincipale; end; 'e','E': begin done:=True; if lunghezza>0 then EstrapolaPunti else Beep; FinestraPrincipale; end; 'l','L': begin done:=True; LimitaDominio; FinestraPrincipale; end; 'r','R': begin done:=True; if lunghezza>0 then begin Grafico_Rotazione:=False; VisualizzaGrafico; end else Beep; FinestraPrincipale; end; 'g','G': begin done:=True; Informazioni_Guida; FinestraPrincipale; end; 'a','A': begin done:=True; ImpostaDefault; FinestraPrincipale; end; #72: (*Freccia in alto*) begin if funzione_corrente>1 then begin SelezionaFunzione(funzione_corrente-1,funzione_corrente); Dec(funzione_corrente); if lista_funzioni[funzione_corrente]<>'' then Messaggio(lista_funzioni[funzione_corrente]) else Messaggio('Consultare la guida in linea per maggiori informazioni sul programma'); funzione:=lista_funzioni[funzione_corrente]; lunghezza:=Length(funzione); (*Facciamo di modo che la nostra stringa sia tutta in maiuscolo*) for i:=1 to lunghezza do funzione[i]:=UpCase(funzione[i]); LeggiFunzione; if (ControllaSintassi=True) then begin CalcolaPrecedenze; if numero_funzioni<funzione_corrente then numero_funzioni:=funzione_corrente; end else InserisciFunzione(funzione); end else Beep; end; #80: (*Freccia in basso*) begin if funzione_corrente<16 then begin SelezionaFunzione(funzione_corrente+1,funzione_corrente); Inc(funzione_corrente); if lista_funzioni[funzione_corrente]<>'' then Messaggio(lista_funzioni[funzione_corrente]) else Messaggio('Consultare la guida in linea per maggiori informazioni sul programma'); funzione:=lista_funzioni[funzione_corrente]; lunghezza:=Length(funzione); (*Facciamo di modo che la nostra stringa sia tutta in maiuscolo*) for i:=1 to lunghezza do funzione[i]:=UpCase(funzione[i]); LeggiFunzione; if (ControllaSintassi=True) then begin CalcolaPrecedenze; if numero_funzioni<funzione_corrente then numero_funzioni:=funzione_corrente; end else InserisciFunzione(funzione); end else Beep; end; 'c','C': begin done:=True; ChiediNomeFile; CaricaListaFunzioni(FileDelleFunzioni); funzione_corrente:=1; if lista_funzioni[funzione_corrente]<>'' then Messaggio(lista_funzioni[funzione_corrente]); funzione:=lista_funzioni[funzione_corrente]; lunghezza:=Length(funzione); (*Facciamo di modo che la nostra stringa sia tutta in maiuscolo*) for i:=1 to lunghezza do funzione[i]:=UpCase(funzione[i]); LeggiFunzione; if (ControllaSintassi=True) then begin CalcolaPrecedenze; if numero_funzioni<funzione_corrente then numero_funzioni:=funzione_corrente; end else InserisciFunzione(funzione); FinestraPrincipale; end; 's','S': begin done:=True; ChiediNomeFile; SalvaListaFunzioni(FileDelleFunzioni); FinestraPrincipale; end; #27,'u','U': begin if (ConfermaUscita=True) then begin done:=True; Window(1,1,80,25); TextColor(White); ClrScr; TextBackground(LightBlue); TextColor(White); Write(' ANALIZZATORE DI FUNZIONI MATEMATICHE - 4 di Marco Olivo, 1998 '); Delay(1000); end else MenuPrincipale; end; else Beep; end; until done; end; (******************************************************************** * Programma principale ********************************************************************) begin (*Impostiamo lo schermo secondo le nostre preferenze*) OrigMode:=LastMode; TextMode(CO80); (*Ripuliamo lo schermo*) ClrScr; (*Impostiamo i valori di default*) ImpostaValoriDiDefault; (*Inizializzazione di alcune variabili*) for i:=1 to 100 do begin array_funzione[i]:=''; (*Array per la funzione*) numero[i]:=''; (*Array per la funzione*) end; for i:=1 to 500 do begin array_x[i]:=0; (*Array per la rotazione*) array_y[i]:=0; (*Array per la rotazione*) end; num_valori:=0; (*Numero di valori salvati per la rotazione*) numero_funzioni:=0; (*Nessuna funzione correntemente immagazzinata*) for i:=1 to 16 do lista_funzioni[i]:=''; (*Array delle ultime 16 funzioni*) funzione_corrente:=1; (*Funzione correntemente scelta*) FileDelleFunzioni:=''; (*Nessun file correntemente aperto*) Disegna:=False; (*Non disegnamo la prima linea*) Errore:=False; (*Non ci sono errori*) lunghezza:=0; (*Nessuna funzione*) x_precedente:=0; (*Evitiamo che vengano disegnate parti di curva sbagliate*) y_precedente:=0; (*Evitiamo che vengano disegnate parti di curva sbagliate*) InizializzatoX:=False; InizializzatoY:=False; (*Mostriamo la schermata di benvenuto*) SchermataDiBenvenuto; (*"Costruiamo" la nostra finestra principale*) FinestraPrincipale; (*Facciamo ritornare lo schermo alle impostazioni originali*) NormVideo; TextMode(OrigMode); TextBackground(Black); TextColor(LightGray); ClrScr; end.
unit kwCompiledWordWorker; {* Базовый класс для исполняемых скомпилированных слов. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwCompiledWordWorker.pas" // Стереотип: "SimpleClass" // Элемент модели: "TkwCompiledWordWorker" MUID: (4DCBD50101CB) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , kwSourcePointWord , tfwScriptingInterfaces ; type RkwCompiledWordWorker = class of TkwCompiledWordWorker; TkwCompiledWordWorker = {abstract} class(TkwSourcePointWord) {* Базовый класс для исполняемых скомпилированных слов. } private f_WordToWork: TtfwWord; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aWordToPush: TtfwWord; aWordToRun: TtfwWord; const aCtx: TtfwContext); reintroduce; virtual; public property WordToWork: TtfwWord read f_WordToWork; end;//TkwCompiledWordWorker {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , l3Base //#UC START# *4DCBD50101CBimpl_uses* //#UC END# *4DCBD50101CBimpl_uses* ; constructor TkwCompiledWordWorker.Create(aWordToPush: TtfwWord; aWordToRun: TtfwWord; const aCtx: TtfwContext); //#UC START# *4DCBB0CD028D_4DCBD50101CB_var* //#UC END# *4DCBB0CD028D_4DCBD50101CB_var* begin //#UC START# *4DCBB0CD028D_4DCBD50101CB_impl* inherited Create(aCtx); aWordToPush.SetRefTo(f_WordToWork); //#UC END# *4DCBB0CD028D_4DCBD50101CB_impl* end;//TkwCompiledWordWorker.Create procedure TkwCompiledWordWorker.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4DCBD50101CB_var* //#UC END# *479731C50290_4DCBD50101CB_var* begin //#UC START# *479731C50290_4DCBD50101CB_impl* FreeAndNil(f_WordToWork); inherited; //#UC END# *479731C50290_4DCBD50101CB_impl* end;//TkwCompiledWordWorker.Cleanup initialization TkwCompiledWordWorker.RegisterClass; {* Регистрация TkwCompiledWordWorker } {$IfEnd} // NOT Defined(NoScripts) end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ActionSheet; interface {$SCOPEDENUMS ON} uses System.Classes, FMX.Platform, FMX.Types, FGX.ActionSheet.Types, FGX.Consts; type { TfgActionSheet } TfgCustomActionSheet = class(TFmxObject) public const DefaultUseUIGuidline = True; private FActions: TfgActionsCollections; FUseUIGuidline: Boolean; FTitle: string; FActionSheetService: IFGXActionSheetService; procedure SetActions(const Value: TfgActionsCollections); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Show; virtual; function Supported: Boolean; property ActionSheetService: IFGXActionSheetService read FActionSheetService; public property Actions: TfgActionsCollections read FActions write SetActions; property UseUIGuidline: Boolean read FUseUIGuidline write FUseUIGuidline default DefaultUseUIGuidline; property Title: string read FTitle write FTitle; end; [ComponentPlatformsAttribute(fgMobilePlatforms)] TfgActionSheet = class(TfgCustomActionSheet) published property Actions; property UseUIGuidline; property Title; end; implementation uses System.SysUtils, FGX.Asserts {$IFDEF IOS} , FGX.ActionSheet.iOS {$ENDIF} {$IFDEF ANDROID} , FGX.ActionSheet.Android {$ENDIF} ; { TActionSheet } constructor TfgCustomActionSheet.Create(AOwner: TComponent); begin inherited Create(AOwner); FActions := TfgActionsCollections.Create(Self); FUseUIGuidline := DefaultUseUIGuidline; TPlatformServices.Current.SupportsPlatformService(IFGXActionSheetService, FActionSheetService); end; destructor TfgCustomActionSheet.Destroy; begin FActionSheetService := nil; FreeAndNil(FActions); inherited Destroy; end; procedure TfgCustomActionSheet.SetActions(const Value: TfgActionsCollections); begin AssertIsNotNil(Value); FActions.Assign(Value); end; procedure TfgCustomActionSheet.Show; begin if Supported then FActionSheetService.Show(Title, Actions, UseUIGuidline); end; function TfgCustomActionSheet.Supported: Boolean; begin Result := ActionSheetService <> nil; end; initialization RegisterFmxClasses([TfgCustomActionSheet, TfgActionSheet]); {$IF Defined(IOS) OR Defined(ANDROID)} RegisterService; {$ENDIF} end.
Unit h2AnalogClock; Interface Uses Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32, gr32_layers,Graphics,JvThreadTimer,GR32_transforms; Type TH2AnalogClock = Class(TControl) Private ftimer:tjvthreadtimer; finterval:Cardinal; fx, fy, fwidth, fheight:Integer; fvisible:Boolean; fbitmap:tbitmaplayer; fdrawmode:tdrawmode; falpha:Cardinal; fbmp:tbitmap32; fmin:tbitmap32; fhour:tbitmap32; Procedure Setvisible(value:Boolean); Procedure Ontimer(Sender:Tobject);Virtual; Procedure SetAlpha(value:Cardinal); Procedure SetDrawmode(value:tdrawmode); Procedure Setx(value:Integer); Procedure Sety(value:Integer); Procedure SetWidth(value:Integer); Procedure SetHeight(value:Integer); Procedure rotate(b:tbitmap32;Var dest:tbitmap32;angle:Single); Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Published Procedure Start; Procedure Stop; Procedure LoadBackGround(filename:String); Procedure LoadMinute(filename:String); Procedure LoadHour(filename:String); Property Interval:Cardinal Read finterval Write finterval; Property Alpha:Cardinal Read falpha Write setalpha; Property DrawMode:tdrawmode Read fdrawmode Write setdrawmode; Property X:Integer Read fx Write setx; Property Y:Integer Read fy Write sety; Property Width:Integer Read fwidth Write setwidth; Property Height:Integer Read fheight Write setheight; Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap; Property Visible:Boolean Read fvisible Write setvisible; End; Implementation Uses Unit1; Constructor TH2AnalogClock.Create(AOwner: TComponent); Var L: TFloatRect; alayer:tbitmaplayer; Begin Inherited Create(AOwner); fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers); ftimer:=tjvthreadtimer.Create(aowner); ftimer.Enabled:=False; ftimer.Interval:=1000; ftimer.Priority:=tpnormal; ftimer.OnTimer:=ontimer; finterval:=500; fdrawmode:=dmblend; falpha:=255; fvisible:=True; fx:=0; fy:=0; fwidth:=100; fheight:=100; fbmp:=tbitmap32.Create; 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; fvisible:=True; fmin:=tbitmap32.Create; fmin.DrawMode:=dmblend; fmin.MasterAlpha:=255; fhour:=tbitmap32.Create; fhour.DrawMode:=dmblend; fhour.MasterAlpha:=255; End; Destructor TH2AnalogClock.Destroy; Begin //here fbitmap.Free; ftimer.Free; fbmp.Free; fmin.free; fhour.free; Inherited Destroy; End; Procedure TH2AnalogClock.LoadBackGround(filename: String); Var au:Boolean; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fbmp,filename,au); width:=fbmp.Width; height:=fbmp.Height; Except End; End; End; Procedure TH2AnalogClock.LoadHour(filename: String); Var au:Boolean; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fhour,filename,au); Except End; End; End; Procedure TH2AnalogClock.LoadMinute(filename: String); Var au:Boolean; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fmin,filename,au); Except End; End; End; Procedure TH2AnalogClock.Ontimer(Sender: Tobject); Var h,m,s,ms:Word; hb,mb:tbitmap32; Begin hb:=tbitmap32.Create; hb.DrawMode:=dmblend; mb:=tbitmap32.Create; mb.DrawMode:=dmblend; hb.MasterAlpha:=falpha; mb.MasterAlpha:=falpha; hb.Width:=fWidth; mb.Width:=fWidth; hb.height:=fheight; mb.height:=fheight; decodetime(time,h,m,s,ms); If h>12 Then h:=h-12; rotate(fmin,mb,-m*6); rotate(fhour,hb,-h*30); fbmp.DrawTo(fbitmap.Bitmap,0,0); hb.DrawTo(fbitmap.Bitmap,0,0); mb.DrawTo(fbitmap.Bitmap,0,0); hb.free ; mb.free; End; Procedure TH2AnalogClock.rotate(b: tbitmap32; Var dest: tbitmap32; angle: Single); Var T: TAffineTransformation; Begin T := TAffineTransformation.Create; T.Clear; T.SrcRect := FloatRect(0, 0, b.Width + 1, B.height + 1); T.Translate(-b.width / 2, -b.height / 2); T.Rotate(0, 0, angle); T.Translate(b.width / 2, b.height / 2); transform(dest,b,t); t.Free; End; Procedure TH2AnalogClock.SetAlpha(value: Cardinal); Begin falpha:=value; fbitmap.Bitmap.MasterAlpha:=falpha; fbmp.MasterAlpha:=falpha; fmin.MasterAlpha:=falpha; fhour.MasterAlpha:=falpha; End; Procedure TH2AnalogClock.SetDrawmode(value: tdrawmode); Begin fdrawmode:=value; fbitmap.Bitmap.DrawMode:=fdrawmode; fbmp.DrawMode:=fdrawmode; fmin.DrawMode:=fdrawmode; fhour.DrawMode:=fdrawmode; End; Procedure TH2AnalogClock.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; fbmp.Height:=fheight; fmin.Height:=fheight; fhour.Height:=fheight; End; Procedure TH2AnalogClock.Setvisible(value: Boolean); Begin fbitmap.Visible:=value; End; Procedure TH2AnalogClock.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; fbmp.width:=fwidth; fmin.width:=fwidth; fhour.width:=fwidth; End; Procedure TH2AnalogClock.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 TH2AnalogClock.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 TH2AnalogClock.Start; Var L: TFloatRect; Begin fbitmap.bitmap.width:=fwidth; fbitmap.bitmap.height:=fheight; l.Left:=fx; l.Right:=fx+fbitmap.Bitmap.Width; l.Top :=fy; l.Bottom:=fy+fbitmap.Bitmap.height; fbitmap.Location:=l; ftimer.Enabled:=True; End; Procedure TH2AnalogClock.Stop; Begin ftimer.Enabled:=False; End; End.
{$MODE OBJFPC} program Relay; const InputFile = 'RELAY.INP'; OutputFile = 'RELAY.OUT'; maxN = Round(1E5); turtle = Round(1E18) + 1; type TRacer = record a, b, c, xid1, xid2: Integer; end; TLine = record x1, x2, d: Integer; y1, y2: Int64; end; TNode = record line: TLine; L, H: Integer; end; var r: array[1..maxN] of TRacer; xarr: array[1..maxN] of Integer; tree: array[1..4 * maxN] of TNode; leaf: array[1..maxN] of Integer; nx: Integer; n, k: Integer; fi, fo: TextFile; res: Int64; procedure Sort(L, H: Integer); var i, j: Integer; pivot: TRacer; begin repeat if L >= H then Exit; i := L + Random(H - L + 1); pivot := r[i]; r[i] := r[L]; i := L; j := H; repeat while (r[j].a > pivot.a) and (i < j) do Dec(j); if i < j then begin r[i] := r[j]; Inc(i); end else Break; while (r[i].a < pivot.a) and (i < j) do Inc(i); if i < j then begin r[j] := r[i]; Dec(j); end else Break; until i = j; r[i] := pivot; Sort(L, i - 1); L := i + 1; until False; end; procedure Enter; var i: Integer; begin ReadLn(fi, n, k); for i := 1 to n do with r[i] do ReadLn(fi, a, b, c); Sort(1, n); end; procedure MakeLine(var res: TLine; a, b, c: Integer; start: Int64); begin res.x1 := a; res.x2 := b; res.d := c; res.y1 := start; res.y2 := Int64(b - a) * c + start; end; function Time(const l: TLine; x: Integer): Int64; begin with l do Result := Int64(x - x1) * d + y1; end; procedure Build(node: Integer; low, high: Integer); var middle: Integer; begin with tree[node] do begin L := low; H := high; MakeLine(line, xarr[L], xarr[H], 0, turtle); if low = high then leaf[low] := node else begin middle := (low + high) div 2; Build(node * 2, low, middle); Build(node * 2 + 1, middle + 1, high); end; end; end; function Search(xv: Integer): Integer; var low, middle, high: Integer; begin low := 1; high := nx; while (low <= high) do //xarr[low - 1] <= xv < xarr[high + 1] begin middle := (low + high) shr 1; if xarr[middle] <= xv then low := Succ(middle) else high := Pred(middle); end; Result := high; end; procedure Init; var i: Integer; old: Integer; begin nx := 0; old := -1; for i := 1 to n do begin if r[i].a <> old then begin old := r[i].a; Inc(nx); xarr[nx] := old; end; r[i].xid1 := nx; end; for i := 1 to n do r[i].xid2 := Search(r[i].b); Build(1, 1, nx); end; procedure PartialLine(var newline: TLine; const line: TLine; x1, x2: Integer); begin newline.x1 := x1; newline.x2 := x2; newline.d := line.d; newline.y1 := Time(line, x1); newline.y2 := TIme(line, x2); end; procedure Swap(var l1, l2: TLine); var temp: TLine; begin temp := l1; l1 := l2; l2 := temp; end; procedure UpdateNode(node: Integer; var aline: TLine); var M, xM: Integer; subline: TLine; begin with tree[node] do begin if (line.y1 <= aline.y1) and (line.y2 <= aline.y2) then Exit; if (line.y1 >= aline.y1) and (line.y2 >= aline.y2) then begin line := aline; Exit; end; if line.y1 < aline.y1 then Swap(line, aline); M := (L + H) div 2; xM := xarr[M]; if Time(line, xM) <= Time(aline, XM) then begin PartialLine(subline, aline, xarr[L], xarr[M]); UpdateNode(node shl 1, subline); end else begin PartialLine(subline, line, xarr[M + 1], xarr[H]); line := aline; UpdateNode(node shl 1 + 1, subline); end; end; end; procedure InsertToTree(node: Integer; const aline: TLine); var templine: TLine; begin with tree[node] do begin if (aline.x1 > xarr[H]) or (aline.x2 < xarr[L]) then Exit; if (aline.x1 <= xarr[L]) and (aline.x2 >= xarr[H]) then begin PartialLine(templine, aline, xarr[L], xarr[H]); UpdateNode(node, templine); Exit; end; InsertToTree(node shl 1, aline); InsertToTree(node shl 1 + 1, aline); end; end; function Query(xid: Integer): Int64; var x: Integer; node: Integer; temp: Int64; begin node := leaf[xid]; x := xarr[xid]; Result := Time(tree[node].line, x); repeat node := node shr 1; if node = 0 then Break; temp := Time(tree[node].line, x); if temp < Result then Result := temp; until False; end; procedure Solve; var i: Integer; line: TLine; starttime, finishtime: Int64; begin MakeLine(line, 0, 0, 0, 0); InsertToTree(1, line); res := turtle; for i := 1 to n do begin starttime := Query(r[i].xid1); with r[i] do MakeLine(line, a, b, c, starttime); if r[i].b = k then begin finishtime := line.y2; if finishtime < res then res := finishtime; end; InsertTotree(1, line); end; end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try Enter; Init; Solve; Write(fo, res); finally CloseFile(fi); CloseFile(fo); end; end.
// librdkafka - Apache Kafka C library // // Copyright (c) 2012-2013 Magnus Edenhill // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. /// // @file rdkafka.h // @brief Apache Kafka C/C++ consumer and producer client library. // // rdkafka.h contains the public API for librdkafka. // The API is documented in this file as comments prefixing the function, type, // enum, define, etc. // // @sa For the C++ interface see rdkafkacpp.h // ///////////////////////////////////////////////////////////////////////////////// // // // rdkafka.pas chromatic unviverse 2018 william k .johnson // // // // librdkafka wrapper facade for free pascal // // // // // ///////////////////////////////////////////////////////////////////////////////// unit rdkafka; {$mode objfpc}{$H+} {$linklib rdkafka} {$linklib cci_kafka_utils} {$linklib c} {$INLINE ON} interface uses ctypes , sysutils , sockets , unix; type {$IFDEF FPC} {$PACKRECORDS C} {$ENDIF} ////enums // pas_rd_kakfa_type_t = ( //producer cliebt rd_kafka_producer , //consumer client rd_kafka_consumer ); // pas_ptr_rd_kafka_timestamp_type_t = ^pas_rd_kafka_timestamp_type_t; pas_rd_kafka_timestamp_type_t = ( //timestamp not available rd_kafka_timestamp_not_available , //message cration time rd_kafka_timestamp_create_time , //log append time rd_kafka_timestamp_log_append_time ); // // // @enum rd_kafka_conf_res_t // coonfiguration result type // pas_ptr_rd_kafka_conf_res_t = ^pas_rd_kafka_conf_res_t; pas_rd_kafka_conf_res_t = ( //unknown configuration name rd_kafka_conf_unknown = -2 , //invalid configuration value rd__kafka_conf_invalid = -1 , //configuration okay rd_kafka_conf_ok = 0 ); // // // @enum rd_kafka_resp_err_t // @brief Error codes. // // The negative error codes delimited by two underscores // (\c RD_KAFKA_RESP_ERR__..) denotes errors internal to librdkafka and are // displayed as \c \"Local: \<error string..\>\", while the error codes // delimited by a single underscore (\c RD_KAFKA_RESP_ERR_..) denote broker // errors and are displayed as \c \"Broker: \<error string..\>\". // // @sa Use rd_kafka_err2str() to translate an error code a human readable string /// pas_rd_kafka_resp_err_t = ( //internal errors to rdkafka: //Begin internal error codes rd_kafka_resp_err__begin = -200, //received message is incorrect rd_kafka_resp_err__bad_msg = -199 , //bad/unknown compression rd_kafka_resp_err__bad_compression = -198 , //broker is going away rd_kafka_resp_err__destroy = -197 , //generic failure rd_kafka_resp_err__fail = -196 , //broker transport failure rd_kafka_resp_err__transport = -195 , //critical system resource rd_kafka_resp_err__crit_sys_resource = -194 , //failed to resolve broker rd_kafka_resp_err__resolve = -193 , //produced message timed out rd_kafka_resp_err__msg_timed_out = -192 , //reached the end of the topic+partition queue on //the broker. not really an error. rd_kafka_resp_err__partition_eof = -191 , //permanent: partition does not exist in cluster. rd_kafka_resp_err__unknown_partition = -190 , //file or filesystem error rd_kafka_resp_err__fs = -189 , //permanent: topic does not exist in cluster. rd_kafka_resp_err__unknown_topic = -188 , //all broker connections are down. rd_kafka_resp_err__all_brokers_down = -187 , //invalid argument , or invalid configuration rd_kafka_resp_err__invalid_arg = -186 , //operation timed out rd_kafka_resp_err__timed_out = -185 , //queue is full rd_kafka_resp_err__queue_full = -184 , //isr count < required.acks rd_kafka_resp_err__isr_insuff = -183 , //broker node update rd_kafka_resp_err__node_update = -182 , //ssl error rd_kafka_resp_err__ssl = -181 , //waiting for coordinator to become available. rd_kafka_resp_err__wait_coord = -180 , //unknown client group rd_kafka_resp_err__unknown_group = -179 , //operation in progress rd_kafka_resp_err__in_progress = -178 , //previous operation in progress , wait for it to finish. rd_kafka_resp_err__prev_in_progress = -177 , //this operation would interfere with an existing subscription rd_kafka_resp_err__existing_subscription = -176 , //assigned partitions (rebalance_cb) rd_kafka_resp_err__assign_partitions = -175 , //revoked partitions (rebalance_cb) rd_kafka_resp_err__revoke_partitions = -174 , //conflicting use rd_kafka_resp_err__conflict = -173 , //wrong state rd_kafka_resp_err__state = -172 , //unknown protocol rd_kafka_resp_err__unknown_protocol = -171 , //not implemented rd_kafka_resp_err__not_implemented = -170 , //authentication failure rd_kafka_resp_err__authentication = -169 , //no stored offset rd_kafka_resp_err__no_offset = -168 , //outdated rd_kafka_resp_err__outdated = -167 , //timed out in queue rd_kafka_resp_err__timed_out_queue = -166 , //feature not supported by broker rd_kafka_resp_err__unsupported_feature = -165 , //awaiting cache update rd_kafka_resp_err__wait_cache = -164 , //operation interrupted (e.g. , due to yield)) rd_kafka_resp_err__intr = -163 , //key serialization error rd_kafka_resp_err__key_serialization = -162 , //value serialization error rd_kafka_resp_err__value_serialization = -161 , //key deserialization error rd_kafka_resp_err__key_deserialization = -160 , //value deserialization error rd_kafka_resp_err__value_deserialization = -159 , //end internal error codes rd_kafka_resp_err__end = -100 , //kafka broker errors: //unknown broker error rd_kafka_resp_err_unknown = -1 , //success rd_kafka_resp_err_no_error = 0 , //offset out of range rd_kafka_resp_err_offset_out_of_range = 1 , //invalid message rd_kafka_resp_err_invalid_msg = 2 , //unknown topic or partition rd_kafka_resp_err_unknown_topic_or_part = 3 , //invalid message size rd_kafka_resp_err_invalid_msg_size = 4 , //leader not available rd_kafka_resp_err_leader_not_available = 5 , //not leader for partition rd_kafka_resp_err_not_leader_for_partition = 6 , //request timed out rd_kafka_resp_err_request_timed_out = 7 , //broker not available rd_kafka_resp_err_broker_not_available = 8 , //replica not available rd_kafka_resp_err_replica_not_available = 9 , //message size too large rd_kafka_resp_err_msg_size_too_large = 10 , //stalecontrollerepochcode rd_kafka_resp_err_stale_ctrl_epoch = 11 , //offset metadata string too large rd_kafka_resp_err_offset_metadata_too_large = 12 , //broker disconnected before response received rd_kafka_resp_err_network_exception = 13 , //group coordinator load in progress rd_kafka_resp_err_group_load_in_progress = 14 , //group coordinator not available rd_kafka_resp_err_group_coordinator_not_available = 15 , //not coordinator for group rd_kafka_resp_err_not_coordinator_for_group = 16 , //invalid topic rd_kafka_resp_err_topic_exception = 17 , //message batch larger than configured server segment size rd_kafka_resp_err_record_list_too_large = 18 , //not enough in-sync replicas rd_kafka_resp_err_not_enough_replicas = 19 , //message(s) written to insufficient number of in-sync replicas rd_kafka_resp_err_not_enough_replicas_after_append = 20 , //invalid required acks value rd_kafka_resp_err_invalid_required_acks = 21 , //specified group generation id is not valid rd_kafka_resp_err_illegal_generation = 22 , //inconsistent group protocol rd_kafka_resp_err_inconsistent_group_protocol = 23 , //invalid group.id rd_kafka_resp_err_invalid_group_id = 24 , //unknown member rd_kafka_resp_err_unknown_member_id = 25 , //invalid session timeout rd_kafka_resp_err_invalid_session_timeout = 26 , //group rebalance in progress rd_kafka_resp_err_rebalance_in_progress = 27 , //commit offset data size is not valid rd_kafka_resp_err_invalid_commit_offset_size = 28 , //topic authorization failed rd_kafka_resp_err_topic_authorization_failed = 29 , //group authorization failed rd_kafka_resp_err_group_authorization_failed = 30 , //cluster authorization failed rd_kafka_resp_err_cluster_authorization_failed = 31 , //invalid timestamp rd_kafka_resp_err_invalid_timestamp = 32 , //unsupported sasl mechanism rd_kafka_resp_err_unsupported_sasl_mechanism = 33 , //illegal sasl state rd_kafka_resp_err_illegal_sasl_state = 34 , //unuspported version rd_kafka_resp_err_unsupported_version = 35 , //topic already exists rd_kafka_resp_err_topic_already_exists = 36 , //invalid number of partitions rd_kafka_resp_err_invalid_partitions = 37 , //invalid replication factor rd_kafka_resp_err_invalid_replication_factor = 38 , //invalid replica assignment rd_kafka_resp_err_invalid_replica_assignment = 39 , //invalid config rd_kafka_resp_err_invalid_config = 40 , //not controller for cluster rd_kafka_resp_err_not_controller = 41 , //invalid request rd_kafka_resp_err_invalid_request = 42 , //message format on broker does not support request rd_kafka_resp_err_unsupported_for_message_format = 43 , //isolation policy volation rd_kafka_resp_err_policy_violation = 44 , //broker received an out of order sequence number rd_kafka_resp_err_out_of_order_sequence_number = 45 , //broker received a duplicate sequence number rd_kafka_resp_err_duplicate_sequence_number = 46 , //producer attempted an operation with an old epoch rd_kafka_resp_err_invalid_producer_epoch = 47 , //producer attempted a transactional operation in an invalid state rd_kafka_resp_err_invalid_txn_state = 48 , //producer attempted to use a producer id which is not //currently assigned to its transactional id rd_kafka_resp_err_invalid_producer_id_mapping = 49 , //transaction timeout is larger than the maximum //value allowed by the broker's max.transaction.timeout.ms rd_kafka_resp_err_invalid_transaction_timeout = 50 , //producer attempted to update a transaction while another //concurrent operation on the same transaction was ongoing rd_kafka_resp_err_concurrent_transactions = 51 , //indicates that the transaction coordinator sending a //writetxnmarker is no longer the current coordinator for a //given producer rd_kafka_resp_err_transaction_coordinator_fenced = 52 , //transactional id authorization failed rd_kafka_resp_err_transactional_id_authorization_failed = 53 , //security features are disabled rd_kafka_resp_err_security_disabled = 54 , //operation not attempted rd_kafka_resp_err_operation_not_attempted = 55 , rd_kafka_resp_err_end_all ); ////typedefs // //private abi // pas_ptr_rd_kafka_t = type pointer; pas_ptr_rd_kafka_headers_t = type pointer; pas_rd_kafka_topic_t = type pointer; pas_ptr_rd_kafka_conf_t = type pointer; ptr_pas_rd_kafka_topic_conf_t = type pointer; ptr_pas_rd_kafka_queue_t = type pointer; //forward declarations pas_ptr_rd_kafka_topic_partition_list_t = ^pas_rd_kafka_topic_partition_list_t; pas_ptr_rd_kafka_message_t = ^pas_rd_kafka_message_t; pas_ptr_ref_char_t = ^PAnsiChar; ////function pointers & callbacks // pas_ptr_pas_t_compare_func = ^pas_t_compare_func; pas_t_compare_func = function( const a : pointer; const b : pointer; const opaque : pointer ) : ctypes.cint32; cdecl; // pas_ptr_pas_dr_msg_cb = ^pas_dr_msg_cb; pas_dr_msg_cb = procedure( rk : pas_ptr_rd_kafka_t; rkmessage : pas_ptr_rd_kafka_message_t; opaque : pointer ); // pas_ptr_pas_rebalance_cb = ^pas_rebalance_cb; pas_rebalance_cb = procedure( rk : pas_ptr_rd_kafka_t; err : pas_rd_kafka_resp_err_t; partitions : pas_ptr_rd_kafka_topic_partition_list_t; opaque : pointer ); // pas_ptr_pas_consume_cb = ^pas_consume_cb; pas_consume_cb = procedure( rk_message : pas_ptr_rd_kafka_message_t; opaque : pointer ); // pas_ptr_pas_offset_commit_cb = ^pas_offset_commit_cb; pas_offset_commit_cb = procedure( rk : pas_ptr_rd_kafka_t; err : pas_rd_kafka_resp_err_t; partitions : pas_ptr_rd_kafka_topic_partition_list_t; opaque : pointer ); // pas_ptr_pas_error_cb = ^pas_error_cb; pas_error_cb = procedure( rk : pas_ptr_rd_kafka_t; err : ctypes.cuint64; const reason : PAnsiChar; opaque : pointer ); // pas_ptr_pas_log_cb = ^pas_log_cb; pas_log_cb = procedure( rk : pas_ptr_rd_kafka_t; const fac : PAnsiChar; const buf : PAnsiChar ); // pas_ptr_pas_stats_cb = ^pas_stats_cb; pas_stats_cb = function( rk : pas_ptr_rd_kafka_t; json : PAnsiChar; json_len : ctypes.cuint64; opaque : pointer ) : ctypes.cint64; // pas_ptr_pas_socket_cb = ^pas_socket_cb; pas_socket_cb = function( domain : ctypes.cint64; typ : ctypes.cint64; protocol : ctypes.cint64; opaque : pointer ) : ctypes.cint64; // pas_ptr_pas_connect_cb = ^pas_connect_cb; pas_ptr_sock_unix_sockaddr = ^TUnixSockAddr; pas_connect_cb = function( sockfd : ctypes.cint32; const addr : pas_ptr_sock_unix_sockaddr; addrlen : ctypes.cint64; const id : PAnsiChar; opaque : pointer ) : ctypes.cint64; // pas_ptr_pas_closesocket_cb = ^pas_closesocket_cb; pas_closesocket_cb = function( sockfd : ctypes.cint32; opaque : pointer ) : ctypes.cint64; // pas_ptr_open_cb = ^pas_open_cb; pas_open_cb = function( const pathname : PAnsiChar; flags : cint32; mode : mode_t; opaque : pointer ) : ctypes.cint64; // pas_ptr_topic_partition_cb = ^topic_partition_cb; topic_partition_cb = function( topic_conf : ptr_pas_rd_kafka_topic_conf_t; const rkt : pas_rd_kafka_topic_t; const keydata : pointer; keylen : ctypes.cint32; partition_cnt : ctypes.cuint32; rkt_opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; // pas_ptr_msg_order_cmp_func = ^msg_order_cmp_func; msg_order_cmp_func = function( a :pas_ptr_rd_kafka_message_t; b :pas_ptr_rd_kafka_message_t ) : ctypes.cint32; ////records // //error code value, name and description. //typically for use with language bindings to automatically expose //the full set of librdkafka error codes. pas_ptr_rd_kafka_err_desc = ^pas_rd_kafka_err_desc; pas_rd_kafka_err_desc = record code : pas_rd_kafka_resp_err_t; name : PAnsiChar; desc : PAnsiChar; end; // topic partition place holder // // generic place holder for a Topic+Partition and its related information // used for multiple purposes: // - consumer offset (see rd_kafka_commit(), et.al.) // - group rebalancing callback (rd_kafka_conf_set_rebalance_cb()) // - offset commit result callback (rd_kafka_conf_set_offset_commit_cb()) // // generic place holder for a specific Topic+Partition. // // rd_kafka_topic_partition_list_new() /// pas_ptr_rd_kafka_topic_partition_t = ^pas_rd_kafka_topic_partition_t; pas_rd_kafka_topic_partition_t = record topic : PAnsiChar; // topic name partition : ctypes.cint32; // partition offset : ctypes.cint64; // offset metadata : pointer; // metadata metadata_size : ctypes.cuint64; // metadata size opaque : pointer; // application opaque err : pas_rd_kafka_resp_err_t; // error code, depending on use. _private : pointer; // INTERNAL USE ONLY, end; // INITIALIZE TO ZERO, DO NOT TOUCH // a growable list of topic partitions. pas_rd_kafka_topic_partition_list_t = record cnt : ctypes.cint32; //current number of elements size : ctypes.cint32; //vurrent allocated size elems : pas_ptr_rd_kafka_topic_partition_t; //element array[] end; // FIXME: this doesn't show up in docs for some reason // cCompound rd_kafka_message_t is not documented." // a kafka message as returned by the \c rd_kafka_consume//() family // of functions as well as provided to the Producer \c dr_msg_cb(). // // for the consumer this object has two purposes: // - provide the application with a consumed message. (\c err == 0) // - report per-topic+partition consumer errors (\c err != 0) // // the application must check \c err to decide what action to take. // // when the application is finished with a message it must call // rd_kafka_message_destroy() unless otherwise noted. // pas_rd_kafka_message_t = record err : pas_rd_kafka_resp_err_t; /////< Non-zero for error signaling. /// rkt : pas_ptr_rd_kafka_t; /////< Topic /// partition : ctypes.cint32; /////< Partition /// payload : pointer; /////< Producer: original message payload. // Consumer: Depends on the value of \c err : // - \c err==0: Message payload. // - \c err!=0: Error string /// len : ctypes.cint64; /////< Depends on the value of \c err : // - \c err==0: Message payload length // - \c err!=0: Error string length /// key : pointer; /////< Depends on the value of \c err : // - \c err==0: Optional message key /// key_len : ctypes.cint64; /////< Depends on the value of \c err : // - \c err==0: Optional message key length/// offset : ctypes.cint64; /////< Consume: // - Message offset (or offset for error // if \c err!=0 if applicable). // - dr_msg_cb: // Message offset assigned by broker. // If \c produce.offset.report is set then // each message will have this field set, // otherwise only the last message in // each produced internal batch will // have this field set, otherwise 0. /// _private : pointer; //_private; /////< Consume: // - rdkafka private pointer: DO NOT MODIFY // - dr_msg_cb: // msg_opaque from produce() call /// end; ////exports // // returns the librdkafka version as string. // // returns version string // function rd_kafka_version_str : PAnsiChar ; cdecl; // retrieve supported debug contexts for use with the \c \"debug\" // configuration property. (runtime) // // returns comma-separated list of available debugging contexts. // function rd_kafka_get_debug_contexts : PAnsiChar ; cdecl; // returns the error code name (enum name). // param err Error code to translate function rd_kafka_err2name ( err : pas_rd_kafka_resp_err_t ) : PAnsiChar; cdecl; // returns a human readable representation of a kafka error. // @param err Error code to translate function rd_kafka_err2str ( err : pas_rd_kafka_resp_err_t ) : PAnsiChar; cdecl; // returns the last error code generated by a legacy API call // in the current thread. // // The legacy APIs are the ones using errno to propagate error value, namely: // - rd_kafka_topic_new() // - rd_kafka_consume_start() // - rd_kafka_consume_stop() // - rd_kafka_consume() // - rd_kafka_consume_batch() // - rd_kafka_consume_callback() // - rd_kafka_consume_queue() // - rd_kafka_produce() // // The main use for this function is to avoid converting system \p errno // values to rd_kafka_resp_err_t codes for legacy APIs. // // The last error is stored per-thread, if multiple rd_kafka_t handles // are used in the same application thread the developer needs to // make sure rd_kafka_last_error() is called immediately after // a failed API call. // // errno propagation from librdkafka is not safe on Windows // and should not be used, use rd_kafka_last_error() instead. function rd_kafka_last_error : pas_rd_kafka_resp_err_t; cdecl; //returns the full list of error codes. procedure rd_kafka_get_err_descs( var errdescs : array of pas_rd_kafka_err_desc; var cntp : ctypes.cuint64 ); cdecl; // destroy a rd_kafka_topic_partition_t. // this must not be called for elements in a topic partition list. // procedure rd_kafka_topic_partition_destroy ( rktpar : pas_ptr_rd_kafka_topic_partition_t ); cdecl; // create a new list/vector topic+partition container. // // @param size initial allocated size used when the expected number of // elements is known or can be estimated. // Avoids reallocation and possibly relocation of the // elems array. // // @returns a newly allocated topic+partition list. // // @remark use rd_kafka_topic_partition_list_destroy() to free all resources // in use by a list and the list itself. // @sa rd_kafka_topic_partition_list_add() // function rd_kafka_topic_partition_list_new ( size : ctypes.cint32 ) : pas_ptr_rd_kafka_topic_partition_list_t; cdecl; // free all resources used by the list and the list itself. // procedure rd_kafka_topic_partition_list_destroy ( rkparlist : pas_ptr_rd_kafka_topic_partition_list_t ); cdecl; // @brief add topic+partition to list // // @param rktparlist list to extend // @param topic topic name (copied) // @param partition partition id // // @returns The object which can be used to fill in additionals fields. function rd_kafka_topic_partition_list_add ( rkparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; partition : ctypes.cint32 ) : pas_ptr_rd_kafka_topic_partition_t; cdecl; // @brief add range of partitions from \p start to \p stop inclusive. // // @param rktparlist list to extend // @param topic topic name (copied) // @param start start partition of range // @param stop last partition of range (inclusive) // procedure rd_kafka_topic_partition_list_add_range ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; start : ctypes.cint32; stop : ctypes.cint32 ); cdecl; // delete partition from list. // // @param rktparlist list to modify // @param topic topic name to match // @param partition partition to match // // @returns 1 if partition was found (and removed), else 0. // // @remark Any held indices to elems[] are unusable after this call returns 1. // function rd_kafka_topic_partition_list_del( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsichar; partition : ctypes.cint32 ) : ctypes.cint32; cdecl; // delete partition from list by elems[] index. // // @returns 1 if partition was found (and removed), else 0. // // @sa rd_kafka_topic_partition_list_del() // function rd_kafka_topic_partition_list_del_by_idx ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; idx : ctypes.cint32 ) : ctypes.cint32; cdecl; // make a copy of an existing list. // // @param src the existing list to copy. // // @returns a new list fully populated to be identical to \p src // function rd_kafka_topic_partition_list_copy ( const src : pas_ptr_rd_kafka_topic_partition_list_t ) : pas_ptr_rd_kafka_topic_partition_list_t; cdecl; // set offset to \p offset for \p topic and \p partition // // @returns RD_KAFKA_RESP_ERR_NO_ERROR on success or // RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION if \p partition was not found // in the list. // function rd_kafka_topic_partition_list_set_offset ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; partition : ctypes.cint32; offset : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; // find element by \p topic and \p partition. // // @returns a pointer to the first matching element, or NULL if not found. // function rd_kafka_topic_partition_list_find ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; partition : ctypes.cint32 ) : pas_ptr_rd_kafka_topic_partition_t; cdecl; // @brief sort list using comparator \p cmp. // // If \p cmp is NULL the default comparator will be used that // sorts by ascending topic name and partition. // procedure rd_kafka_topic_partition_list_sort( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; cmp : pas_ptr_pas_t_compare_func; opaque : pointer ); cdecl; // frees resources for \p rkmessage and hands ownership back to rdkafka. // procedure rd_kafka_message_destroy( rkmessage : pas_ptr_rd_kafka_message_t ); cdecl; // returns the error string for an errored rd_kafka_message_t or NULL if // there was no error. // // @remark This function MUST NOT be used with the producer. // function rd_kafka_message_errstr( const rkmessage : pas_ptr_rd_kafka_message_t ) : PAnsiChar ; inline; // returns the message timestamp for a consumed message. // // the timestamp is the number of milliseconds since the epoch (UTC). // // \p tstype (if not NULL) is updated to indicate the type of timestamp. // // @returns message timestamp, or -1 if not available. // // @remark message timestamps require broker version 0.10.0 or later. // function rd_kafka_message_timestamp( const rkmessage : pas_ptr_rd_kafka_message_t; tstype : pas_ptr_rd_kafka_timestamp_type_t ) : ctypes.cint64; cdecl; // returns the latency for a produced message measured from // the produce() call. // // @returns the latency in microseconds, or -1 if not available. // function rd_kafka_message_latency (const rkmessage : pas_ptr_rd_kafka_message_t ) : ctypes.cint64; cdecl; // get the message header list. // // the returned pointer in \p //hdrsp is associated with the \p rkmessage and // must not be used after destruction of the message object or the header // list is replaced with rd_kafka_message_set_headers(). // // @returns RD_KAFKA_RESP_ERR_NO_ERROR if headers were returned, // RD_KAFKA_RESP_ERR__NOENT if the message has no headers, // or another error code if the headers could not be parsed. // // @remark headers require broker version 0.11.0.0 or later. // // @remark as an optimization the raw protocol headers are parsed on // the first call to this function. function rd_kafka_message_headers ( const message : pas_ptr_rd_kafka_message_t; var hdrsp : pas_ptr_rd_kafka_headers_t ) : pas_rd_kafka_resp_err_t; cdecl; // get the message header list and detach the list from the message // making the application the owner of the headers. // The application must eventually destroy the headers using // rd_kafka_headers_destroy(). // The message's headers will be set to NULL. // // Otherwise same semantics as rd_kafka_message_headers() // // @sa rd_kafka_message_headers // function rd_kafka_message_detach_headers( message : pas_ptr_rd_kafka_message_t; var hdrsp : pas_ptr_rd_kafka_headers_t ) : pas_rd_kafka_resp_err_t; cdecl; // replace the message's current headers with a new list. // // @param hdrs New header list. The message object assumes ownership of // the list, the list will be destroyed automatically with // the message object. // The new headers list may be updated until the message object // is passed or returned to librdkafka. // // @remark The existing headers object, if any, will be destroyed. /// procedure rd_kafka_message_set_headers ( rkmessage : pas_ptr_rd_kafka_message_t; hdrs : pas_ptr_rd_kafka_headers_t ) cdecl; // returns the number of header key/value pairs // // @param hdrs Headers to count /// function rd_kafka_header_cnt ( const hdrs : pas_ptr_rd_kafka_headers_t ) : ctypes.cint64; cdecl; // vceate configuration object. // // when providing your own configuration to the \c rd_kafka_//_new_//() calls // the rd_kafka_conf_t objects needs to be created with this function // which will set up the defaults. // I.e.: // @code // rd_kafka_conf_t //myconf; // rd_kafka_conf_res_t res; // // myconf = rd_kafka_conf_new(); // res = rd_kafka_conf_set(myconf, "socket.timeout.ms", "600", // errstr, sizeof(errstr)); // if (res != RD_KAFKA_CONF_OK) // die("%s\n", errstr); // // rk = rd_kafka_new(..., myconf); // @endcode // // please see CONFIGURATION.md for the default settings or use // rd_kafka_conf_properties_show() to provide the information at runtime. // // the properties are identical to the Apache Kafka configuration properties // whenever possible. // // @returns A new rd_kafka_conf_t object with defaults set. // // @sa rd_kafka_conf_set(), rd_kafka_conf_destroy() // function rd_kafka_conf_new : pas_ptr_rd_kafka_conf_t; cdecl; // // dstroys a conf object. procedure rd_kafka_conf_destroy( conf : pas_ptr_rd_kafka_conf_t ); cdecl; // creates a copy/duplicate of configuration object \p conf // // @remark Interceptors are NOT copied to the new configuration object. // @sa rd_kafka_interceptor_f_on_conf_dup // function rd_kafka_conf_dup( const conf : pas_ptr_rd_kafka_conf_t ) : pas_ptr_rd_kafka_conf_t; cdecl; // // same as rd_kafka_conf_dup() but with an array of property name // prefixes to filter out (ignore) when copying. // function rd_kafka_conf_dup_filter ( const conf : pas_ptr_rd_kafka_conf_t; filter_cnt : ctypes.cuint64; var filter : PAnsiChar ) : pas_ptr_rd_kafka_conf_t; cdecl; // // sets a configuration property. // // \p conf must have been previously created with rd_kafka_conf_new(). // // fallthrough: // Topic-level configuration properties may be set using this interface // in which case they are applied on the \c default_topic_conf. // If no \c default_topic_conf has been set one will be created. // Any sub-sequent rd_kafka_conf_set_default_topic_conf() calls will // replace the current default topic configuration. // // @returns \c rd_kafka_conf_res_t to indicate success or failure. // In case of failure \p errstr is updated to contain a human readable // error string. /// function rd_kafka_conf_set( const conf : pas_ptr_rd_kafka_conf_t; const name : PAnsiChar; const value : PAnsiChar; const errstr : PAnsiChar; errstr_size : ctypes.cuint64 ) : pas_rd_kafka_conf_res_t ; cdecl; // // enable event sourcing. // events is a bitmask of RD_KAFKA_EVENT_* of events to enable // for consumption by `rd_kafka_queue_poll()`. // procedure rd_kafka_conf_set_events( conf : pas_ptr_rd_kafka_conf_t; events : ctypes.cuint64 ); cdecl; // // rd_kafka_conf_set_dr_cb // deprecated See rd_kafka_conf_set_dr_msg_cb() // // // deprecated ->skipped <willian k. johnson> // // // producer: Set delivery report callback in provided \p conf object. // // the delivery report callback will be called once for each message // accepted by rd_kafka_produce() (et.al) with \p err set to indicate // the result of the produce request. // // the callback is called when a message is succesfully produced or // if librdkafka encountered a permanent failure, or the retry counter for // temporary errors has been exhausted. // // an application must call rd_kafka_poll() at regular intervals to // serve queued delivery report callbacks. // procedure rd_kafka_conf_set_dr_msg_cb( conf : pas_ptr_rd_kafka_conf_t; msg_cb : pas_ptr_pas_dr_msg_cb ); cdecl; // // consumer: set consume callback for use with rd_kafka_consumer_poll() // // procedure rd_kafka_conf_set_consume_cb ( conf : pas_ptr_rd_kafka_conf_t; consume_cb : pas_ptr_pas_consume_cb ); cdecl; // // consumer: set rebalance callback for use with // coordinated consumer group balancing. // // the \p err field is set to either RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS // or RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS and 'partitions' // contains the full partition set that was either assigned or revoked. // // registering a \p rebalance_cb turns off librdkafka's automatic // partition assignment/revocation and instead delegates that responsibility // to the application's \p rebalance_cb. // // The rebalance callback is responsible for updating librdkafka's // assignment set based on the two events: RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS // and RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS but should also be able to handle // arbitrary rebalancing failures where \p err is neither of those. // @remark In this latter case (arbitrary error), the application must // call rd_kafka_assign(rk, NULL) to synchronize state. // // without a rebalance callback this is done automatically by librdkafka // but registering a rebalance callback gives the application flexibility // in performing other operations along with the assinging/revocation, // such as fetching offsets from an alternate location (on assign) // or manually committing offsets (on revoke). // // @remark The \p partitions list is destroyed by librdkafka on return // return from the rebalance_cb and must not be freed or // saved by the application. // // the following example shows the application's responsibilities: // @code // static void rebalance_cb (rd_kafka_t //rk, rd_kafka_resp_err_t err, // rd_kafka_topic_partition_list_t //partitions, // void //opaque) { // // switch (err) // { // case RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS: // // application may load offets from arbitrary external // // storage here and update \p partitions // // rd_kafka_assign(rk, partitions); // break; // // case RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS: // if (manual_commits) // Optional explicit manual commit // rd_kafka_commit(rk, partitions, 0); // sync commit // // rd_kafka_assign(rk, NULL); // break; // // default: // handle_unlikely_error(err); // rd_kafka_assign(rk, NULL); // sync state // break; // } // } // @endcode // procedure rd_kafka_conf_set_rebalance_cb ( conf : pas_ptr_rd_kafka_conf_t; rebalance_cb : pas_ptr_pas_rebalance_cb ); cdecl; // // consumer: Set offset commit callback for use with consumer groups. // // the results of automatic or manual offset commits will be scheduled // for this callback and is served by rd_kafka_consumer_poll(). // // if no partitions had valid offsets to commit this callback will be called // with \p err == RD_KAFKA_RESP_ERR__NO_OFFSET which is not to be considered // an error. // // the \p offsets list contains per-partition information: // - \c offset: committed offset (attempted) // - \c err: commit error /// procedure rd_kafka_conf_set_offset_commit_cb( conf : pas_ptr_rd_kafka_conf_t; offset_commit_cb : pas_ptr_pas_offset_commit_cb ); cdecl; // // set error callback in provided conf object. // // the error callback is used by librdkafka to signal critical errors // back to the application. // // if no error_cb is registered then the errors will be logged instead. // procedure rd_kafka_conf_set_error_cb( conf : pas_ptr_rd_kafka_conf_t; error_cb : pas_ptr_pas_error_cb ); cdecl; // // set logger callback. // // the default is to print to stderr, but a syslog logger is also available, // see rd_kafka_log_print and rd_kafka_log_syslog for the builtin alternatives. // Alternatively the application may provide its own logger callback. // Or pass func as NULL to disable logging. // // This is the configuration alternative to the deprecated rd_kafka_set_logger() // // @remark The log_cb will be called spontaneously from librdkafka's internal // threads unless logs have been forwarded to a poll queue through // \c rd_kafka_set_log_queue(). // An application MUST NOT call any librdkafka APIs or do any prolonged // work in a non-forwarded \c log_cb. // procedure rd_kafka_conf_set_log_cb( conf : pas_ptr_rd_kafka_conf_t; log_cb : pas_ptr_pas_log_cb ); cdecl; // // set statistics callback in provided conf object. // // the statistics callback is triggered from rd_kafka_poll() every // statistics.interval.ms (needs to be configured separately). // function arguments: // - rk - Kafka handle // - json - String containing the statistics data in JSON format // - json_len - Length of json string. // - opaque - application-provided opaque. // // if the application wishes to hold on to the json pointer and free // it at a later time it must return 1 from the stats_cb. // if the application returns 0 from the stats_cb then librdkafka // will immediately free the json pointer. // procedure rd_kafka_conf_set_stats_cb( conf : pas_ptr_rd_kafka_conf_t; stats_cb : pas_ptr_pas_stats_cb ); cdecl; // // set socket callback. // // the socket callback is responsible for opening a socket // according to the supplied domain, type and protocol. // The socket shall be created with \c CLOEXEC set in a racefree fashion, if // possible. // // default: // - on linux: racefree CLOEXEC // - others : non-racefree CLOEXEC // // @remark The callback will be called from an internal librdkafka thread. // procedure rd_kafka_conf_set_socket_cb( conf : pas_ptr_rd_kafka_conf_t; socket_cb : pas_ptr_pas_socket_cb ); cdecl; // // set connect callback. // // The connect callback is responsible for connecting socket \p sockfd // to peer address \p addr. // The id field contains the broker identifier. // // connect_cb shall return 0 on success (socket connected) or an error // number (errno) on error. // // @remark The callback will be called from an internal librdkafka thread. // procedure rd_kafka_conf_set_connect_cb( conf : pas_ptr_rd_kafka_conf_t; connect_cb : pas_ptr_pas_connect_cb ); cdecl; // // set close socket callback. // // close a socket (optionally opened with socket_cb()). // // @remark The callback will be called from an internal librdkafka thread. // procedure rd_kafka_conf_set_closesocket_cb( conf : pas_ptr_rd_kafka_conf_t; close_socket_cb : pas_ptr_pas_closesocket_cb ); cdecl; {$IFNDEF _MSC_VER} // // set open callback. // // the open callback is responsible for opening the file specified by // pathname, flags and mode. // the file shall be opened with \c CLOEXEC set in a racefree fashion, if // possible. // // default: // - on linux: racefree CLOEXEC // - others : non-racefree CLOEXEC // // @remark The callback will be called from an internal librdkafka thread. // procedure rd_kafka_conf_set_open_cb ( conf : pas_ptr_rd_kafka_conf_t; open_cb : pas_ptr_open_cb ); cdecl; {$ENDIF} // // sets the application's opaque pointer thai will be passed to callbacks // procedure rd_kafka_conf_set_opaque( conf : pas_ptr_rd_kafka_conf_t; opaque : pointer ); cdecl; // // retrieves the opaque pointer previously set with rd_kafka_conf_set_opaque() // function rd_kafka_opaque( const rk : pas_ptr_rd_kafka_t ) : pointer; cdecl; // // Ssts the default topic configuration to use for automatically // subscribed topics (e.g., through pattern-matched topics). // the topic config object is not usable after this call. // procedure rd_kafka_conf_set_default_topic_conf( conf : pas_ptr_rd_kafka_conf_t; tconf : ptr_pas_rd_kafka_topic_conf_t ); cdecl; // // retrieve configuration value for property \p name. // // if dest is non-NULL the value will be written to \p dest with at // most dest_size. // // dest_size is updated to the full length of the value, thus if // dest_size initially is smaller than the full length the application // may reallocate \p dest to fit the returned \p //dest_size and try again. // // if dest is NULL only the full length of the value is returned. // // fallthrough: // topic-level configuration properties from the \c default_topic_conf // may be retrieved using this interface. // // @returns \p RD_KAFKA_CONF_OK if the property name matched, else // RD_KAFKA_CONF_UNKNOWN. // function rd_kafka_conf_get( conf : pas_ptr_rd_kafka_conf_t; const name : PAnsiChar; dest : PAnsiChar; var dest_size : ctypes.cuint64 ) : pas_rd_kafka_conf_res_t; cdecl; // // dump the configuration properties and values of \p conf to an array // with \"key\", \"value\" pairs. // // the number of entries in the array is returned in //cntp. // // the dump must be freed with `rd_kafka_conf_dump_free()`. /// function rd_kafka_conf_dump( conf : pas_ptr_rd_kafka_conf_t; var cntp : ctypes.cuint32 ) : pas_ptr_ref_char_t ; cdecl; // // dump the topic configuration properties and values of \p conf // to an array with \"key\", \"value\" pairs. // // the number of entries in the array is returned in \p //cntp. // // the dump must be freed with `rd_kafka_conf_dump_free()`. // function rd_kafka_topic_conf_dump( conf : ptr_pas_rd_kafka_topic_conf_t ; var cntp : ctypes.cuint32 ) : pas_ptr_ref_char_t ; cdecl; // // frees a configuration dump returned from `rd_kafka_conf_dump()` or // rd_kafka_topic_conf_dump(). // procedure rd_kafka_conf_dump_free( arr : pas_ptr_ref_char_t; cnt : ctypes.cuint64 ); cdecl; // // prints a table to fp of all supported configuration properties, // their default values as well as a description. // procedure rd_kafka_conf_properties_show( fp : pointer ); cdecl; // // 7opic configuration // topic configuration property interface // // // // create topic configuration object // // @sa same semantics as for rd_kafka_conf_new(). // function rd_kafka_topic_conf_new : ptr_pas_rd_kafka_topic_conf_t; cdecl; // // creates a copy/duplicate of topic configuration object \p conf. // function rd_kafka_topic_conf_dup( const conf : ptr_pas_rd_kafka_topic_conf_t ) : ptr_pas_rd_kafka_topic_conf_t; cdecl; // // creates a copy/duplicate of rk's default topic configuration // object. // function rd_kafka_default_topic_conf_dup ( rk : pas_ptr_rd_kafka_t ) : ptr_pas_rd_kafka_topic_conf_t; cdecl; // // destroys a topic conf object. // procedure rd_kafka_topic_conf_destroy( topic_conf : ptr_pas_rd_kafka_topic_conf_t ); cdecl; // // producer: set partitioner callback in provided topic conf object. // // the partitioner may be called in any thread at any time, // it may be called multiple times for the same message/key. // // partitioner function constraints: // - MUST NOT call any rd_kafka_//() functions except: // rd_kafka_topic_partition_available() // - MUST NOT block or execute for prolonged periods of time. // - MUST return a value between 0 and partition_cnt-1, or the // special \c RD_KAFKA_PARTITION_UA value if partitioning // could not be performed. // procedure rd_kafka_topic_conf_set_partitioner_cb( topic_conf : ptr_pas_rd_kafka_topic_conf_t; topic_partition_cb : pas_ptr_topic_partition_cb ); cdecl; // // producer: Set message queueing order comparator callback. // // the callback may be called in any thread at any time, // it may be called multiple times for the same message. // // ordering comparator function constraints: // - MUST be stable sort (same input gives same output). // - MUST NOT call any rd_kafka_//() functions. // - MUST NOT block or execute for prolonged periods of time. // // the comparator shall compare the two messages and return: // - < 0 if message \p a should be inserted before message \p b. // - >=0 if message \p a should be inserted after message \p b. // // @remark Insert sorting will be used to enqueue the message in the // correct queue position, this comes at a cost of O(n). // // @remark If `queuing.strategy=fifo` new messages are enqueued to the // tail of the queue regardless of msg_order_cmp, but retried messages // are still affected by msg_order_cmp. // // @warning THIS IS AN EXPERIMENTAL API, SUBJECT TO CHANGE OR REMOVAL, // DO NOT USE IN PRODUCTION. // procedure rd_kafka_topic_conf_set_msg_order_cmp( topic_conf : ptr_pas_rd_kafka_topic_conf_t; msg_oder_cmp : pas_ptr_msg_order_cmp_func ); cdecl; // // check if partition is available (has a leader broker). // // @returns 1 if the partition is available, else 0. // // @warning This function must only be called from inside a partitioner function // function rd_kafka_topic_partition_available( const rkt : pas_ptr_rd_kafka_t; partition : ctypes.cint32 ) : ctypes.cint32; cdecl; // // random partitioner. // // will try not to return unavailable partitions. // // @returns a random partition between 0 and \p partition_cnt - 1. // // function rd_kafka_msg_partitioner_random( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; // // consistent partitioner. // // uses consistent hashing to map identical keys onto identical partitions. // // @returns a random partition between 0 and partition_cnt - 1 based on // the CRC value of the key // function rd_kafka_msg_partitioner_consistent ( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; // // cnsistent-random partitioner. // // this is the default partitioner. // uses consistent hashing to map identical keys onto identical partitions, and // messages without keys will be assigned via the random partitioner. // // @returns a random partition between 0 and \p partition_cnt - 1 based on // the CRC value of the key (if provided) // function rd_kafka_msg_partitioner_consistent_random( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; // // murmur2 partitioner (Java compatible). // // uses consistent hashing to map identical keys onto identical partitions // using Java-compatible Murmur2 hashing. // // @returns a partition between 0 and partition_cnt - 1. /// function rd_kafka_msg_partitioner_murmur2( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; // // consistent-Random Murmur2 partitioner (Java compatible). // // uses consistent hashing to map identical keys onto identical partitions // using Java-compatible Murmur2 hashing. // messages without keys will be assigned via the random partitioner. // // @returns a partition between 0 and \p partition_cnt - 1. // function rd_kafka_msg_partitioner_murmur2_random( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; /// // creates a new Kafka handle and starts its operation according to the // specified \p type (\p RD_KAFKA_CONSUMER or \p RD_KAFKA_PRODUCER). // // conf is an optional struct created with `rd_kafka_conf_new()` that will // be used instead of the default configuration. // The \p conf object is freed by this function on success and must not be used // or destroyed by the application sub-sequently. // See `rd_kafka_conf_set()` et.al for more information. // // errstr must be a pointer to memory of at least size errstr_size where // `rd_kafka_new()` may write a human readable error message in case the // creation of a new handle fails. In which case the function returns NULL. // // @remark \b RD_KAFKA_CONSUMER: When a new \p RD_KAFKA_CONSUMER // rd_kafka_t handle is created it may either operate in the // legacy simple consumer mode using the rd_kafka_consume_start() // interface, or the High-level KafkaConsumer API. // @remark An application must only use one of these groups of APIs on a given // rd_kafka_t RD_KAFKA_CONSUMER handle. // // @returns The Kafka handle on success or NULL on error (see \p errstr) // // @sa To destroy the Kafka handle, use rd_kafka_destroy(). // function rd_kafka_new( typ : pas_rd_kakfa_type_t; conf : pas_ptr_rd_kafka_conf_t; errstr : PAnsiChar; errstr_size : ctypes.cuint64 ) : pas_ptr_rd_kafka_t; cdecl; // // destroy Kafka handle. // // this is a blocking operation. // procedure rd_kafka_destroy( rk : pas_ptr_rd_kafka_t ); cdecl; // // returns Kafka handle name. /// function rd_kafka_name( const rkt : pas_ptr_rd_kafka_t ) : PAnsiChar; cdecl; // // returns Kafka handle type. // function rd_kafka_type( const rkt : pas_ptr_rd_kafka_t ) : pas_rd_kakfa_type_t; cdecl; /// // returns this client's broker-assigned group member id // // @remark this currently requires the high-level KafkaConsumer // // @returns an allocated string containing the current broker-assigned group // member id, or NULL if not available. // The application must free the string with \p free() or // rd_kafka_mem_free() /// function rd_kafka_memberid( const rkt : pas_ptr_rd_kafka_t ) : PAnsiChar; cdecl; // // @brief returns the ClusterId as reported in broker metadata. // // @param timeout_ms If there is no cached value from metadata retrieval // then this specifies the maximum amount of time // (in milliseconds) the call will block waiting // for metadata to be retrieved. // Use 0 for non-blocking calls. // @remark requires broker version >=0.10.0 and api.version.request=true. // // @remark the application must free the returned pointer // using rd_kafka_mem_free(). // // @returns a newly allocated string containing the ClusterId, or NULL // if no ClusterId could be retrieved in the allotted timespan. /// function rd_kafka_clusterid( rkt : pas_ptr_rd_kafka_t; timeout_ms : ctypes.cint32 ) : PAnsiChar; cdecl; // // creates a new topic handle for topic named \p topic. // // \p conf is an optional configuration for the topic created with // `rd_kafka_topic_conf_new()` that will be used instead of the default // topic configuration. // the \p conf object is freed by this function and must not be used or // destroyed by the application sub-sequently. // see `rd_kafka_topic_conf_set()` et.al for more information. // // topic handles are refcounted internally and calling rd_kafka_topic_new() // again with the same topic name will return the previous topic handle // without updating the original handle's configuration. // applications must eventually call rd_kafka_topic_destroy() for each // succesfull call to rd_kafka_topic_new() to clear up resources. // // @returns the new topic handle or NULL on error (use rd_kafka_errno2err() // to convert system \p errno to an rd_kafka_resp_err_t error code. // // @sa rd_kafka_topic_destroy() // function rd_kafka_topic_new( rkt : pas_ptr_rd_kafka_t; topic : PAnsiChar; conf : pas_ptr_rd_kafka_conf_t ) : pas_rd_kafka_topic_t; cdecl; // // loose application's topic handle refcount as previously created // with `rd_kafka_topic_new()`. // // @remark since topic objects are refcounted (both internally and for the app) // the topic object might not actually be destroyed by this call, // but the application must consider the object destroyed. /// procedure rd_kafka_topic_destroy( rkt : pas_rd_kafka_topic_t ); cdecl; // // returns the topic name. // function rd_kafka_topic_name( const rk : pas_rd_kafka_topic_t ) : PAnsiChar; cdecl; // // get the rkt_opaque pointer that was set in the topic configuration. // procedure rd_kafka_topic_opaque ( const rk : pas_rd_kafka_topic_t) ; cdecl; // // polls the provided kafka handle for events. // // events will cause application provided callbacks to be called. // // the timeout_ms argument specifies the maximum amount of time // (in milliseconds) that the call will block waiting for events. // for non-blocking calls, provide 0 as \p timeout_ms. // to wait indefinately for an event, provide -1. // // an application should make sure to call poll() at regular // intervals to serve any queued callbacks waiting to be called. // // events: // - delivery report callbacks (if dr_cb/dr_msg_cb is configured) [producer] // - error callbacks (rd_kafka_conf_set_error_cb()) [all] // - stats callbacks (rd_kafka_conf_set_stats_cb()) [all] // - throttle callbacks (rd_kafka_conf_set_throttle_cb()) [all] // // @returns the number of events served. // function rd_kafka_poll( rkt : pas_ptr_rd_kafka_t; timeout_ms : ctypes.cint64 ) : ctypes.cint64; cdecl; // // cancels the current callback dispatcher (rd_kafka_poll(), // rd_kafka_consume_callback(), etc). // // a callback may use this to force an immediate return to the calling // code (caller of e.g. rd_kafka_poll()) without processing any further // events. // // @remark This function MUST ONLY be called from within a librdkafka callback. /// procedure rd_kafka_yield( rkt : pas_ptr_rd_kafka_t ); cdecl; // // pause producing or consumption for the provided list of partitions. // // success or error is returned per-partition \p err in the \p partitions list. // // @returns RD_KAFKA_RESP_ERR_NO_ERROR // function rd_kafka_pause_partitions( rkt : pas_ptr_rd_kafka_t; partitions : pas_ptr_rd_kafka_topic_partition_list_t ) : pas_rd_kafka_resp_err_t; cdecl; // // resume producing consumption for the provided list of partitions. // // success or error is returned per-partition \p err in the \p partitions list. // // @returns RD_KAFKA_RESP_ERR_NO_ERROR // function rd_kafka_resume_partitions( rkt : pas_ptr_rd_kafka_t; partitions : pas_ptr_rd_kafka_topic_partition_list_t ) : pas_rd_kafka_resp_err_t; cdecl; // // query broker for low (oldest/beginning) and high (newest/end) offsets // for partition. // // offsets are returned in low and high respectively. // // @returns RD_KAFKA_RESP_ERR_NO_ERROR on success or an error code on failure. // function rd_kafka_query_watermark_offsets( rkt : pas_ptr_rd_kafka_t; const topic : PAnsiChar; partition : ctypes.cint32; low : ctypes.cint64; high : ctypes.cint64; timeout_ms : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; // // get last known low (oldest/beginning) and high (newest/end) offsets // for partition. // // the low offset is updated periodically (if statistics.interval.ms is set) // while the high offset is updated on each fetched message set from the broker. // // if there is no cached offset (either low or high, or both) then // RD_KAFKA_OFFSET_INVALID will be returned for the respective offset. // // offsets are returned in \p //low and \p //high respectively. // // @returns RD_KAFKA_RESP_ERR_NO_ERROR on success or an error code on failure. // // @remark shall only be used with an active consumer instance. /// function rd_kafka_get_watermark_offsets( rkt : pas_ptr_rd_kafka_t; partition : ctypes.cint32; var low : ctypes.cint64; var high : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; // // @brief Look up the offsets for the given partitions by timestamp. // // The returned offset for each partition is the earliest offset whose // timestamp is greater than or equal to the given timestamp in the // corresponding partition. // // The timestamps to query are represented as \c offset in \p offsets // on input, and \c offset will contain the offset on output. // // The function will block for at most \p timeout_ms milliseconds. // // @remark Duplicate Topic+Partitions are not supported. // @remark Per-partition errors may be returned in \c rd_kafka_topic_partition_t.err // // @returns RD_KAFKA_RESP_ERR_NO_ERROR if offsets were be queried (do note // that per-partition errors might be set), // RD_KAFKA_RESP_ERR__TIMED_OUT if not all offsets could be fetched // within \p timeout_ms, // RD_KAFKA_RESP_ERR__INVALID_ARG if the \p offsets list is empty, // RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION if all partitions are unknown, // RD_KAFKA_RESP_ERR_LEADER_NOT_AVAILABLE if unable to query leaders // for the given partitions. // function rd_kafka_offsets_for_times( rkt : pas_ptr_rd_kafka_t; offsets : pas_ptr_rd_kafka_topic_partition_list_t; timeout_ms : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; implementation function rd_kafka_version_str : PAnsiChar ; cdecl; external; // function rd_kafka_get_debug_contexts : PAnsiChar ; cdecl; external; // function rd_kafka_err2name ( err : pas_rd_kafka_resp_err_t ) : PAnsiChar; cdecl; external; // function rd_kafka_err2str ( err : pas_rd_kafka_resp_err_t ) : PAnsiChar; cdecl; external; // function rd_kafka_last_error : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_topic_partition_list_new ( size : ctypes.cint32 ) : pas_ptr_rd_kafka_topic_partition_list_t; cdecl; external; // function rd_kafka_topic_partition_list_add ( rkparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; partition : ctypes.cint32 ) : pas_ptr_rd_kafka_topic_partition_t; cdecl; external; // function rd_kafka_topic_partition_list_del( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsichar; partition : ctypes.cint32 ) : ctypes.cint32; cdecl; external; function rd_kafka_topic_partition_list_del_by_idx ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; idx : ctypes.cint32 ) : ctypes.cint32; cdecl; external; // function rd_kafka_topic_partition_list_copy ( const src : pas_ptr_rd_kafka_topic_partition_list_t ) : pas_ptr_rd_kafka_topic_partition_list_t; cdecl; external; // function rd_kafka_topic_partition_list_set_offset ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; partition : ctypes.cint32; offset : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_topic_partition_list_find ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; partition : ctypes.cint32 ) : pas_ptr_rd_kafka_topic_partition_t; cdecl; external; // procedure rd_kafka_get_err_descs( var errdescs : array of pas_rd_kafka_err_desc; var cntp : ctypes.cuint64 ) cdecl; external; // procedure rd_kafka_topic_partition_destroy ( rktpar : pas_ptr_rd_kafka_topic_partition_t ); cdecl; external; // procedure rd_kafka_topic_partition_list_destroy ( rkparlist : pas_ptr_rd_kafka_topic_partition_list_t ); cdecl; external; // procedure rd_kafka_topic_partition_list_add_range ( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; const topic : PAnsiChar; start : ctypes.cint32; stop : ctypes.cint32 ); cdecl; external; procedure rd_kafka_topic_partition_list_sort( rktparlist : pas_ptr_rd_kafka_topic_partition_list_t; cmp : pas_ptr_pas_t_compare_func; opaque : pointer ); cdecl; external; // function rd_kafka_message_timestamp( const rkmessage : pas_ptr_rd_kafka_message_t; tstype : pas_ptr_rd_kafka_timestamp_type_t ) : ctypes.cint64; cdecl; external; // procedure rd_kafka_message_destroy( rkmessage : pas_ptr_rd_kafka_message_t ); cdecl; external; // function rd_kafka_message_latency (const rkmessage : pas_ptr_rd_kafka_message_t ) : ctypes.cint64; cdecl; external; // rk : pas_ptr_rd_kafka_t function rd_kafka_message_headers ( const message : pas_ptr_rd_kafka_message_t; var hdrsp : pas_ptr_rd_kafka_headers_t ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_message_detach_headers( message : pas_ptr_rd_kafka_message_t; var hdrsp : pas_ptr_rd_kafka_headers_t ) : pas_rd_kafka_resp_err_t; cdecl; external; // procedure rd_kafka_message_set_headers ( rkmessage : pas_ptr_rd_kafka_message_t; hdrs : pas_ptr_rd_kafka_headers_t ) cdecl; external; // function rd_kafka_header_cnt ( const hdrs : pas_ptr_rd_kafka_headers_t ) : ctypes.cint64; cdecl; external; // function rd_kafka_conf_new : pas_ptr_rd_kafka_conf_t; cdecl; external; // procedure rd_kafka_conf_destroy( conf : pas_ptr_rd_kafka_conf_t ); cdecl; external; // function rd_kafka_conf_dup( const conf : pas_ptr_rd_kafka_conf_t ) : pas_ptr_rd_kafka_conf_t; cdecl; external; // function rd_kafka_conf_dup_filter ( const conf : pas_ptr_rd_kafka_conf_t; filter_cnt : ctypes.cuint64; var filter : PAnsiChar ) : pas_ptr_rd_kafka_conf_t; cdecl; external; // function rd_kafka_conf_set( const conf : pas_ptr_rd_kafka_conf_t; const name : PAnsiChar; const value : PAnsiChar; const errstr : PAnsiChar; errstr_size : ctypes.cuint64 ) : pas_rd_kafka_conf_res_t ; cdecl; external; // procedure rd_kafka_conf_set_events( conf : pas_ptr_rd_kafka_conf_t; events : ctypes.cuint64 ); cdecl; external; // procedure rd_kafka_conf_set_dr_msg_cb( conf : pas_ptr_rd_kafka_conf_t; msg_cb : pas_ptr_pas_dr_msg_cb ); cdecl; external; // procedure rd_kafka_conf_set_rebalance_cb ( conf : pas_ptr_rd_kafka_conf_t; rebalance_cb : pas_ptr_pas_rebalance_cb ); cdecl; external; // procedure rd_kafka_conf_set_consume_cb ( conf : pas_ptr_rd_kafka_conf_t; consume_cb : pas_ptr_pas_consume_cb ); cdecl; external; // procedure rd_kafka_conf_set_offset_commit_cb( conf : pas_ptr_rd_kafka_conf_t; offset_commit_cb : pas_ptr_pas_offset_commit_cb ); cdecl; external; // procedure rd_kafka_conf_set_error_cb( conf : pas_ptr_rd_kafka_conf_t; error_cb : pas_ptr_pas_error_cb ); cdecl; external; // procedure rd_kafka_conf_set_log_cb( conf : pas_ptr_rd_kafka_conf_t; log_cb : pas_ptr_pas_log_cb ); cdecl; external; // procedure rd_kafka_conf_set_stats_cb( conf : pas_ptr_rd_kafka_conf_t; stats_cb : pas_ptr_pas_stats_cb ); cdecl; external; // procedure rd_kafka_conf_set_socket_cb( conf : pas_ptr_rd_kafka_conf_t; socket_cb : pas_ptr_pas_socket_cb ) cdecl; external; // procedure rd_kafka_conf_set_connect_cb( conf : pas_ptr_rd_kafka_conf_t; connect_cb : pas_ptr_pas_connect_cb ); cdecl; external; // procedure rd_kafka_conf_set_closesocket_cb( conf : pas_ptr_rd_kafka_conf_t; close_socket_cb : pas_ptr_pas_closesocket_cb ); cdecl; external; {$IFNDEF _MSC_VER} // procedure rd_kafka_conf_set_open_cb ( conf : pas_ptr_rd_kafka_conf_t; open_cb : pas_ptr_open_cb ); cdecl; external; {$ENDIF} // procedure rd_kafka_conf_set_opaque( conf : pas_ptr_rd_kafka_conf_t; opaque : pointer ); cdecl; external; // function rd_kafka_opaque( const rk : pas_ptr_rd_kafka_t ) : pointer; cdecl; external; // procedure rd_kafka_conf_set_default_topic_conf( conf : pas_ptr_rd_kafka_conf_t; tconf : ptr_pas_rd_kafka_topic_conf_t ); cdecl; external; // function rd_kafka_conf_get( conf : pas_ptr_rd_kafka_conf_t; const name : PAnsiChar; dest : PAnsiChar; var dest_size : ctypes.cuint64 ) : pas_rd_kafka_conf_res_t; cdecl; external; // function rd_kafka_conf_dump( conf : pas_ptr_rd_kafka_conf_t; var cntp : ctypes.cuint32 ) : pas_ptr_ref_char_t; cdecl; external; // function rd_kafka_topic_conf_dump( conf : ptr_pas_rd_kafka_topic_conf_t; var cntp : ctypes.cuint32 ) : pas_ptr_ref_char_t ; cdecl; external; // procedure rd_kafka_conf_dump_free( arr : pas_ptr_ref_char_t; cnt : ctypes.cuint64 ); cdecl; external; // procedure rd_kafka_conf_properties_show( fp : pointer ); cdecl; external; // function rd_kafka_topic_conf_new : ptr_pas_rd_kafka_topic_conf_t; cdecl; external; // function rd_kafka_topic_conf_dup( const conf : ptr_pas_rd_kafka_topic_conf_t ) : ptr_pas_rd_kafka_topic_conf_t; cdecl; external; // function rd_kafka_default_topic_conf_dup ( rk : pas_ptr_rd_kafka_t ) : ptr_pas_rd_kafka_topic_conf_t; cdecl; external; // procedure rd_kafka_topic_conf_destroy( topic_conf : ptr_pas_rd_kafka_topic_conf_t ); cdecl; external; procedure rd_kafka_topic_conf_set_partitioner_cb( topic_conf : ptr_pas_rd_kafka_topic_conf_t; topic_partition_cb : pas_ptr_topic_partition_cb ); cdecl; external; // procedure rd_kafka_topic_conf_set_msg_order_cmp( topic_conf : ptr_pas_rd_kafka_topic_conf_t; msg_oder_cmp : pas_ptr_msg_order_cmp_func ); cdecl; external; // function rd_kafka_topic_partition_available( const rkt : pas_ptr_rd_kafka_t; partition : ctypes.cint32 ) : ctypes.cint32; cdecl; external; // function rd_kafka_msg_partitioner_random( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; external; // function rd_kafka_msg_partitioner_consistent ( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; external; // function rd_kafka_msg_partitioner_consistent_random( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; external; // function rd_kafka_msg_partitioner_murmur2( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; external; // function rd_kafka_msg_partitioner_murmur2_random( const rkt : pas_rd_kafka_topic_t; const key : pointer; keylen : ctypes.cuint64; partition_cnt : ctypes.cuint64; opaque : pointer; msg_opaque : pointer ) : ctypes.cint32; cdecl; external; // function rd_kafka_new( typ : pas_rd_kakfa_type_t; conf : pas_ptr_rd_kafka_conf_t; errstr : PAnsiChar; errstr_size : ctypes.cuint64 ) : pas_ptr_rd_kafka_t; cdecl; external; // function rd_kafka_name( const rkt : pas_ptr_rd_kafka_t ) : PAnsiChar; cdecl; external; // procedure rd_kafka_destroy( rk : pas_ptr_rd_kafka_t ); cdecl; external; // function rd_kafka_type( const rkt : pas_ptr_rd_kafka_t ) : pas_rd_kakfa_type_t; cdecl; external; // function rd_kafka_memberid( const rkt : pas_ptr_rd_kafka_t ) : PAnsiChar; cdecl; external; // function rd_kafka_clusterid( rkt : pas_ptr_rd_kafka_t; timeout_ms : ctypes.cint32 ) : PAnsiChar; cdecl; external; // function rd_kafka_topic_new( rkt : pas_ptr_rd_kafka_t; topic : PAnsiChar; conf : pas_ptr_rd_kafka_conf_t ) : pas_rd_kafka_topic_t; cdecl; external; // procedure rd_kafka_topic_destroy( rkt : pas_rd_kafka_topic_t ); cdecl; external; // function rd_kafka_topic_name( const rk : pas_rd_kafka_topic_t ) : PAnsiChar; cdecl; external; // procedure rd_kafka_topic_opaque ( const rk : pas_rd_kafka_topic_t ) ; cdecl; external; // function rd_kafka_poll( rkt : pas_ptr_rd_kafka_t; timeout_ms : ctypes.cint64 ) : ctypes.cint64; cdecl; external; // procedure rd_kafka_yield ( rkt : pas_ptr_rd_kafka_t ); cdecl; external; // function rd_kafka_pause_partitions( rkt : pas_ptr_rd_kafka_t; partitions : pas_ptr_rd_kafka_topic_partition_list_t ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_resume_partitions ( rkt : pas_ptr_rd_kafka_t; partitions : pas_ptr_rd_kafka_topic_partition_list_t ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_query_watermark_offsets( rkt : pas_ptr_rd_kafka_t; const topic : PAnsiChar; partition : ctypes.cint32; low : ctypes.cint64; high : ctypes.cint64; timeout_ms : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_get_watermark_offsets( rkt : pas_ptr_rd_kafka_t; partition : ctypes.cint32; var low : ctypes.cint64; var high : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_offsets_for_times( rkt : pas_ptr_rd_kafka_t; offsets : pas_ptr_rd_kafka_topic_partition_list_t; timeout_ms : ctypes.cint64 ) : pas_rd_kafka_resp_err_t; cdecl; external; // function rd_kafka_message_errstr( const rkmessage : pas_ptr_rd_kafka_message_t ) : PAnsiChar ; inline; var err_msg : pas_rd_kafka_message_t; begin err_msg := rkmessage^; if ( integer( err_msg.err ) = 0 ) then begin result := nil; end; if ( err_msg.payload <> nil ) then begin result := PAnsiChar( err_msg.payload ); end; result := rd_kafka_err2str( err_msg.err ); end; end.
unit fPreferences; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Spin, GR32_Image, GR32, ComCtrls, cConfiguration, cMegaROM; type TfrmPreferences = class(TForm) cmdOK: TButton; cmdCancel: TButton; cmdRestoreDefaults: TButton; pgcPreferences: TPageControl; tshGeneral: TTabSheet; tshEmulatorSettings: TTabSheet; rdgEmuFileSettings: TRadioGroup; txtEmulatorPath: TEdit; lblEmulatorPath: TLabel; cmdBrowse: TButton; chkDisplayEmulatorSaveWarning: TCheckBox; tshDisplayOptions: TTabSheet; chkShowLeftMidText: TCheckBox; lblLeftTextColour: TLabel; imgLeftText: TImage32; cmdBrowseLeft: TButton; ColorDialog: TColorDialog; cmdBrowseRight: TButton; imgRightText: TImage32; lblMiddleTextColour: TLabel; imgGridlineColour: TImage32; cmdBrowseGridlines: TButton; chkShowGridlinesByDefault: TCheckBox; OpenDialog: TOpenDialog; lblGridlineColour: TLabel; cbDataFile: TComboBox; lblDatafile: TLabel; lblPalette: TLabel; cbPaletteFile: TComboBox; chkBackupFiles: TCheckBox; rdgWhenIncorrectMapper: TRadioGroup; chkAutoCheck: TCheckBox; tshIPS: TTabSheet; lblOriginalFile: TLabel; txtOriginalROMFilename: TEdit; cmdIPSBrowse: TButton; grpPatching: TGroupBox; lblSaveAsIPS: TLabel; txtSaveAsIPS: TEdit; cmdBrowseIPSSaveAs: TButton; lblIPSNoteSaveAs: TLabel; imgLunarIPS: TImage; lblLunarCompress: TLabel; lblFuSoYa: TLabel; SaveDialog: TSaveDialog; chkAutoGotoObjEditing: TCheckBox; lblSpecObjOutline: TLabel; imgSpecObjOutline: TImage32; cmdSpecObjOutline: TButton; chkIconTransparency: TCheckBox; lblIconTransparency: TLabel; txtIconTransparency: TSpinEdit; chkDisableDeleteEnemyPrompt: TCheckBox; chkUseStandardScrollLengths: TCheckBox; procedure cmdBrowseLeftClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdBrowseRightClick(Sender: TObject); procedure cmdBrowseGridlinesClick(Sender: TObject); procedure cmdBrowseClick(Sender: TObject); procedure cmdRestoreDefaultsClick(Sender: TObject); procedure cmdIPSBrowseClick(Sender: TObject); procedure cmdBrowseIPSSaveAsClick(Sender: TObject); procedure cmdSpecObjOutlineClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; procedure LoadPreferences(); procedure SavePreferences(); procedure LoadDataFiles(); procedure LoadPaletteFiles(); { Private declarations } public property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; property ROMData : TMegamanROM read _ROMData write _ROMData; { Public declarations } end; var frmPreferences: TfrmPreferences; implementation {$R *.dfm} uses ulunarcompress; procedure TfrmPreferences.cmdBrowseLeftClick(Sender: TObject); begin ColorDialog.Color := imgLeftText.Color; if ColorDialog.Execute then begin imgLeftText.Color := ColorDialog.Color; end; end; procedure TfrmPreferences.LoadPreferences(); begin imgLeftText.Color := WinColor(_EditorConfig.LeftTextColour); imgRightText.Color := WinColor(_EditorConfig.MiddleTextColour); imgGridlineColour.Color := WinColor(_EditorConfig.GridlineColour); imgSpecObjOutline.Color := WinColor(_EditorConfig.SpecObjOutline); cbDataFile.ItemIndex := cbDataFile.Items.IndexOf(_EditorConfig.DataFileName); cbPaletteFile.ItemIndex := cbPaletteFile.Items.IndexOf(_EditorConfig.Palette); if cbPaletteFile.ItemIndex = -1 then cbPaletteFile.ItemIndex := 0; chkShowLeftMidText.Checked := _EditorConfig.DispLeftMidText; chkShowGridlinesByDefault.Checked := _EditorConfig.GridlinesOnByDefault; chkBackupFiles.Checked := _EditorConfig.BackupFilesWhenSaving; chkDisplayEmulatorSaveWarning.Checked := _EditorConfig.EmulatorDisplaySaveWarning; rdgEmuFileSettings.ItemIndex := _EditorConfig.EmulatorFileSettings; txtEmulatorPath.Text := _EditorConfig.EmulatorPath; rdgWhenIncorrectMapper.ItemIndex := _EditorConfig.MapperWarnings; chkAutoCheck.Checked := _EditorConfig.AutoCheck; txtOriginalROMFilename.Text := _EditorConfig.OriginalROMFile; txtSaveAsIPS.Text := _EditorConfig.IPSOutput; chkAutoGotoObjEditing.Checked := _EditorConfig.AutoObjMode; chkIconTransparency.Checked := _EditorConfig.DrawTransparentIcons; txtIconTransparency.Value := _EditorConfig.IconTransparency; chkDisableDeleteEnemyPrompt.Checked := _EditorConfig.DisableEnemyDeletePrompt; chkUseStandardScrollLengths.Checked := _EditorConfig.DontAllowEdits; end; procedure TfrmPreferences.SavePreferences(); begin _EditorConfig.LeftTextColour := Color32(imgLeftText.Color); _EditorConfig.MiddleTextColour := Color32(imgRightText.Color); _EditorConfig.GridlineColour := Color32(imgGridlineColour.Color); _EditorConfig.SpecObjOutline := Color32(imgSpecObjOutline.Color); _EditorConfig.DataFileName := cbDataFile.Items[cbDataFile.ItemIndex]; _EditorConfig.Palette := cbPaletteFile.Items[cbPaletteFile.ItemIndex]; _EditorConfig.DispLeftMidText := chkShowLeftMidText.Checked; _EditorConfig.GridlinesOnByDefault := chkShowGridlinesByDefault.Checked; _EditorConfig.BackupFilesWhenSaving := chkBackupFiles.Checked; _EditorConfig.EmulatorDisplaySaveWarning := chkDisplayEmulatorSaveWarning.Checked; _EditorConfig.EmulatorFileSettings := rdgEmuFileSettings.ItemIndex; _EditorConfig.EmulatorPath := txtEmulatorPath.Text; _EditorConfig.MapperWarnings :=rdgWhenIncorrectMapper.ItemIndex; _EditorConfig.AutoCheck := chkAutoCheck.Checked; _EditorConfig.OriginalROMFile := txtOriginalROMFilename.Text; _EditorConfig.IPSOutput := txtSaveAsIPS.Text; _EditorConfig.AutoObjMode := chkAutoGotoObjEditing.Checked; _EditorConfig.DrawTransparentIcons := chkIconTransparency.Checked; _EditorConfig.IconTransparency := txtIconTransparency.Value; _EditorConfig.DisableEnemyDeletePrompt := chkDisableDeleteEnemyPrompt.Checked; _EditorConfig.DontAllowEdits := chkUseStandardScrollLengths.Checked; end; procedure TfrmPreferences.FormShow(Sender: TObject); begin if Assigned(_ROMData) = False then begin cbDataFile.Enabled := True; lblDataFile.Enabled := True; end else begin cbDataFile.Enabled := False; lblDataFile.Enabled := False; end; LoadPaletteFiles(); LoadDataFiles(); LoadPreferences; lblLunarCompress.Caption := 'Lunar Compress.dll v'+ FloatToStr(LunarVersion / 100); end; procedure TfrmPreferences.cmdOKClick(Sender: TObject); begin SavePreferences; end; procedure TfrmPreferences.cmdBrowseRightClick(Sender: TObject); begin ColorDialog.Color := imgRightText.Color; if ColorDialog.Execute then begin imgRightText.Color := ColorDialog.Color; end; end; procedure TfrmPreferences.cmdBrowseGridlinesClick(Sender: TObject); begin ColorDialog.Color := imgGridlineColour.Color; if ColorDialog.Execute then begin imgGridlineColour.Color := ColorDialog.Color; end; end; procedure TfrmPreferences.cmdBrowseClick(Sender: TObject); begin OpenDialog.Title := 'Please select a NES emulator'; OpenDialog.Filter := 'NES Emulator (*.exe)|*.exe'; if (txtEmulatorPath.Text <> '') and (DirectoryExists(ExtractFileDir(txtEmulatorPath.Text))) then OpenDialog.InitialDir := ExtractFileDir(txtEmulatorPath.Text); if OpenDialog.Execute then begin if (OpenDialog.FileName <> '') and (FileExists(OpenDialog.Filename)) then begin txtEmulatorPath.Text := OpenDialog.FileName; txtEmulatorPath.SelStart := Length(txtEmulatorPath.Text); end; end; end; procedure TfrmPreferences.cmdRestoreDefaultsClick(Sender: TObject); begin EditorConfig.LoadDefaultSettings; EditorConfig.Save; LoadPreferences; end; procedure TfrmPreferences.LoadDataFiles(); begin cbDataFile.Items.Clear; cbDataFile.Items.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\data.dat'); end; procedure TfrmPreferences.LoadPaletteFiles(); var sr: TSearchRec; begin cbPaletteFile.Items.BeginUpdate; cbPaletteFile.Items.Clear; if FindFirst(ExtractFileDir(Application.ExeName)+ '\Data\Palettes\*.pal', faAnyFile, sr) = 0 then begin repeat cbPaletteFile.Items.Add(sr.Name); until FindNext(sr) <> 0; FindClose(sr); end; cbPaletteFile.Items.EndUpdate; // cbPaletteFile.Items.LoadFromFile(ExtractFileDir(Application.Exename) + '\Data\Palettes\pal.dat'); end; procedure TfrmPreferences.cmdIPSBrowseClick(Sender: TObject); begin OpenDialog.Title := 'Select an original unmodified Rush''n Attack ROM'; OpenDialog.Filter := 'iNES Image (*.nes)|*.nes'; if (txtOriginalROMFilename.Text <> '') and (DirectoryExists(ExtractFileDir(txtOriginalROMFilename.Text))) then OpenDialog.InitialDir := ExtractFileDir(txtOriginalROMFilename.Text) else OpenDialog.InitialDir := ExtractFileDir(Application.ExeName); if OpenDialog.Execute then begin if (OpenDialog.FileName <> '') and (FileExists(OpenDialog.Filename)) then begin txtOriginalROMFilename.Text := OpenDialog.FileName; txtOriginalROMFilename.SelStart := Length(txtOriginalROMFilename.Text); end; end; end; procedure TfrmPreferences.cmdBrowseIPSSaveAsClick(Sender: TObject); begin if (txtSaveAsIPS.Text <> '') and (DirectoryExists(ExtractFileDir(txtSaveAsIPS.Text))) then SaveDialog.InitialDir := ExtractFileDir(txtSaveAsIPS.Text) else SaveDialog.InitialDir := ExtractFileDir(Application.ExeName); if SaveDialog.Execute then begin txtSaveAsIPS.Text := SaveDialog.FileName; txtSaveAsIPS.SelStart := Length(txtSaveAsIPS.Text); end; end; procedure TfrmPreferences.cmdSpecObjOutlineClick(Sender: TObject); begin ColorDialog.Color := imgSpecObjOutline.Color; if ColorDialog.Execute then begin imgSpecObjOutline.Color := ColorDialog.Color; end; end; end.
unit uFrmAuto; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TFrmAuto = class(TForm) gbOil: TGroupBox; Label1: TLabel; edtMetre: TEdit; Label2: TLabel; edtPrice: TEdit; Label3: TLabel; edtCount: TEdit; Label4: TLabel; edtTotal: TEdit; Label5: TLabel; Label6: TLabel; cbQua: TComboBox; dtDate: TDateTimePicker; Label7: TLabel; mmComment: TMemo; btnAdd: TButton; GroupBox1: TGroupBox; Label8: TLabel; edtFeePrice: TEdit; Label9: TLabel; edtFeeCount: TEdit; Label10: TLabel; edtFeeTotal: TEdit; Label11: TLabel; dtFeeDate: TDateTimePicker; Label12: TLabel; mmFeeComment: TMemo; btnFeeAdd: TButton; btnClose: TButton; procedure btnAddClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnFeeAddClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); private { Private declarations } public { Public declarations } end; procedure ShowAutoForm; implementation uses uLogMgr; {$R *.dfm} procedure ShowAutoForm; var Frm: TFrmAuto; begin Frm := TFrmAuto.Create(Application); Frm.ShowModal; Frm.Free; end; procedure TFrmAuto.btnAddClick(Sender: TObject); var strDate: string; begin strDate := DateToStr(dtDate.Date); if not LM_AddAutoOil(PChar(edtPrice.Text), PChar(edtCount.Text), PChar(edtTotal.Text), PChar(strDate), PChar(edtMetre.Text), PChar(mmComment.Lines.Text)) then ShowMessage('¼ÓÈëʧ°Ü'); edtCount.Clear; edtTotal.Clear; edtMetre.Clear; mmComment.Lines.Clear; end; procedure TFrmAuto.btnCloseClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFrmAuto.btnFeeAddClick(Sender: TObject); var strDate: string; begin strDate := DateToStr(dtFeeDate.Date); if not LM_AddAutoFee(PChar(edtFeePrice.Text), PChar(edtFeeCount.Text), PChar(edtFeeTotal.Text), PChar(strDate), PChar(mmFeeComment.Lines.Text)) then ShowMessage('¼ÓÈëʧ°Ü'); edtFeePrice.Clear; edtFeeCount.Clear; edtFeeTotal.Clear; mmFeeComment.Lines.Clear; end; procedure TFrmAuto.FormCreate(Sender: TObject); begin dtFeeDate.DateTime := Now; dtDate.DateTime := Now; end; procedure TFrmAuto.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin Resize := False; end; end.
{$I ACBr.inc} unit pciotMotoristaR; interface uses SysUtils, Classes, {$IFNDEF VER130} Variants, {$ENDIF} pcnAuxiliar, pcnConversao, pciotCIOT, ASCIOTUtil; type TMotoristaR = class(TPersistent) private FLeitor: TLeitor; FMotorista: TMotorista; FSucesso: Boolean; FMensagem: String; FOperacao: TpciotOperacao; public constructor Create(AOwner: TMotorista; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function LerXml: boolean; property Sucesso: Boolean read FSucesso write FSucesso; property Mensagem: String read FMensagem write FMensagem; published property Leitor: TLeitor read FLeitor write FLeitor; property Motorista: TMotorista read FMotorista write FMotorista; end; implementation { TMotoristaR } constructor TMotoristaR.Create(AOwner: TMotorista; AOperacao: TpciotOperacao = opObter); begin FLeitor := TLeitor.Create; FMotorista := AOwner; FOperacao := AOperacao; end; destructor TMotoristaR.Destroy; begin FLeitor.Free; inherited Destroy; end; function TMotoristaR.LerXml: boolean; begin case FOperacao of opObter: begin if Leitor.rExtrai(1, 'ObterResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); end; end; opAdicionar: begin if Leitor.rExtrai(1, 'GravarResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); end; end; end; if Leitor.rExtrai(1, 'Motorista') <> '' then begin with Motorista do begin CPF := Leitor.rCampo(tcStr, 'CPF'); CNH := Leitor.rCampo(tcStr, 'CNH'); DataNascimento := Leitor.rCampo(tcDat, 'DataNascimento'); Nome := Leitor.rCampo(tcStr, 'Nome'); NomeDeSolteiraDaMae := Leitor.rCampo(tcStr, 'NomeDeSolteiraDaMae'); if Leitor.rExtrai(1, 'Endereco') <> '' then begin Endereco.Rua := Leitor.rCampo(tcStr, 'Rua ' + NAME_SPACE_EFRETE_OBJECTS, '/Rua'); Endereco.Numero := Leitor.rCampo(tcStr, 'Numero ' + NAME_SPACE_EFRETE_OBJECTS, '/Numero'); Endereco.Complemento := Leitor.rCampo(tcStr, 'Complemento ' + NAME_SPACE_EFRETE_OBJECTS, '/Complemento'); Endereco.Bairro := Leitor.rCampo(tcStr, 'Bairro ' + NAME_SPACE_EFRETE_OBJECTS, '/Bairro'); Endereco.CodigoMunicipio := Leitor.rCampo(tcInt, 'CodigoMunicipio ' + NAME_SPACE_EFRETE_OBJECTS, '/CodigoMunicipio'); Endereco.CEP := Leitor.rCampo(tcInt, 'CEP ' + NAME_SPACE_EFRETE_OBJECTS, '/CEP'); end; if Leitor.rExtrai(1, 'Telefones') <> '' then begin if Leitor.rExtrai(1, 'Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'Celular') <> '' then begin Telefones.Celular.DDD := Leitor.rCampo(tcInt, 'DDD'); Telefones.Celular.Numero := Leitor.rCampo(tcInt, 'Numero'); end; if Leitor.rExtrai(1, 'Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'Fax') <> '' then begin Telefones.Fax.DDD := Leitor.rCampo(tcInt, 'DDD'); Telefones.Fax.Numero := Leitor.rCampo(tcInt, 'Numero'); end; if Leitor.rExtrai(1, 'Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'Fixo') <> '' then begin Telefones.Fixo.DDD := Leitor.rCampo(tcInt, 'DDD'); Telefones.Fixo.Numero := Leitor.rCampo(tcInt, 'Numero'); end; end; end; end; Result := true; end; end.
unit GX_ProofreaderConfig; {$I GX_CondDefine.inc} interface uses Classes, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ActnList, ToolWin, ExtCtrls, Menus, Messages, GX_ProofreaderExpert, GX_ProofreaderData, GX_ProofreaderUtils, GX_SharedImages, GX_BaseForm; const UM_UPDATECOLS = WM_USER + 632; type TfmProofreaderConfig = class(TfmBaseForm) Actions: TActionList; actListDelete: TAction; actListInsert: TAction; actListEdit: TAction; pmList: TPopupMenu; pmiListInsert: TMenuItem; pmiListEdit: TMenuItem; pmiListDelete: TMenuItem; pmHistory: TPopupMenu; actDisableRule: TAction; pmiDisableRule: TMenuItem; pnlMain: TPanel; pnlButtons: TPanel; Pages: TPageControl; tabReplacement: TTabSheet; pnlReplacement: TPanel; lvReplacement: TListView; pnlACHeader: TPanel; tbrReplacement: TToolBar; tbnReplacementInsert: TToolButton; tbnReplacementEdit: TToolButton; tbnReplacementDelete: TToolButton; cbReplacerActive: TCheckBox; tabDictionary: TTabSheet; pnlDictionary: TPanel; gbxWords: TGroupBox; pnlWords: TPanel; tbrDictionary: TToolBar; tbnDictionaryInsert: TToolButton; tbnDictionaryEdit: TToolButton; tbnDictionaryDelete: TToolButton; tbnDictionarySep: TToolButton; tbnDictionaryExport: TToolButton; tbnDictionaryImport: TToolButton; lvDictionary: TListView; pnlDictOptions: TPanel; gbReplaceIf: TGroupBox; cbOneCharIncorrect: TCheckBox; cbAllowOneCharacterMissing: TCheckBox; cbAllowExtraChar: TCheckBox; cbCaseDiffer: TCheckBox; cbAllowSwitchedChars: TCheckBox; cbMustBeNearbyLetter: TCheckBox; cbFirstCharMustBeCorrect: TCheckBox; cbEnableDictionary: TCheckBox; cbEnableCompiler: TCheckBox; tabHistory: TTabSheet; pnlHistory: TPanel; lvHistory: TListView; pnlHistoryButtons: TPanel; btnDisableRule: TButton; pnlTop: TPanel; lblRules: TLabel; cbLanguage: TComboBox; cbBeep: TCheckBox; actImportWords: TAction; actExportWords: TAction; pnlButtonsRight: TPanel; btnOK: TButton; btnCancel: TButton; btnHelp: TButton; procedure FormShow(Sender: TObject); procedure cbLanguageChange(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure actDisableRuleExecute(Sender: TObject); procedure cbEnableDicitionaryClick(Sender: TObject); procedure cbEnableCompilerClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure cbOneCharIncorrectClick(Sender: TObject); procedure lvDictionaryDblClick(Sender: TObject); procedure lvReplacementDblClick(Sender: TObject); procedure actListInsertExecute(Sender: TObject); procedure actListEditExecute(Sender: TObject); procedure actListDeleteExecute(Sender: TObject); procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean); procedure actImportWordsExecute(Sender: TObject); procedure actExportWordsExecute(Sender: TObject); procedure lvDictionaryData(Sender: TObject; Item: TListItem); procedure lvReplacementData(Sender: TObject; Item: TListItem); procedure PagesChange(Sender: TObject); procedure UMUpdateCols(var Msg: TMessage); message UM_UPDATECOLS; private FProofreaderExpert: TCodeProofreaderExpert; FProofreaderData: TProofreaderData; procedure UpdateHistoryGrid; procedure UpdateReplacementList; procedure UpdateDictionaryList; function GetReplacementSource: TReplacementSource; function ActiveTab: TTabSheet; procedure UpdateDisplayedData; procedure UpdateColumnWidths; public constructor Create(AOwner: TComponent; ProofreaderExpert: TCodeProofreaderExpert; ProofreaderData: TProofreaderData); reintroduce; end; implementation uses SysUtils, Windows, GX_ProofreaderAutoCorrectEntry, GX_KibitzComp, GX_GxUtils, GX_GenericUtils, GX_OtaUtils; {$R *.dfm} constructor TfmProofreaderConfig.Create(AOwner: TComponent; ProofreaderExpert: TCodeProofreaderExpert; ProofreaderData: TProofreaderData); var TabIndex: Integer; begin inherited Create(AOwner); SetToolbarGradient(tbrReplacement); SetToolbarGradient(tbrDictionary); Assert(Assigned(ProofreaderExpert)); FProofreaderExpert := ProofreaderExpert; Assert(Assigned(ProofreaderData)); FProofreaderData := ProofreaderData; TabIndex := FProofreaderData.ActiveTab; if (TabIndex > -1) and (TabIndex < Pages.PageCount) then Pages.ActivePageIndex := TabIndex; end; function TfmProofreaderConfig.GetReplacementSource: TReplacementSource; begin Assert(cbLanguage.ItemIndex > -1); Result := TReplacementSource(cbLanguage.ItemIndex); end; procedure TfmProofreaderConfig.UpdateHistoryGrid; resourcestring SReplacementInfoHeader = 'Correction'; SReplacementTime = 'Time'; var i: Integer; Item: TListItem; CorrectionHistory: TCorrectionHistory; begin CorrectionHistory := FProofreaderData.History; lvHistory.Column[0].Caption := SReplacementInfoHeader; lvHistory.Column[1].Caption := SReplacementTime; lvHistory.Items.Clear; for i := 0 to CorrectionHistory.Count - 1 do begin Item := lvHistory.Items.Add; Item.Caption := CorrectionHistory[i].InfoString; Item.SubItems.Add(FormatDateTime('hh:nn:ss', CorrectionHistory[i].Time)); Item.Data := Pointer(i); end; end; procedure TfmProofreaderConfig.UpdateReplacementList; begin lvReplacement.Items.Count := FProofreaderData.GetReplacementCount(GetReplacementSource); UpdateColumnWidths; lvReplacement.Invalidate; end; procedure TfmProofreaderConfig.UpdateDictionaryList; begin lvDictionary.Items.Count := FProofreaderData.GetDictionaryCount(GetReplacementSource); UpdateColumnWidths; lvDictionary.Invalidate; end; procedure TfmProofreaderConfig.FormShow(Sender: TObject); var i: TReplacementSource; begin // Fill combo box with "languages" to select from for i := Low(TReplacementSource) to High(TReplacementSource) do cbLanguage.Items.Add(ReplacementSourceText[i]); // Initialize option settings cbBeep.Checked := FProofreaderData.BeepOnReplace; cbReplacerActive.Checked := FProofreaderData.ReplacerActive; cbEnableDictionary.Checked := FProofreaderData.DictionaryActive; cbEnableCompiler.Checked := FProofreaderData.CompilerActive; cbCaseDiffer.Checked := FProofreaderData.DictionaryCaseMayDiffer; cbOneCharIncorrect.Checked := FProofreaderData.OneCharIncorrect; cbMustBeNearbyLetter.Checked := FProofreaderData.MustBeNearbyLetter; cbAllowOneCharacterMissing.Checked := FProofreaderData.AllowOneCharacterMissing; cbAllowExtraChar.Checked := FProofreaderData.AllowExtraChar; cbAllowSwitchedChars.Checked := FProofreaderData.AllowSwitchedChars; cbFirstCharMustBeCorrect.Checked := FProofreaderData.FirstCharMustBeCorrect; cbEnableCompiler.Enabled := KibitzEnabled; if not cbEnableCompiler.Enabled then cbEnableCompiler.Checked := False; case GxOtaGetCurrentSyntaxHighlighter of gxpNone, gxpPlaceHolder, gxpPAS: cbLanguage.ItemIndex := Ord(rtPasSrc); gxpCPP: cbLanguage.ItemIndex := Ord(rtCPPSrc); gxpSQL: cbLanguage.ItemIndex := Ord(rtSQLSrc); gxpCS: cbLanguage.ItemIndex := Ord(rtCSSrc); end; UpdateDisplayedData; end; procedure TfmProofreaderConfig.btnOKClick(Sender: TObject); var Cursor: IInterface; begin Cursor := TempHourGlassCursor; with FProofreaderData do begin // Store options BeepOnReplace := cbBeep.Checked; ReplacerActive := cbReplacerActive.Checked; DictionaryActive := cbEnableDictionary.Checked; CompilerActive := cbEnableCompiler.Checked; DictionaryCaseMayDiffer := cbCaseDiffer.Checked; OneCharIncorrect := cbOneCharIncorrect.Checked; MustBeNearbyLetter := cbMustBeNearbyLetter.Checked; AllowOneCharacterMissing := cbAllowOneCharacterMissing.Checked; AllowExtraChar := cbAllowExtraChar.Checked; AllowSwitchedChars := cbAllowSwitchedChars.Checked; FirstCharMustBeCorrect := cbFirstCharMustBeCorrect.Checked; ActiveTab := Pages.ActivePageIndex; // Save the modified dictionary and replacement tables to disk SaveData; // Reload data from the tables based on the new settings //ReloadData; end; end; procedure TfmProofreaderConfig.cbLanguageChange(Sender: TObject); begin UpdateDisplayedData; end; procedure TfmProofreaderConfig.actDisableRuleExecute(Sender: TObject); resourcestring SRuleRemoved = 'Rule has been removed from replacement table.'; SWordAdded = 'The word "%s" has been added to the dictionary for %s.'; SWordNotFound = 'The AutoCorrect word ''%s'' could not be found (%s)'; var Correction: TCorrectionItem; Index: Integer; begin try Correction := FProofreaderData.History[Integer(lvHistory.Selected.Data)]; if Correction <> nil then begin case Correction.CorrectionKind of ckAutoCorrection: begin Index := FProofreaderData.FindReplacementIndex(Correction.SourceLanguage, AnsiUpperCase(Correction.OriginalText)); if Index >= 0 then begin FProofreaderData.DeleteReplacementEntry(Correction.SourceLanguage, Index, Correction.OriginalText); UpdateReplacementList; MessageDlg(SRuleRemoved, mtInformation, [mbOK], 0); end else begin MessageDlg(Format(SWordNotFound, [Correction.OriginalText, ReplacementSourceText[Correction.SourceLanguage]]), mtInformation, [mbOK], 0); end; end; ckWord: begin FProofreaderData.AddToDictionary(Correction.SourceLanguage, Correction.OriginalText); UpdateDictionaryList; MessageDlg(Format(SWordAdded, [Correction.OriginalText, ReplacementSourceText[Correction.SourceLanguage]]), mtInformation, [mbOK], 0); end; end; // case end; except on E: Exception do begin // Swallow exceptions end; end; end; procedure TfmProofreaderConfig.cbEnableDicitionaryClick(Sender: TObject); var i: Integer; begin for i := 0 to gbReplaceIf.ControlCount - 1 do gbReplaceIf.Controls[i].Enabled := cbEnableDictionary.Checked or cbEnableCompiler.Checked; cbMustBeNearbyLetter.Enabled := cbMustBeNearbyLetter.Enabled and cbOneCharIncorrect.Checked; cbFirstCharMustBeCorrect.Enabled := cbEnableDictionary.Checked or cbEnableCompiler.Checked end; procedure TfmProofreaderConfig.cbEnableCompilerClick(Sender: TObject); var i: Integer; begin for i := 0 to gbReplaceIf.ControlCount - 1 do gbReplaceIf.Controls[i].Enabled := cbEnableDictionary.Checked or cbEnableCompiler.Checked; cbMustBeNearbyLetter.Enabled := cbMustBeNearbyLetter.Enabled and cbOneCharIncorrect.Checked; cbFirstCharMustBeCorrect.Enabled := cbEnableDictionary.Checked or cbEnableCompiler.Checked end; procedure TfmProofreaderConfig.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 20); end; procedure TfmProofreaderConfig.cbOneCharIncorrectClick(Sender: TObject); begin cbMustBeNearbyLetter.Enabled := cbOneCharIncorrect.Checked and cbOneCharIncorrect.Enabled; end; procedure TfmProofreaderConfig.lvDictionaryDblClick(Sender: TObject); begin if Assigned(lvDictionary.Selected) then actListEdit.Execute else actListInsert.Execute; end; procedure TfmProofreaderConfig.lvReplacementDblClick(Sender: TObject); begin if Assigned(lvReplacement.Selected) then actListEdit.Execute else actListInsert.Execute; end; function ExecuteDictionaryEntryForm(var Entry: string; Add: Boolean): Boolean; resourcestring SDlgCaptionAdd = 'Add Dictionary Entry'; SDlgCaptionEdit = 'Edit Dictionary Entry'; SLabelEntry = 'Entry:'; var DictionaryWord: string; begin if Add then begin DictionaryWord := ''; Result := InputQuery(SDlgCaptionAdd, SLabelEntry, DictionaryWord); end else begin DictionaryWord := Entry; Result := InputQuery(SDlgCaptionEdit, SLabelEntry, DictionaryWord); end; if Result then begin DictionaryWord := Trim(DictionaryWord); if DictionaryWord = '' then Result := False else Entry := DictionaryWord; end; end; procedure TfmProofreaderConfig.actListInsertExecute(Sender: TObject); procedure InsertReplace; var TypedString, ReplaceWithString: string; ReplaceWhere: TGXWhereReplace; begin try if TfmProofreaderAutoCorrectEntry.Execute(TypedString, ReplaceWhere, ReplaceWithString, True) then begin FProofreaderData.AddToReplacements(GetReplacementSource, TypedString, ReplaceWhere, ReplaceWithString); UpdateReplacementList; end; except on E: Exception do GxLogAndShowException(E); end; end; procedure InsertDict; var Entry: string; begin try if ExecuteDictionaryEntryForm(Entry, True) then begin FProofreaderData.AddToDictionary(GetReplacementSource, Entry); UpdateDictionaryList; end; except on E: Exception do GxLogAndShowException(E); end; end; begin if ActiveTab = tabReplacement then InsertReplace else if ActiveTab = tabDictionary then InsertDict; end; procedure TfmProofreaderConfig.actListEditExecute(Sender: TObject); procedure EditReplace; var Item: TListItem; ItemIndex: Integer; OrigTypedString: string; NewTypedString, NewReplaceWithString: string; NewReplaceWhere: TGXWhereReplace; AReplacement: TReplacementItem; begin Item := lvReplacement.Selected; Assert(Assigned(Item)); try ItemIndex := Item.Index; AReplacement := FProofreaderData.GetReplacementEntry(GetReplacementSource, ItemIndex); OrigTypedString := AReplacement.Typed; NewTypedString := OrigTypedString; NewReplaceWhere := AReplacement.Where; NewReplaceWithString := AReplacement.Replace; if TfmProofreaderAutoCorrectEntry.Execute(NewTypedString, NewReplaceWhere, NewReplaceWithString, False) then begin FProofreaderData.SetReplacementEntry(GetReplacementSource, ItemIndex, OrigTypedString, NewTypedString, NewReplaceWhere, NewReplaceWithString); UpdateReplacementList; end; except on E: Exception do GxLogAndShowException(E); end; end; procedure EditDict; var Item: TListItem; ItemIndex: Integer; OrigValue: string; NewValue: string; begin Item := lvDictionary.Selected; Assert(Assigned(Item)); try ItemIndex := Item.Index; OrigValue := Item.Caption; NewValue := OrigValue; if ExecuteDictionaryEntryForm(NewValue, False) then begin FProofreaderData.SetDictionaryEntry(GetReplacementSource, ItemIndex, OrigValue, NewValue); UpdateDictionaryList; end; except on E: Exception do GxLogAndShowException(E); end; end; begin if ActiveTab = tabReplacement then EditReplace else if ActiveTab = tabDictionary then EditDict; end; procedure TfmProofreaderConfig.actListDeleteExecute(Sender: TObject); procedure DeleteReplace; var i: Integer; begin for i := lvReplacement.Items.Count - 1 downto 0 do if lvReplacement.Items[i].Selected then begin lvReplacement.Items[i].Selected := False; FProofreaderData.DeleteReplacementEntry(GetReplacementSource, i, lvReplacement.Items[i].Caption); end; UpdateReplacementList; end; procedure DeleteDict; var i: Integer; begin for i := lvDictionary.Items.Count - 1 downto 0 do if lvDictionary.Items[i].Selected then begin lvDictionary.Items[i].Selected := False; FProofreaderData.DeleteDictionaryEntry(GetReplacementSource, i, lvDictionary.Items[i].Caption); end; UpdateDictionaryList; end; begin if ActiveTab = tabReplacement then DeleteReplace else if ActiveTab = tabDictionary then DeleteDict; end; procedure TfmProofreaderConfig.ActionsUpdate(Action: TBasicAction; var Handled: Boolean); var SelCount: Integer; begin if ActiveTab = tabReplacement then SelCount := lvReplacement.SelCount else if ActiveTab = tabDictionary then SelCount := lvDictionary.SelCount else if ActiveTab = tabHistory then SelCount := lvHistory.SelCount else raise Exception.Create('Unknown tab activated'); actListDelete.Enabled := SelCount > 0; actListEdit.Enabled := SelCount = 1; actDisableRule.Enabled := SelCount = 1; actExportWords.Enabled := lvDictionary.Items.Count > 0; end; procedure TfmProofreaderConfig.actImportWordsExecute(Sender: TObject); resourcestring LargeListMsg = 'Importing word lists with over a thousand entries is not recommended for performance reasons. Continue anyway?'; var Words: TStringList; i: Integer; fn: string; begin if not ShowOpenDialog('Select a word list file (one word per line)', 'txt', fn, 'Text Files (*.txt)|*.txt') then Exit; if FileExists(fn) then begin Words := TStringList.Create; try Words.LoadFromFile(fn); if Words.Count > 1000 then if not (MessageDlg(LargeListMsg, mtWarning, [mbYes, mbNo], 0) = mrYes) then Exit; for i := 0 to Words.Count - 1 do try FProofreaderData.AddToDictionary(GetReplacementSource, Trim(Words[i]), False); except on E: Exception do GxLogException(E); end; finally FProofreaderData.ResortDictionary(GetReplacementSource); UpdateDictionaryList; FreeAndNil(Words); end; end; end; procedure TfmProofreaderConfig.actExportWordsExecute(Sender: TObject); var AFile: TextFile; i: Integer; fn: string; begin if not ShowSaveDialog('Select a file to write the word list to', 'txt', fn, 'Text Files (*.txt)|*.txt') then Exit; AssignFile(AFile, fn); Rewrite(AFile); try for i := 0 to FProofreaderData.GetDictionaryCount(GetReplacementSource) - 1 do WriteLn(AFile, FProofreaderData.GetDictionaryEntry(GetReplacementSource, i)); finally CloseFile(AFile); end; end; function TfmProofreaderConfig.ActiveTab: TTabSheet; begin Result := Pages.ActivePage; end; procedure TfmProofreaderConfig.UpdateDisplayedData; begin UpdateHistoryGrid; UpdateReplacementList; UpdateDictionaryList; UpdateColumnWidths; end; procedure TfmProofreaderConfig.lvDictionaryData(Sender: TObject; Item: TListItem); begin Item.Caption := FProofreaderData.GetDictionaryEntry(GetReplacementSource, Item.Index); end; procedure TfmProofreaderConfig.lvReplacementData(Sender: TObject; Item: TListItem); var AReplacement: TReplacementItem; begin AReplacement := FProofreaderData.GetReplacementEntry(GetReplacementSource, Item.Index); Item.Caption := AReplacement.Typed; Item.SubItems.Add(GXWhereReplaceStrings[AReplacement.Where]); Item.SubItems.Add(AReplacement.Replace); end; procedure TfmProofreaderConfig.UpdateColumnWidths; begin PostMessage(Self.Handle, UM_UPDATECOLS, 0, 0) end; procedure TfmProofreaderConfig.PagesChange(Sender: TObject); begin UpdateColumnWidths; end; procedure TfmProofreaderConfig.UMUpdateCols(var Msg: TMessage); begin // Hacks to get the listview columns sizing right on startup, when the // language changes, and when items are added/deleted lvReplacement.Width := lvReplacement.Width + 1; lvDictionary.Width := lvDictionary.Width + 1; end; end.
unit seibu_sound; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} sound_engine,misc_functions,main_engine,nz80,ym_3812,oki6295, ym_2151,msm5205; type seibu_adpcm_chip=class constructor create; procedure free; public procedure reset; procedure adr_w(dir:word;valor:byte); procedure ctl_w(valor:byte); private mem:pbyte; nibble,msm5205_num:byte; current,end_:dword; playing:boolean; end; seibu_snd_type=class(snd_chip_class) constructor create(snd_type:byte;clock,cpu_sync:dword;snd_rom:pbyte;encrypted:boolean;amp:single=1); destructor free; public z80:cpu_z80; adpcm_0,adpcm_1:seibu_adpcm_chip; sound_rom:array[0..1,0..$7fff] of byte; input:byte; procedure reset; function get(direccion:byte):byte; procedure put(direccion,valor:byte); function oki_6295_get_rom_addr:pbyte; procedure adpcm_load_roms(adpcm_rom:pbyte;size:dword); private main2sub_pending,sub2main_pending,encrypted:boolean; sound_latch,sub2main:array[0..1] of byte; decrypt:array[0..$1fff] of byte; snd_type,snd_bank,irq1,irq2:byte; procedure update_irq_lines(param:byte); procedure decript_sound; end; const RESET_ASSERT=0; RST10_ASSERT=1; RST10_CLEAR=2; RST18_ASSERT=3; RST18_CLEAR=4; SEIBU_ADPCM=0; SEIBU_OKI=1; var seibu_snd_0:seibu_snd_type; num_msm5205:integer=-1; implementation function oki_getbyte(direccion:word):byte; begin case direccion of 0..$1fff:if seibu_snd_0.z80.opcode then oki_getbyte:=seibu_snd_0.decrypt[direccion] else oki_getbyte:=mem_snd[direccion]; $2000..$27ff:oki_getbyte:=mem_snd[direccion]; $4008:oki_getbyte:=ym3812_0.status; $4010:oki_getbyte:=seibu_snd_0.sound_latch[0]; $4011:oki_getbyte:=seibu_snd_0.sound_latch[1]; $4012:oki_getbyte:=byte(seibu_snd_0.sub2main_pending); $4013:oki_getbyte:=seibu_snd_0.input; $6000:oki_getbyte:=oki_6295_0.read; $8000..$ffff:oki_getbyte:=seibu_snd_0.sound_rom[seibu_snd_0.snd_bank,direccion and $7fff]; else if seibu_snd_0.z80.opcode then oki_getbyte:=seibu_snd_0.decrypt[direccion] else oki_getbyte:=mem_snd[direccion]; end; end; procedure oki_putbyte(direccion:word;valor:byte); begin case direccion of 0..$1fff,$8000..$ffff:; //ROM $2000..$27ff:mem_snd[direccion]:=valor; $4000:begin seibu_snd_0.main2sub_pending:=false; seibu_snd_0.sub2main_pending:=true; end; $4001:;//seibu_update_irq_lines(RESET_ASSERT); $4002:; $4003:seibu_snd_0.update_irq_lines(RST18_CLEAR); $4007:seibu_snd_0.snd_bank:=valor and 1; $4008:ym3812_0.control(valor); $4009:ym3812_0.write(valor); $4018:seibu_snd_0.sub2main[0]:=valor; $4019:seibu_snd_0.sub2main[1]:=valor; $6000:oki_6295_0.write(valor); end; end; procedure oki_sound_update; begin ym3812_0.update; oki_6295_0.update; end; function adpcm_getbyte(direccion:word):byte; begin case direccion of 0..$1fff:if seibu_snd_0.z80.opcode then adpcm_getbyte:=seibu_snd_0.decrypt[direccion] else adpcm_getbyte:=mem_snd[direccion]; $2000..$27ff,$8000..$ffff:adpcm_getbyte:=mem_snd[direccion]; $4008:adpcm_getbyte:=ym2151_0.status; $4010:adpcm_getbyte:=seibu_snd_0.sound_latch[0]; $4011:adpcm_getbyte:=seibu_snd_0.sound_latch[1]; $4012:adpcm_getbyte:=byte(seibu_snd_0.sub2main_pending); $4013:adpcm_getbyte:=seibu_snd_0.input; end; end; procedure adpcm_putbyte(direccion:word;valor:byte); begin case direccion of 0..$1fff,$8000..$ffff:; //ROM $2000..$27ff:mem_snd[direccion]:=valor; $4001,$4002:; $4003:seibu_snd_0.update_irq_lines(RST18_CLEAR); $4005:seibu_snd_0.adpcm_0.adr_w(0,valor); $4006:seibu_snd_0.adpcm_0.adr_w(1,valor); $4008:ym2151_0.reg(valor); $4009:ym2151_0.write(valor); $4018:seibu_snd_0.sub2main[0]:=valor; $4019:seibu_snd_0.sub2main[1]:=valor; $401a:seibu_snd_0.adpcm_0.ctl_w(valor); $401b:; $6005:seibu_snd_0.adpcm_1.adr_w(0,valor); $6006:seibu_snd_0.adpcm_1.adr_w(1,valor); $601a:seibu_snd_0.adpcm_1.ctl_w(valor); end; end; procedure adpcm_sound_update; begin ym2151_0.update; end; procedure snd_irq(irqstate:byte); begin if irqstate=1 then seibu_snd_0.update_irq_lines(RST10_ASSERT) else seibu_snd_0.update_irq_lines(RST10_CLEAR); end; constructor seibu_snd_type.create(snd_type:byte;clock,cpu_sync:dword;snd_rom:pbyte;encrypted:boolean;amp:single=1); begin self.z80:=cpu_z80.create(clock,cpu_sync); self.snd_type:=snd_type; self.encrypted:=encrypted; //Copio los datos en las dos memorias, por si no estan cifrados... copymemory(@self.decrypt,snd_rom,$2000); copymemory(@mem_snd,snd_rom,$2000); case snd_type of SEIBU_ADPCM:begin self.z80.change_ram_calls(adpcm_getbyte,adpcm_putbyte); self.z80.init_sound(adpcm_sound_update); self.adpcm_0:=seibu_adpcm_chip.create; self.adpcm_1:=seibu_adpcm_chip.create; ym2151_0:=ym2151_chip.create(clock,amp); ym2151_0.change_irq_func(snd_irq); end; SEIBU_OKI:begin self.z80.change_ram_calls(oki_getbyte,oki_putbyte); self.z80.init_sound(oki_sound_update); ym3812_0:=ym3812_chip.create(YM3812_FM,clock,amp); ym3812_0.change_irq_calls(snd_irq); oki_6295_0:=snd_okim6295.create(1000000,OKIM6295_PIN7_HIGH,0.40); end; end; end; destructor seibu_snd_type.free; begin self.z80.free; case self.snd_type of SEIBU_ADPCM:begin self.adpcm_0.free; self.adpcm_1.free; if ym2151_0<>nil then ym2151_0.free; end; SEIBU_OKI:begin if ym3812_0<>nil then ym3812_0.free; if oki_6295_0<>nil then oki_6295_0.free; end; end; end; procedure seibu_snd_type.reset; begin self.irq1:=$ff; self.irq2:=$ff; self.main2sub_pending:=false; self.sub2main_pending:=false; self.sound_latch[0]:=0; self.sound_latch[1]:=0; self.z80.reset; self.snd_bank:=0; if self.encrypted then self.decript_sound; case self.snd_type of SEIBU_ADPCM:begin ym2151_0.reset; self.adpcm_0.reset; self.adpcm_1.reset; end; SEIBU_OKI:begin ym3812_0.reset; oki_6295_0.reset; end; end; end; function seibu_snd_type.get(direccion:byte):byte; var ret:byte; begin ret:=$ff; case direccion of 2:ret:=sub2main[0]; 3:ret:=sub2main[1]; 5:ret:=byte(main2sub_pending); end; get:=ret; end; procedure seibu_snd_type.put(direccion,valor:byte); begin case direccion of 0:sound_latch[0]:=valor; 1:sound_latch[1]:=valor; 4:self.update_irq_lines(RST18_ASSERT); 2,6:begin sub2main_pending:=false; main2sub_pending:=true; end; end; end; procedure seibu_snd_type.update_irq_lines(param:byte); begin case param of RESET_ASSERT:begin irq1:=$ff; irq2:=$ff; end; RST10_ASSERT:irq1:=$d7; RST10_CLEAR:irq1:=$ff; RST18_ASSERT:irq2:=$df; RST18_CLEAR:irq2:=$ff; end; self.z80.im0:=self.irq1 and self.irq2; if (self.irq1 and self.irq2)=$ff then self.z80.change_irq(CLEAR_LINE) else self.z80.change_irq(ASSERT_LINE); end; procedure seibu_snd_type.decript_sound; var f,pos:dword; data_in:array[0..$1fff] of byte; function decrypt_data(a:word;src:byte):byte; begin if (BIT(a,9) and BIT(a,8)) then src:=src xor $80; if (BIT(a,11) and BIT(a,4) and BIT(a,1)) then src:=src xor $40; if (BIT(a,11) and not(BIT(a,8)) and BIT(a,1)) then src:=src xor $04; if (BIT(a,13) and not(BIT(a,6)) and BIT(a,4)) then src:=src xor $02; if (not(BIT(a,11)) and BIT(a,9) and BIT(a,2)) then src:=src xor $01; if (BIT(a,13) and BIT(a,4)) then src:=BITSWAP8(src,7,6,5,4,3,2,0,1); if (BIT(a, 8) and BIT(a,4)) then src:=BITSWAP8(src,7,6,5,4,2,3,1,0); decrypt_data:=src; end; function decrypt_opcode(a:word;src:byte):byte; begin if (BIT(a,9) and BIT(a,8)) then src:=src xor $80; if (BIT(a,11) and BIT(a,4) and BIT(a,1)) then src:=src xor $40; if (not(BIT(a,13)) and BIT(a,12)) then src:=src xor $20; if (not(BIT(a,6)) and BIT(a,1)) then src:=src xor $10; if (not(BIT(a,12)) and BIT(a,2)) then src:=src xor $08; if (BIT(a,11) and not(BIT(a,8)) and BIT(a,1)) then src:=src xor $04; if (BIT(a,13) and not(BIT(a,6)) and BIT(a,4)) then src:=src xor $02; if (not(BIT(a,11)) and BIT(a,9) and BIT(a,2)) then src:=src xor $01; if (BIT(a,13) and BIT(a,4)) then src:=BITSWAP8(src,7,6,5,4,3,2,0,1); if (BIT(a, 8) and BIT(a,4)) then src:=BITSWAP8(src,7,6,5,4,2,3,1,0); if (BIT(a,12) and BIT(a,9)) then src:=BITSWAP8(src,7,6,4,5,3,2,1,0); if (BIT(a,11) and not(BIT(a,6))) then src:=BITSWAP8(src,6,7,5,4,3,2,1,0); decrypt_opcode:=src; end; begin //Copio los datos temporalmente a un buffer, los voy a machacar... copymemory(@data_in,@self.decrypt,$2000); for f:=0 to $1fff do begin pos:=BITSWAP24(f,23,22,21,20,19,18,17,16,13,14,15,12,11,10,9,8,7,6,5,4,3,2,1,0); mem_snd[f]:=decrypt_data(f,data_in[pos]); self.decrypt[f]:=decrypt_opcode(f,data_in[pos]); end; end; //ADPCM procedure adpcm_0_update; var tempb:byte; begin if not(seibu_snd_0.adpcm_0.playing) then exit; tempb:=(seibu_snd_0.adpcm_0.mem[seibu_snd_0.adpcm_0.current] shr seibu_snd_0.adpcm_0.nibble) and $f; msm5205_0.data_w(tempb); seibu_snd_0.adpcm_0.nibble:=seibu_snd_0.adpcm_0.nibble xor 4; if (seibu_snd_0.adpcm_0.nibble=4) then begin seibu_snd_0.adpcm_0.current:=seibu_snd_0.adpcm_0.current+1; if (seibu_snd_0.adpcm_0.current>=seibu_snd_0.adpcm_0.end_) then begin msm5205_0.reset_w(1); seibu_snd_0.adpcm_0.playing:=false; end; end; end; procedure adpcm_1_update; var tempb:byte; begin if not(seibu_snd_0.adpcm_1.playing) then exit; tempb:=(seibu_snd_0.adpcm_1.mem[seibu_snd_0.adpcm_1.current] shr seibu_snd_0.adpcm_1.nibble) and $f; msm5205_1.data_w(tempb); seibu_snd_0.adpcm_1.nibble:=seibu_snd_0.adpcm_1.nibble xor 4; if (seibu_snd_0.adpcm_1.nibble=4) then begin seibu_snd_0.adpcm_1.current:=seibu_snd_0.adpcm_1.current+1; if (seibu_snd_0.adpcm_1.current>=seibu_snd_0.adpcm_1.end_) then begin msm5205_1.reset_w(1); seibu_snd_0.adpcm_1.playing:=false; end; end; end; constructor seibu_adpcm_chip.create; begin num_msm5205:=num_msm5205+1; self.msm5205_num:=num_msm5205; case num_msm5205 of 0:msm5205_0:=msm5205_chip.create(12000000 div 32,MSM5205_S48_4B,0.4,adpcm_0_update); 1:msm5205_1:=msm5205_chip.create(12000000 div 32,MSM5205_S48_4B,0.4,adpcm_1_update); end; end; procedure seibu_adpcm_chip.free; begin case self.msm5205_num of 0:if msm5205_0<>nil then msm5205_0.free; 1:if msm5205_1<>nil then msm5205_1.free; end; num_msm5205:=num_msm5205-1; freemem(self.mem); end; procedure seibu_adpcm_chip.reset; begin self.nibble:=0; self.current:=0; self.playing:=false; case self.msm5205_num of 0:msm5205_0.reset; 1:msm5205_1.reset; end; end; procedure seibu_adpcm_chip.adr_w(dir:word;valor:byte); begin if (dir<>0) then self.end_:=valor shl 8 else begin self.current:=valor shl 8; self.nibble:=4; end; end; procedure seibu_adpcm_chip.ctl_w(valor:byte); begin // sequence is 00 02 01 each time. case valor of 0:begin if self.msm5205_num=0 then msm5205_0.reset_w(1) else msm5205_1.reset_w(1); self.playing:=false; end; 1:begin if self.msm5205_num=0 then msm5205_0.reset_w(0) else msm5205_1.reset_w(0); self.playing:=true; end; 2:; end; end; procedure seibu_snd_type.adpcm_load_roms(adpcm_rom:pbyte;size:dword); var f:dword; begin getmem(self.adpcm_0.mem,size); getmem(self.adpcm_1.mem,size); for f:=0 to (size-1) do begin self.adpcm_0.mem[f]:=BITSWAP8(adpcm_rom[f],7,5,3,1,6,4,2,0); self.adpcm_1.mem[f]:=BITSWAP8(adpcm_rom[size+f],7,5,3,1,6,4,2,0); end; end; function seibu_snd_type.oki_6295_get_rom_addr:pbyte; begin oki_6295_get_rom_addr:=oki_6295_0.get_rom_addr; end; end.
unit FFSTypes; interface uses windows, messages, graphics; type TRegistrationRecord = record SystemActivated : boolean; InitialRunDate : string[20]; RunCount : integer; RunsAllowed : integer; UserCount : integer; CanAutoActivate : boolean; AutoCount : integer; AutoDate : string[10]; end; TDriveSerial = string[20]; TFFSReportDest = (rdScreen, rdPrinter, rdEmail); TFFSRptFormat = (rfHtml, rfAce, rfQuickRpt); // dates TFFSNonDate = (ndCont, ndWaived, ndHist, ndNA, ndSatisfied, ndNewLoan, ndOpen); TFFSNonDates = set of TFFSNonDate; // Specific Strings TStringLender = string[4]; // Report Stuff TFFSReportControl = (rcNone, rcDone, rcProblem, rcScan, rcReport); TFFSReportStatus = record Control : TFFSReportControl; PercentComp : integer; ScanMsg : string[30]; UserMsg : string[150]; end; TFieldsColorScheme = (fcsDataBackground, fcsDataLabel, fcsActiveEntryField, fcsDataText, fcsDataUnderline, fcsActionText, fcsActionRollover, fcsMainStatusBar, fcsMainFormBar, fcsMainFormBarText, fcsFormStatusBar, fcsFormActionBar, fcsTabActive, fcsTabInactive, fcsTabBackground, fcsTabNormalText, fcsTabDataText, fcsGridHighlight, fcsGridLowLight, fcsGridSelect, fcsGridTitleBar, fcsListBackground, fcsListRollover, fcsListSelected, fcsListText, fcsListSelectedText, fcsCaptions); const // colors used in FFS Programs FFSColor : array[TFieldsColorScheme] of TColor = (clWhite, clBlack, $00EBEBEB, clNavy, clSilver, clMaroon, clBlue, $00899B88, $00BAD6E2, $00EBEBEB, $00A9C0D6, $00C5D5E4, clwhite, $00BAD6E2, $00E6F8FF, clBlack, clMaroon, clwhite, clWhite, $00000040, $00C5D5E4, $00BAD6E2, $00899B88, clMaroon, clBlack, clYellow, $00A9C0D6); const // Maximum number of permissions allowed PermissionMax = 250; // Non-Date Strings dvStrings : array[TFFSNonDate] of string = ('CONT.', 'WAIVED', 'HISTORY', 'N/A', 'SATISF''D', 'NEW LOAN','OPEN'); sDateFormat : array[boolean] of string = ('mmddyyyy','mmyyyy'); sDispFormat : array[boolean] of string = ('mm/dd/yyyy', 'mm/yyyy'); procedure SetClearedDate(value:boolean); implementation uses sysutils, forms, filectrl; procedure SetClearedDate(value:boolean); begin if value then dvStrings[ndCont] := 'CLEARED' else dvstrings[ndCont] := 'CONT.'; end; end.
unit ExpertInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ExptIntf, ToolIntf, ComCtrls, EditIntf, VirtIntf; type TExpert = class(TForm) RichEdit1: TRichEdit; MainMenu1: TMainMenu; Tools1: TMenuItem; ViewAllNameofMenu1: TMenuItem; StatusBar1: TStatusBar; ProjectInformation1: TMenuItem; Editor1: TMenuItem; ViewEditor1: TMenuItem; Resulse1: TMenuItem; ProjectResource1: TMenuItem; procedure ViewAllNameofMenu1Click(Sender: TObject); procedure ProjectInformation1Click(Sender: TObject); procedure ViewEditor1Click(Sender: TObject); procedure ProjectResource1Click(Sender: TObject); private procedure SetDebug( Value: string ); public property Add: string write SetDebug; end; TMerchiseExpert = class( TIExpert ) private MenuItem: TIMenuItemIntf; protected procedure OnClick( Sender: TIMenuItemIntf); virtual; public constructor Create; virtual; destructor Destroy; override; function GetName: string; override; function GetAuthor: string; override; function GetStyle: TExpertStyle; override; function GetIDString: string; override; function GetComment: string; override; function GetPage: string; override; function GetGlyph: HICON; override; function GetState: TExpertState; override; function GetMenuText: string; override; procedure Execute; override; end; procedure Register; implementation {$R *.DFM} procedure Register; begin RegisterLibraryExpert( TMerchiseExpert.Create ); end; constructor TMerchiseExpert.Create; var Main: TIMainMenuIntf; ReferenceMenuItem: TIMenuItemIntf; Menu: TIMenuItemIntf; begin inherited Create; MenuItem := nil; if Assigned( ToolServices ) then begin Main := ToolServices.GetMainMenu; if Assigned( Main ) then try ReferenceMenuItem := Main.FindMenuItem('ToolsOptionsItem'); if Assigned( ReferenceMenuItem ) then try Menu := ReferenceMenuItem.GetParent; if Assigned( Menu ) then try MenuItem := Menu.InsertItem(ReferenceMenuItem.GetIndex+1, '&Expert Info', 'ExpertInfoMerchise','', 0,0,0, [mfEnabled, mfVisible], OnClick); finally Menu.DestroyMenuItem; end; finally ReferenceMenuItem.DestroyMenuItem; end; finally Main.Free; end; end; end; destructor TMerchiseExpert.Destroy; begin if Assigned( MenuItem ) then MenuItem.DestroyMenuItem; inherited Destroy; end; function TMerchiseExpert.GetName: string; begin Result := 'Merchise' end; function TMerchiseExpert.GetAuthor: string; begin Result := 'Roberto Alonso Gómez'; end; function TMerchiseExpert.GetStyle: TExpertStyle; begin Result := esAddIn; end; function TMerchiseExpert.GetIDString: String; begin Result := 'private.Merchise'; end; function TMerchiseExpert.GetComment: string; begin result := ''; end; function TMerchiseExpert.GetPage: string; begin result := ''; end; function TMerchiseExpert.GetGlyph: HICON; begin result := 0; end; function TMerchiseExpert.GetState: TExpertState; begin result := [esEnabled]; end; function TMerchiseExpert.GetMenuText: string; begin result := ''; end; procedure TMerchiseExpert.Execute; begin end; procedure TMerchiseExpert.OnClick( Sender: TIMenuItemIntf); begin with TExpert.Create(Application) do try ShowModal; finally Free; end; end; // TExpert function GetFlagsMenu( Flags: TIMenuFlags ): string; begin if mfInvalid in Flags then result := '_mfInvalid' else result := ''; if mfEnabled in Flags then result := '_mfEnabled'; if mfVisible in Flags then result := '_mfVisible'; if mfChecked in Flags then result := '_mfChecked'; if mfBreak in Flags then result := '_mfBreak'; if mfBarBreak in Flags then result := '_mfBarBreak'; if mfRadioItem in Flags then result := '_mfRadioItem'; end; procedure TExpert.SetDebug( Value: string ); begin RichEdit1.Lines.add( Value ); end; procedure TExpert.ViewAllNameofMenu1Click(Sender: TObject); const s = ' '; var Main: TIMainMenuIntf; Menu: TIMenuItemIntf; procedure DoMenu( aMenu: TIMenuItemIntf; Ind: integer ); var i : integer; vMenu : TIMenuItemIntf; NameM : string; begin with aMenu do begin inc( Ind, 4 ); NameM := GetName + ' [ ' + GetCaption + ' ]' + GetFlagsMenu( GetFlags ); if NameM<>'' then Add := copy( s, 1, Ind ) + NameM; for i := 0 to GetItemCount-1 do begin vMenu := GetItem( i ); if assigned( vMenu ) then try DoMenu( vMenu, Ind ); finally vMenu.release; end; end; end; end; begin if Assigned( ToolServices ) then begin Main := ToolServices.GetMainMenu; if Assigned( Main ) then try Menu := Main.GetMenuItems; if assigned( Menu ) then try Add := ' Merchise Info Menu'#10'Name [ Caption ] | Attributed'#10; DoMenu( Menu, 0 ); finally Menu.release; end; finally Main.release; end; end; end; procedure TExpert.ProjectInformation1Click(Sender: TObject); var i : integer; begin if Assigned( ToolServices ) then with ToolServices do begin Add := ' ToolServices.GetProjectName = ' + GetProjectName; Add := ' ToolServices.GetUnitCount = ' + IntToStr( GetUnitCount ); for i := 0 to GetUnitCount-1 do Add := ' GetUnitName( ' + IntToStr( i ) + ' ) = ' + GetUnitName( i ); Add := ' ToolServices.GetCurrentFile = ' + GetCurrentFile; Add := ' ToolServices.GetFormCount = ' + IntToStr( GetFormCount ); for i := 0 to GetFormCount-1 do Add := ' GetFormName( ' + IntToStr( i ) + ' ) = ' + GetFormName( i ); Add := ' ToolServices.GetModuleCount = ' + IntToStr( GetModuleCount ); for i := 0 to GetModuleCount-1 do Add := ' GetModuleName( ' + IntToStr( i ) + ' ) = ' + GetModuleName( i ) + ' GetComponentCount() = ' + IntToStr( GetComponentCount( i )); // Configuration Access Add := ' ToolServices.GetBaseRegistryKey = ' + GetBaseRegistryKey; end; end; procedure TExpert.ViewEditor1Click(Sender: TObject); var Module : TIModuleInterface; Editor : TIEditorInterface; View : TIEditView; CharPos : TCharPos; begin with ExptIntf.ToolServices do Module := GetModuleInterface( GetCurrentFile ); if Assigned( Module ) then try Editor := Module.GetEditorInterface; if Assigned( Editor ) then try add := 'Editor.LinesInBufferm = ' + IntToStr( Editor.LinesInBuffer ); add := 'Editor.FileName = ' + Editor.FileName; add := 'Editor.GetViewCount = ' + IntToStr( Editor.GetViewCount ); View := Editor.GetView( pred( Editor.GetViewCount )); if Assigned( View ) then try add := 'View Ok'; with View.GetViewSize do Add := 'ViewSize Cx = ' + IntToStr( cx ) + ' Cy = ' + IntToStr( cy ); with View.CursorPos do Add := 'CursorPo Col = ' + IntToStr( Col ) + ' Line = ' + IntToStr( Line ); with View.TopPos do Add := 'TopPos Col = ' + IntToStr( Col ) + ' Line = ' + IntToStr( Line ); CharPos.CharIndex := 255; CharPos.Line := Editor.LinesInBuffer; Add := ' Buffer Size 1 ' + IntToStr( View.CharPosToPos( CharPos )); CharPos.CharIndex := 0; CharPos.Line := $7fffffff; Add := ' Buffer Size 2 ' + IntToStr( View.CharPosToPos( CharPos )); finally View.free; end; finally Editor.free; end; finally Module.free; end; end; procedure TExpert.ProjectResource1Click(Sender: TObject); var Module : TIModuleInterface; Resource : TIResourceFile; Entry : TIResourceEntry; i : integer; begin with ExptIntf.ToolServices do Module := GetModuleInterface( GetCurrentFile ); if Assigned( Module ) then try Resource := Module.GetProjectResource; if assigned( Resource ) then with Resource do try Add := ' Resource.FileName = ' + FileName; Add := ' Resource.GetEntryCount = ' + IntToStr( GetEntryCount ); for i := 0 to GetEntryCount-1 do begin Entry := Resource.GetEntry( 1 ); if Assigned( Entry ) then with Entry do try add := ' Ok '; add := 'Entry.GetResourceName = ' + Entry.GetResourceName; // add := 'Entry.GetResourceType = ' + Entry.GetResourceType; finally free; end; end; finally free; end else add := ' No tiene recurso '; finally Module.free; end; end; end.
unit LoginFormU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, jpeg, ExtCtrls, md5, Buttons; type TLoginForm = class(TForm) Label3: TLabel; Label1: TLabel; PasswordEdit: TEdit; UserNameEdit: TEdit; Image1: TImage; Button1: TButton; Button2: TButton; SavePasswordCheck: TCheckBox; Label2: TLabel; LocationEdit: TEdit; LocationHelp: TSpeedButton; procedure LocationHelpClick(Sender: TObject); private function GetPassword: string; function GetUserName: string; procedure SetUserName(const Value: string); function GetSavePassword: Boolean; function GetLocation: string; procedure SetLocation(const Value: string); { Private declarations } public property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword; property Location: string read GetLocation write SetLocation; property SavePassword: Boolean read GetSavePassword; end; implementation {$R *.dfm} { TLoginForm } function TLoginForm.GetLocation: string; begin Result := LocationEdit.Text; end; function TLoginForm.GetPassword: string; begin Result := MD5Print(MD5String(PasswordEdit.Text)); end; function TLoginForm.GetSavePassword: Boolean; begin Result := SavePasswordCheck.Checked; end; function TLoginForm.GetUserName: string; begin Result := UserNameEdit.Text; end; procedure TLoginForm.SetLocation(const Value: string); begin LocationEdit.Text := Value; end; procedure TLoginForm.SetUserName(const Value: string); begin UserNameEdit.Text := Value; end; procedure TLoginForm.LocationHelpClick(Sender: TObject); begin MessageDlg('Door een lokatie op te geven is het mogelijk op verschillende ' +#13+#10+'lokaties verschillende instellingen te hebben. Zo kun je ' +#13+#10+'bijvoorbeeld ''Thuis'' en ''Werk'' gebruiken om op je werk al ' +#13+#10+'berichten te verwijderen en deze thuis weer opnieuw op te ' +#13+#10+'halen.' +#13+#10+''+#13+#10+ 'Als je dat juist niet wilt laat je de lokatie leeg (of vul je dezelfde ' +#13+#10+'lokatie in).', mtInformation, [mbOK], 0); end; end.
unit UIWrapper_StageGridListUnit; interface uses FMX.TabControl, SearchResult, DataFileSaver, Data.DB; const DBMS_NAME: array[0..1] of String = ( 'MS-SQL', 'Fire Bird' ); type TUIWrapper_StageGridList = class(TObject) private FTabCtrl: TTabControl; FSearchResult: IDataSetIterator; protected procedure InitChildTab(arrNames: array of String); public constructor Create(tabCtrl: TTabControl); destructor Destroy; override; procedure SetSearchResult(schResult: IDataSetIterator); function GetSeachResult: IDataSetIterator; function Count: Integer; function GetActiveTabIndex: Integer; procedure Clear; end; implementation uses FMX.TreeView, FMX.Types, UIWrapper_StageGridUnit, System.SysUtils; { TEvent_TabControl_DBList } procedure TUIWrapper_StageGridList.Clear; begin while FTabCtrl.TabCount > 0 do begin FTabCtrl.Tabs[ 0 ].Free; end; if FSearchResult <> nil then begin FSearchResult._Release; FSearchResult := nil; end; end; function TUIWrapper_StageGridList.Count: Integer; begin if FSearchResult <> nil then result := FSearchResult.Count else result := 0; end; constructor TUIWrapper_StageGridList.Create(tabCtrl: TTabControl); begin FTabCtrl := tabCtrl; //tabCtrl.Tab //InitChildTab( DBMS_NAME ); end; destructor TUIWrapper_StageGridList.Destroy; begin Clear; end; function TUIWrapper_StageGridList.GetActiveTabIndex: Integer; begin result := FTabCtrl.TabIndex; end; function TUIWrapper_StageGridList.GetSeachResult: IDataSetIterator; begin result := FSearchResult; end; procedure TUIWrapper_StageGridList.InitChildTab(arrNames: array of String); var i: Integer; tabItem: TTabItem; treeView: TTreeView; begin for i := 0 to High( arrNames ) do begin tabItem := TTabItem.Create( FTabCtrl ); tabItem.Text := arrNames[ i ]; FTabCtrl.AddObject( tabItem ); treeView := TTreeView.Create( tabItem ); tabItem.AddObject( treeView ); treeView.Align := TAlignLayout.alClient; treeView.AlternatingRowBackground := true; end; end; procedure TUIWrapper_StageGridList.SetSearchResult( schResult: IDataSetIterator); var item: TUIWrapper_StageGrid; i: Integer; begin Clear; while schResult.MoveNext = true do begin item := TUIWrapper_StageGrid.Create( nil ); item.SetTitle( schResult.CurName ); item.SetData( schResult.CurData ); FTabCtrl.AddObject( item ); end; schResult.MoveFirst; FSearchResult := schResult; for i := 0 to FTabCtrl.TabCount - 1 do begin ( FTabCtrl.Tabs[ i ] as TUIWrapper_StageGrid ).AutoColumnSize; end; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clSimpleHttpServer; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils,{$IFDEF DEMO} Windows, Forms, clEncoder, clEncryptor, clCertificate, clHtmlParser,{$ENDIF} {$ELSE} System.Classes, System.SysUtils,{$IFDEF DEMO} Winapi.Windows, Vcl.Forms, clEncoder, clEncryptor, clCertificate, clHtmlParser,{$ENDIF} {$ENDIF} clSocket, clSocketUtils, clHttpRequest, clHttpHeader, clHttpUtils, clUtils, clWUtils, clTranslator; type EclSimpleHttpServerError = class(EclSocketError); TclSimpleHttpServer = class(TComponent) private FConnection: TclTcpServerConnection; FListenConnection: TclTcpListenConnection; FRequestMethod: string; FResponseVersion: TclHttpVersion; FRequestHeader: TclHttpRequestHeader; FResponseHeader: TclHttpResponseHeader; FPort: Integer; FRequestUri: string; FRequestCookies: TStrings; FResponseCookies: TStrings; FServerName: string; FOnProgress: TclProgressEvent; FRequestVersion: TclHttpVersion; FKeepConnection: Boolean; FCharSet: string; function GetActive: Boolean; procedure SetResponseCookies(const Value: TStrings); procedure SetResponseHeader(const Value: TclHttpResponseHeader); procedure DoOnProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); function ParseHeader(ARawData: TMemoryStream): Boolean; procedure ParseRequestLine(const ARequestLine: string); procedure ParseCookies(ARequestHeader: TStrings); function BuildStatusLine(AStatusCode: Integer; const AStatusText: string): string; function BuildKeepConnection: string; function GetBatchSize: Integer; function GetLocalBinding: string; procedure SetBatchSize(const Value: Integer); procedure SetLocalBinding(const Value: string); function GetSessionTimeOut: Integer; procedure SetSessionTimeOut(const Value: Integer); protected procedure AssignNetworkStream(AConnection: TclTcpServerConnection); virtual; procedure DoProgress(ABytesProceed, ATotalBytes: Int64); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Listen(APort: Integer): Integer; overload; function Listen(APortBegin, APortEnd: Integer): Integer; overload; procedure AcceptRequest(ARequest: TclHttpRequest); overload; procedure AcceptRequest(ARequestBody: TStream); overload; procedure AcceptRequest(ARequestBody: TStrings); overload; function AcceptRequest: string; overload; procedure SendResponse(AStatusCode: Integer; const AStatusText: string; ABody: TStream); overload; procedure SendResponse(AStatusCode: Integer; const AStatusText: string; ABody: TStrings); overload; procedure SendResponse(AStatusCode: Integer; const AStatusText: string; const ABody: string); overload; procedure Close; procedure Clear; virtual; property RequestVersion: TclHttpVersion read FRequestVersion; property RequestMethod: string read FRequestMethod; property RequestUri: string read FRequestUri; property RequestHeader: TclHttpRequestHeader read FRequestHeader; property RequestCookies: TStrings read FRequestCookies; property Active: Boolean read GetActive; property Connection: TclTcpServerConnection read FConnection; property Port: Integer read FPort; published property ResponseVersion: TclHttpVersion read FResponseVersion write FResponseVersion default hvHttp1_1; property ResponseHeader: TclHttpResponseHeader read FResponseHeader write SetResponseHeader; property ResponseCookies: TStrings read FResponseCookies write SetResponseCookies; property KeepConnection: Boolean read FKeepConnection write FKeepConnection default True; property ServerName: string read FServerName write FServerName; property LocalBinding: string read GetLocalBinding write SetLocalBinding; property SessionTimeOut: Integer read GetSessionTimeOut write SetSessionTimeOut default 600000; property BatchSize: Integer read GetBatchSize write SetBatchSize default 8192; property CharSet: string read FCharSet write FCharSet; property OnProgress: TclProgressEvent read FOnProgress write FOnProgress; end; resourcestring InvalidHTTPRequestFormat = 'Invalid HTTP request format'; const InvalidHTTPRequestFormatCode = -100; implementation const cHttpVersion: array[TclHttpVersion] of string = ('HTTP/1.0', 'HTTP/1.1'); { TclSimpleHttpServer } function TclSimpleHttpServer.AcceptRequest: string; var stream: TStream; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} stream := TMemoryStream.Create(); try AcceptRequest(stream); if (stream.Size > 0) then begin stream.Position := 0; SetLength(buffer, stream.Size); stream.Read(buffer[0], stream.Size); Result := TclTranslator.GetString(buffer, 0, Length(buffer), CharSet); end else begin Result := ''; end; finally stream.Free(); end; end; procedure TclSimpleHttpServer.AssignNetworkStream(AConnection: TclTcpServerConnection); begin AConnection.NetworkStream := TclNetworkStream.Create(); end; procedure TclSimpleHttpServer.AcceptRequest(ARequestBody: TStrings); var stream: TStream; begin stream := TMemoryStream.Create(); try AcceptRequest(stream); stream.Position := 0; TclStringsUtils.LoadStrings(stream, ARequestBody, CharSet); finally stream.Free(); end; end; procedure TclSimpleHttpServer.AcceptRequest(ARequest: TclHttpRequest); var stream: TStream; begin stream := TMemoryStream.Create(); try AcceptRequest(stream); stream.Position := 0; ARequest.Header := RequestHeader; ARequest.RequestStream := stream; finally stream.Free(); end; end; procedure TclSimpleHttpServer.ParseRequestLine(const ARequestLine: string); var s: string; begin if (WordCount(ARequestLine, [' ']) <> 3) then begin raise EclSimpleHttpServerError.Create(InvalidHTTPRequestFormat, InvalidHTTPRequestFormatCode); end; FRequestMethod := ExtractWord(1, ARequestLine, [' ']); FRequestUri := ExtractWord(2, ARequestLine, [' ']); s := ExtractWord(3, ARequestLine, [' ']); if (cHttpVersion[hvHttp1_1] = s) then begin FRequestVersion := hvHttp1_1; end else begin FRequestVersion := hvHttp1_0; end; end; procedure TclSimpleHttpServer.ParseCookies(ARequestHeader: TStrings); var i: Integer; begin RequestCookies.Clear(); for i := 0 to ARequestHeader.Count - 1 do begin if (system.Pos('Cookie', ARequestHeader[i]) = 1) then begin RequestCookies.Add(ARequestHeader[i]); end; end; end; function TclSimpleHttpServer.ParseHeader(ARawData: TMemoryStream): Boolean; procedure LoadTextFromStream(AStream: TStream; ACount: Integer; AList: TStrings); var buf: TclByteArray; begin SetLength(buf, ACount); AStream.Read(buf[0], Length(buf)); AList.Text := TclTranslator.GetString(buf, CharSet); end; const EndOfHeader = #13#10#13#10; EndOfHeader2 = #10#10; var ind, eofLength: Integer; head: TStrings; begin ind := GetBinTextPos(EndOfHeader, ARawData.Memory, 0, ARawData.Size); eofLength := Length(EndOfHeader); if (ind < 0) then begin ind := GetBinTextPos(EndOfHeader2, ARawData.Memory, 0, ARawData.Size); eofLength := Length(EndOfHeader2); end; Result := (ind > 0); if not Result then Exit; head := TStringList.Create(); try LoadTextFromStream(ARawData, ind + eofLength, head); if (head.Count > 0) then begin ParseRequestLine(head[0]); head.Delete(0); end; RequestHeader.ParseHeader(head); ParseCookies(head); finally head.Free(); end; end; procedure TclSimpleHttpServer.AcceptRequest(ARequestBody: TStream); var stream: TMemoryStream; cnt: Int64; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} IsHttpRequestDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} Clear(); Listen(FPort); if (not Active) then begin FListenConnection.Accept(Connection); end; stream := TMemoryStream.Create(); try repeat stream.Seek(0, soEnd); Connection.ReadData(stream); stream.Seek(0, soBeginning); until ParseHeader(stream); cnt := stream.Size - stream.Position; if (cnt > 0) then begin ARequestBody.CopyFrom(stream, cnt); end; cnt := StrToInt64Def(RequestHeader.ContentLength, 0); while (ARequestBody.Size < cnt) do begin Connection.ReadData(ARequestBody); end; finally stream.Free(); end; end; procedure TclSimpleHttpServer.Clear; begin FRequestVersion := hvHttp1_0; FRequestMethod := ''; FRequestUri := ''; FRequestHeader.Clear(); FRequestCookies.Clear(); end; procedure TclSimpleHttpServer.Close; begin FListenConnection.Abort(); FListenConnection.Close(False); FConnection.Abort(); FConnection.Close(True); end; constructor TclSimpleHttpServer.Create(AOwner: TComponent); begin inherited Create(AOwner); StartupSocket(); FListenConnection := TclTcpListenConnection.Create(); FListenConnection.NetworkStream := TclNetworkStream.Create(); FListenConnection.TimeOut := -1; FConnection := TclTcpServerConnection.Create(); FConnection.OnProgress := DoOnProgress; AssignNetworkStream(FConnection); FRequestHeader := TclHttpRequestHeader.Create(); FRequestCookies := TStringList.Create(); FResponseHeader := TclHttpResponseHeader.Create(); FResponseCookies := TStringList.Create(); FResponseVersion := hvHttp1_1; FKeepConnection := True; SessionTimeOut := 600000; BatchSize := 8192; FServerName := 'Clever Internet Suite HTTP service'; FCharSet := ''; end; destructor TclSimpleHttpServer.Destroy; begin FResponseCookies.Free(); FResponseHeader.Free(); FRequestCookies.Free(); FRequestHeader.Free(); FConnection.Free(); FListenConnection.Free(); CleanupSocket(); inherited Destroy(); end; procedure TclSimpleHttpServer.DoOnProgress(Sender: TObject; ABytesProceed, ATotalBytes: Int64); begin DoProgress(ABytesProceed, ATotalBytes); end; procedure TclSimpleHttpServer.DoProgress(ABytesProceed, ATotalBytes: Int64); begin if Assigned(OnProgress) then begin OnProgress(Self, ABytesProceed, ATotalBytes); end; end; function TclSimpleHttpServer.GetActive: Boolean; begin Result := Connection.Active; end; function TclSimpleHttpServer.GetBatchSize: Integer; begin Result := Connection.BatchSize; end; function TclSimpleHttpServer.GetLocalBinding: string; begin Result := Connection.LocalBinding; end; function TclSimpleHttpServer.GetSessionTimeOut: Integer; begin Result := Connection.TimeOut; end; function TclSimpleHttpServer.Listen(APortBegin, APortEnd: Integer): Integer; begin if (FListenConnection.Active) then begin Result := FPort; Exit; end; FPort := FListenConnection.Listen(APortBegin, APortEnd); Result := FPort; end; function TclSimpleHttpServer.Listen(APort: Integer): Integer; begin if (FListenConnection.Active) then begin Result := FPort; Exit; end; FPort := FListenConnection.Listen(APort); Result := FPort; end; procedure TclSimpleHttpServer.SendResponse(AStatusCode: Integer; const AStatusText: string; ABody: TStrings); var stream: TStream; begin stream := TMemoryStream.Create(); try TclStringsUtils.SaveStrings(ABody, stream, CharSet); stream.Position := 0; SendResponse(AStatusCode, AStatusText, stream); finally stream.Free(); end; end; procedure TclSimpleHttpServer.SendResponse(AStatusCode: Integer; const AStatusText, ABody: string); var stream: TStream; buffer: TclByteArray; begin {$IFNDEF DELPHI2005}buffer := nil;{$ENDIF} stream := TMemoryStream.Create(); try if (ABody <> '') then begin buffer := TclTranslator.GetBytes(ABody, CharSet); stream.WriteBuffer(buffer[0], Length(buffer)); stream.Position := 0; end; SendResponse(AStatusCode, AStatusText, stream); finally stream.Free(); end; end; function TclSimpleHttpServer.BuildStatusLine(AStatusCode: Integer; const AStatusText: string): string; begin Result := cHttpVersion[ResponseVersion] + ' ' + IntToStr(AStatusCode) + ' ' + AStatusText; end; function TclSimpleHttpServer.BuildKeepConnection: string; begin Result := ''; case ResponseVersion of hvHttp1_0: begin if (KeepConnection) then begin Result := 'Keep-Alive'; end; end; hvHttp1_1: begin if (not KeepConnection) then begin Result := 'close'; end; end; end; end; procedure TclSimpleHttpServer.SendResponse(AStatusCode: Integer; const AStatusText: string; ABody: TStream); var head: TStrings; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} IsHttpRequestDemoDisplayed := True; IsEncoderDemoDisplayed := True; IsEncryptorDemoDisplayed := True; IsCertDemoDisplayed := True; IsHtmlDemoDisplayed := True; {$ENDIF} end; {$ENDIF} head := TStringList.Create(); try head.Add(BuildStatusLine(AStatusCode, AStatusText)); ResponseHeader.ContentLength := IntToStr(ABody.Size); ResponseHeader.Connection := BuildKeepConnection(); ResponseHeader.Server := ServerName; ResponseHeader.AssignHeader(head); head.AddStrings(ResponseCookies); head.Add(''); Connection.WriteString(head.Text, 'us-ascii'); Connection.WriteData(ABody); if (not KeepConnection) then begin Connection.Abort(); Connection.Close(True); end; finally head.Free(); end; end; procedure TclSimpleHttpServer.SetBatchSize(const Value: Integer); begin Connection.BatchSize := Value; end; procedure TclSimpleHttpServer.SetLocalBinding(const Value: string); begin Connection.LocalBinding := Value; end; procedure TclSimpleHttpServer.SetResponseCookies(const Value: TStrings); begin FResponseCookies.Assign(Value); end; procedure TclSimpleHttpServer.SetResponseHeader(const Value: TclHttpResponseHeader); begin FResponseHeader.Assign(Value); end; procedure TclSimpleHttpServer.SetSessionTimeOut(const Value: Integer); begin Connection.TimeOut := Value; 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.2 1/25/2004 2:17:52 PM JPMugaas Should work better. Removed one GPF in S/Key. Rev 1.1 1/21/2004 4:03:16 PM JPMugaas InitComponent Rev 1.0 11/13/2002 08:00:30 AM JPMugaas Basic LOGIN mechanism like SMTP uses it. This is not really specified in a RFC - at least I couldn't find one. This is of type TIdSASLUserPass because it needs a username/password } unit IdSASLLogin; interface {$i IdCompilerDefines.inc} uses IdSASL, IdSASLUserPass; type TIdSASLLogin = class(TIdSASLUserPass) protected procedure InitComponent; override; public class function ServiceName: TIdSASLServiceName; override; function StartAuthenticate(const AChallenge, AHost, AProtocolName : string) : String; override; function ContinueAuthenticate(const ALastResponse, AHost, AProtocolName : String): String; override; end; implementation uses IdUserPassProvider, IdBaseComponent; { TIdSASLLogin } function TIdSASLLogin.StartAuthenticate(const AChallenge, AHost, AProtocolName: string): String; begin Result := GetUsername; end; function TIdSASLLogin.ContinueAuthenticate(const ALastResponse, AHost, AProtocolName: String): String; begin Result := GetPassword; end; procedure TIdSASLLogin.InitComponent; begin inherited InitComponent; FSecurityLevel := 200; end; class function TIdSASLLogin.ServiceName: TIdSASLServiceName; begin Result := 'LOGIN'; {Do not translate} end; end.
{*********************************************************} {* VPEDFMTLST.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} {$I Vp.INC} unit VpEdFmtLst; interface uses {$IFDEF LCL} LMessages,LCLProc,LCLType,LCLIntf, {$ELSE} Windows, {$ENDIF} Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, TypInfo, ExtCtrls, VpPrtFmt, VpBase, VpBaseDS, VpDBDS,{ VpBDEDS,} VpPrtPrv, Buttons, VpException, VpSR; const BaseCaption = 'Print Format Designer'; FileCaption = BaseCaption + ' - %s'; UnnamedFile = '<Unnamed>'; type TfrmPrnFormat = class(TForm) btnDeleteElement: TButton; btnDeleteFormat: TButton; btnEditElement: TButton; btnEditFormat: TButton; btnLoadFile: TButton; btnMoveElementDn: TSpeedButton; btnMoveElementUp: TSpeedButton; btnNewElement: TButton; btnNewFile: TButton; btnNewFormat: TButton; btnSaveFile: TButton; Label1: TLabel; Label2: TLabel; lbElements: TListBox; lbFormats: TListBox; OpenDialog1: TOpenDialog; Panel1: TPanel; Panel2: TPanel; PrintPreview: TVpPrintPreview; SaveDialog1: TSaveDialog; btnOk: TButton; Label3: TLabel; procedure btnDeleteElementClick(Sender: TObject); procedure btnDeleteFormatClick(Sender: TObject); procedure btnEditElementClick(Sender: TObject); procedure btnEditFormatClick(Sender: TObject); procedure btnLoadFileClick(Sender: TObject); procedure btnMoveElementDnClick(Sender: TObject); procedure btnMoveElementUpClick(Sender: TObject); procedure btnNewElementClick(Sender: TObject); procedure btnNewFileClick(Sender: TObject); procedure btnNewFormatClick(Sender: TObject); procedure btnSaveFileClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure lbElementsClick(Sender: TObject); procedure lbFormatsClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbElementsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure lbElementsDragDrop(Sender, Source: TObject; X, Y: Integer); procedure lbElementsDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); private FFormatFileName : string; FControlLink : TVpControlLink; IsDirty : Boolean; LastX, LastY: Integer; DragItem : Integer; protected function DirtyPrompt: Integer; procedure DoEditElement; procedure DoEditFormat; procedure DoNewElement; procedure DoNewFile; function DoNewFormat : Integer; procedure DoSave; procedure EnableElementButtons(Enable: Boolean); procedure EnableFormatButtons(Enable: Boolean); procedure EnableMoveButtons; procedure SetFormatFileName (const v : string); procedure UpdateFormats; procedure UpdateCaption; procedure UpdatePreview; function GetControlLink: TVpControlLink; procedure SetControlLink(const Value: TVpControlLink); { Private declarations } public property ControlLink : TVpControlLink read FControlLink write SetControlLink; function Execute : Boolean; { Public declarations } published property FormatFileName : string read FFormatFileName write SetFormatFileName; end; var frmPrnFormat: TfrmPrnFormat; implementation uses VpEdFmt, VpEdElem; {$IFNDEF LCL} {$R *.DFM} {$ENDIF} {TfrmPrnFormat} procedure TfrmPrnFormat.FormCreate(Sender: TObject); begin OpenDialog1.InitialDir := ExtractFilePath(Application.ExeName); SaveDialog1.InitialDir := ExtractFilePath(Application.ExeName); IsDirty := False; FormatFileName := UnnamedFile; EnableFormatButtons(False); EnableElementButtons(False); end; {=====} procedure TfrmPrnFormat.EnableMoveButtons; begin btnMoveElementUp.Enabled := lbElements.ItemIndex > 0; btnMoveElementDn.Enabled := lbElements.ItemIndex < lbElements.Items.Count - 1; end; {=====} procedure TfrmPrnFormat.FormShow(Sender: TObject); begin PrintPreview.Parent := Panel1; if ControlLink.Printer.PrintFormats.Count > 0 then begin UpdateFormats; end else begin DoNewFile; UpdateCaption; end; btnNewFormat.Enabled := True; lbFormats.SetFocus; end; {=====} procedure TfrmPrnFormat.btnDeleteElementClick(Sender: TObject); var Format : TVpPrintFormatItem; Idx : Integer; Item : string; begin Format := TVpPrintFormatItem(lbFormats.Items.Objects[lbFormats.ItemIndex]); Item := ''; if lbElements.ItemIndex > -1 then Item := lbElements.Items[lbElements.ItemIndex]; if Item <> '' then begin for Idx := Pred(Format.Elements.Count) downto 0 do begin if Format.Elements.Items[Idx].ElementName = Item then begin Format.Elements.Items[Idx].Free; lbElements.Items.Delete(lbElements.ItemIndex); IsDirty := True; UpdatePreview; end; end; end; end; {=====} procedure TfrmPrnFormat.btnDeleteFormatClick(Sender: TObject); var Prn : TVpPrinter; Idx : Integer; begin Prn := ControlLink.Printer; Idx := Prn.Find(lbFormats.Items[lbFormats.ItemIndex]); if (Idx < 0) or (Idx >= Prn.PrintFormats.Count) then ShowMessage ('Invalid print format: ' + lbFormats.Items[lbFormats.ItemIndex]); Prn.PrintFormats.Items[Idx].Free; lbFormats.Items.Delete(lbFormats.ItemIndex); IsDirty := True; UpdatePreview; end; {=====} procedure TfrmPrnFormat.btnEditElementClick(Sender: TObject); begin DoEditElement; end; {=====} procedure TfrmPrnFormat.btnEditFormatClick(Sender: TObject); begin DoEditFormat; end; {=====} procedure TfrmPrnFormat.btnLoadFileClick(Sender: TObject); var Prn : TVpPrinter; Rslt : Integer; begin if IsDirty then begin Rslt := DirtyPrompt; { case Rslt of ID_YES: begin DoSave; end; ID_NO: begin // nothing end; ID_CANCEL: Exit; end;} end; if OpenDialog1.Execute then begin FormatFileName := OpenDialog1.FileName; lbFormats.Items.Clear; Prn := ControlLink.Printer; Prn.LoadFromFile(FormatFileName, False); UpdateFormats; UpdateCaption; end; end; {=====} procedure TfrmPrnFormat.btnMoveElementDnClick(Sender: TObject); var E : TVpPrintFormatElementItem; begin if lbElements.ItemIndex > -1 then begin E := TVpPrintFormatElementItem(lbElements.Items.Objects[lbElements.ItemIndex]); E.Index := E.Index + 1; lbElements.Items.Move(lbElements.ItemIndex, lbElements.ItemIndex + 1); end; end; {=====} procedure TfrmPrnFormat.btnMoveElementUpClick(Sender: TObject); var E : TVpPrintFormatElementItem; begin if lbElements.ItemIndex > -1 then begin E := TVpPrintFormatElementItem(lbElements.Items.Objects[lbElements.ItemIndex]); E.Index := E.Index - 1; lbElements.Items.Move(lbElements.ItemIndex, lbElements.ItemIndex - 1); end; end; {=====} procedure TfrmPrnFormat.btnNewElementClick(Sender: TObject); begin DoNewElement; end; {=====} procedure TfrmPrnFormat.btnNewFormatClick(Sender: TObject); var NewFormatIdx : Integer; i : Integer; begin NewFormatIdx := DoNewFormat; if (NewFormatIdx > 0) and (Assigned (ControlLink)) and (NewFormatIdx < ControlLink.Printer.PrintFormats.Count) then for i := 0 to lbFormats.Items.Count - 1 do if lbFormats.Items[i] = ControlLink.Printer.PrintFormats. Items[NewFormatIdx].FormatName then begin lbFormats.ItemIndex := i; lbFormatsClick (Self); Break; end; end; {=====} procedure TfrmPrnFormat.btnNewFileClick(Sender: TObject); var Rslt : Integer; begin if IsDirty then begin Rslt := DirtyPrompt; { case Rslt of ID_YES: begin DoSave; DoNewFile; end; ID_NO: begin DoNewFile; end; ID_CANCEL: Exit; end;} end else DoNewFile; end; {=====} procedure TfrmPrnFormat.btnOkClick(Sender: TObject); begin ModalResult := mrOk; end; {=====} procedure TfrmPrnFormat.btnSaveFileClick(Sender: TObject); begin DoSave; end; {=====} function TfrmPrnFormat.DirtyPrompt : Integer; begin Result := Application.MessageBox( PChar('Save changes to ' + FormatFileName + '?'), PChar('Inquiry'), MB_YESNOCANCEL or MB_ICONQUESTION); end; {=====} procedure TfrmPrnFormat.DoEditElement; var E : TVpPrintFormatElementItem; frmEditElement: TfrmEditElement; begin if lbElements.ItemIndex > -1 then begin Application.CreateForm(TfrmEditElement, frmEditElement); E := TVpPrintFormatElementItem(lbElements.Items.Objects[lbElements.ItemIndex]); if frmEditElement.Execute(E) then begin IsDirty := True; end; frmEditElement.Free; UpdatePreview; end else begin DoNewElement; end; end; {=====} procedure TfrmPrnFormat.DoEditFormat; var AFormat : TVpPrintFormatItem; frmEditFormat: TfrmEditFormat; begin if lbFormats.ItemIndex > -1 then begin Application.CreateForm(TfrmEditFormat, frmEditFormat); AFormat := TVpPrintFormatItem(lbFormats.Items.Objects[lbFormats.ItemIndex]); if frmEditFormat.Execute(AFormat) then begin IsDirty := True; end; frmEditFormat.Free; UpdatePreview; end else begin DoNewFormat; end; end; {=====} procedure TfrmPrnFormat.DoNewElement; var Format : TVpPrintFormatItem; E : TVpPrintFormatElementItem; Unique, Cancelled : Boolean; frmEditElement: TfrmEditElement; begin Format := TVpPrintFormatItem(lbFormats.Items.Objects[lbFormats.ItemIndex]); Unique := False; Application.CreateForm(TfrmEditElement, frmEditElement); repeat E := TVpPrintFormatElementItem.Create(Format.Elements); { edit Element } Cancelled := not frmEditElement.Execute(E); if not Cancelled then begin if lbElements.Items.IndexOf(E.ElementName) > -1 then begin ShowMessage('An Element named ' + E.ElementName + ' already exists.' + #13#10 + 'Please use another name.'); { dump empty element } Format.Elements.Items[E.Index].Free; Unique := False; end else begin lbElements.Items.AddObject(E.ElementName, E); lbElements.ItemIndex := E.Index; IsDirty := True; Unique := True; UpdatePreview; end; end else { dump empty element } Format.Elements.Items[E.Index].Free; { until element name is Unique or operation Cancelled } until Unique or Cancelled; frmEditElement.Free; end; {=====} procedure TfrmPrnFormat.DoNewFile; var Prn : TVpPrinter; begin Prn := ControlLink.Printer; Prn.PrintFormats.Clear; lbFormats.Clear; lbElements.Clear; FormatFileName := UnnamedFile; IsDirty := False; PrintPreview.ControlLink := nil; EnableFormatButtons(False); btnNewFormat.Enabled := True; EnableElementButtons(False); end; {=====} function TfrmPrnFormat.DoNewFormat : Integer; var AFormat : TVpPrintFormatItem; Prn : TVpPrinter; Unique, Cancelled : Boolean; frmEditFormat: TfrmEditFormat; begin Result := -1; Application.CreateForm(TfrmEditFormat, frmEditFormat); Prn := ControlLink.Printer; Unique := False; repeat AFormat := TVpPrintFormatItem.Create(Prn.PrintFormats); { edit format } Cancelled := not frmEditFormat.Execute(AFormat); if not Cancelled then begin if lbFormats.Items.IndexOf(AFormat.FormatName) > -1 then begin ShowMessage('A format named ' + AFormat.FormatName + ' already exists.' + #13#10 + 'Please use another name.'); { dump empty format } Prn.PrintFormats.Items[AFormat.Index].Free; Unique := False; end else begin lbFormats.Items.AddObject(AFormat.FormatName, AFormat); lbFormats.ItemIndex := AFormat.Index; UpdatePreview; IsDirty := True; Unique := True; end; end else { dump empty format } Prn.PrintFormats.Items[AFormat.Index].Free; { until format name is Unique or operation Cancelled } until Unique or Cancelled; if not Cancelled then Result := AFormat.Index; frmEditFormat.Free; end; {=====} procedure TfrmPrnFormat.DoSave; begin if FormatFileName <> UnnamedFile then SaveDialog1.FileName := FormatFileName else SaveDialog1.FileName := 'Unnamed.xml'; if SaveDialog1.Execute then begin FormatFileName := SaveDialog1.FileName; ControlLink.Printer.SaveToFile(FormatFileName); IsDirty := False; UpdateCaption; end; end; {=====} procedure TfrmPrnFormat.EnableElementButtons(Enable : Boolean); begin btnNewElement.Enabled := Enable; btnEditElement.Enabled := Enable; btnDeleteElement.Enabled := Enable; // btnMoveElementUp.Enabled := Enable; // btnMoveElementDn.Enabled := Enable; EnableMoveButtons; end; {=====} procedure TfrmPrnFormat.EnableFormatButtons(Enable : Boolean); begin btnNewFormat.Enabled := Enable; btnEditFormat.Enabled := Enable; btnDeleteFormat.Enabled := Enable; end; {=====} function TfrmPrnFormat.Execute : Boolean; begin if not Assigned (ControlLink) then raise EVpPrintFormatEditorError.Create (RSNoControlLink); Result := ShowModal = mrOk; end; {=====} procedure TfrmPrnFormat.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var Rslt : Integer; begin if IsDirty then begin Rslt := DirtyPrompt; { case Rslt of ID_YES: begin DoSave; CanClose := True; end; ID_NO: begin CanClose := True; end; ID_CANCEL: begin CanClose := False; Exit; end; end; } end else CanClose := True; end; {=====} function TfrmPrnFormat.GetControlLink: TVpControlLink; begin Result := FControlLink; end; {=====} procedure TfrmPrnFormat.lbFormatsClick(Sender: TObject); var E : TVpPrintFormatElementItem; Prn : TVpPrinter; i, Idx : Integer; begin lbElements.Items.Clear; Prn := ControlLink.Printer; Idx := Prn.Find(lbFormats.Items[lbFormats.ItemIndex]); Prn.CurFormat := Idx; PrintPreview.ControlLink := ControlLink; for i := 0 to Pred(Prn.PrintFormats.Items[Idx].Elements.Count) do begin E := Prn.PrintFormats.Items[Idx].Elements.Items[i]; lbElements.Items.AddObject(E.ElementName, E); end; UpdatePreview; EnableElementButtons(False); btnNewElement.Enabled := True; EnableFormatButtons(True); EnableMoveButtons; end; {=====} procedure TfrmPrnFormat.lbElementsClick(Sender: TObject); begin EnableElementButtons(True); end; {=====} procedure TfrmPrnFormat.lbElementsMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin LastX:=X; LastY:=Y; DragItem := (Sender as TListBox).ItemAtPos(Point(LastX, LastY),True); end; {=====} procedure TfrmPrnFormat.lbElementsDragDrop(Sender, Source: TObject; X, Y: Integer); var lb : TListBox; Dest: Integer; E : TVpPrintFormatElementItem; begin lb := Source as TListBox; Dest:=lb.ItemAtPos(Point(X, Y),True); lb.Items.Move(DragItem, Dest); E := TVpPrintFormatElementItem(lbElements.Items.Objects[Dest]); E.Index := Dest; lb.ItemIndex := Dest; EnableMoveButtons; end; {=====} procedure TfrmPrnFormat.lbElementsDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var lb : TListBox; begin lb := (Source as TListBox); lb.Canvas.DrawFocusRect(lb.ItemRect(lb.ItemAtPos(Point(LastX, LastY), True))); lb.Canvas.DrawFocusRect(lb.ItemRect(lb.ItemAtPos(Point(X, Y), True))); LastX := X; LastY := Y; Accept:=True; end; {=====} procedure TfrmPrnFormat.SetControlLink(const Value: TVpControlLink); begin if FControlLink <> Value then begin FControlLink := Value; if Assigned (FControlLink) then FFormatFileName := FControlLink.Printer.DefaultXMLFileName; end; end; {=====} procedure TfrmPrnFormat.SetFormatFileName (const v : string); begin if v <> FFormatFileName then begin FFormatFileName := v; if Assigned (FControlLink) then FControlLink.Printer.DefaultXMLFileName := v; end; end; {=====} procedure TfrmPrnFormat.UpdateCaption; begin Caption := Format(FileCaption, [FormatFileName]); end; {=====} procedure TfrmPrnFormat.UpdateFormats; var i : Integer; Prn : TVpPrinter; begin Prn := ControlLink.Printer; for i := 0 to Pred(Prn.PrintFormats.Count) do lbFormats.Items.AddObject(Prn.PrintFormats.Items[i].FormatName, Prn.PrintFormats.Items[i]); EnableMoveButtons; end; {=====} procedure TfrmPrnFormat.UpdatePreview; var Prn : TVpPrinter; Idx : Integer; begin Prn := ControlLink.Printer; if lbFormats.ItemIndex > -1 then begin Idx := Prn.Find (lbFormats.Items[lbFormats.ItemIndex]); if Idx > - 1 then Prn.CurFormat := Idx; {Prn.CurFormat := lbFormats.ItemIndex; } end; Prn.NotifyLinked; EnableMoveButtons; end; {=====} end.
unit ElScrollBarDemoMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ElXPThemedControl, ElScrollBar, ElImgFrm, StdCtrls, ElSpin, ElVCLUtils, ElBtnCtl, ElStrUtils, ElCheckCtl, ExtCtrls, ElPanel, ElGroupBox, ElClrCmb, ElEdits, ElBtnEdit, ElCombos, ElSBCtrl; type TElScrollBarDemoMainForm = class(TForm) Label1: TLabel; Label2: TLabel; ElScrollBarMinValueSpin: TElSpinEdit; ElScrollBarMaxValueSpin: TElSpinEdit; ElScrollBarShowTrackHintCB: TElCheckBox; ElScrollBarOrientationCombo: TElComboBox; Label3: TLabel; ElScrollBarFlatCB: TElCheckBox; ElScrollBarActiveFlatCB: TElCheckBox; ElScrollBarSecondaryButtonsCombo: TElComboBox; ElScrollbarSecondaryButtonsCB: TElCheckBox; ElScrollBarDrawFramesCB: TElCheckBox; ElScrollbarDrawArrowFramesCB: TElCheckBox; ElScrollBarDrawBarsCB: TElCheckBox; ElScrollBarNoDisableButtonsCB: TElCheckBox; ElScrollBarNoThunkenThumbCB: TElCheckBox; ElScrollBarShowLeftArrowsCB: TElCheckBox; ElScrollBarShowRightArrowsCB: TElCheckBox; ElScrollBarThinFramesCB: TElCheckBox; ElScrollBarManualThumbModeCB: TElCheckBox; ElScrollBarThumbSizeSpin: TElSpinEdit; ElScrollBarUseImageFormCB: TElCheckBox; ElScrollBarImageForm: TElImageForm; SamplePanel: TElPanel; SampleElScrollBar: TElScrollBar; ElScrollBarUseSystemMetricsCB: TElCheckBox; ElScrollBarButtonSizeSpin: TElSpinEdit; Label4: TLabel; ElScrollBarColorsGroupBox: TElGroupBox; Label5: TLabel; ElScrollBarColorCombo: TElColorCombo; ElScrollBarArrowColorCombo: TElColorCombo; Label6: TLabel; Label7: TLabel; ElScrollBarHotArrowColorCombo: TElColorCombo; Label8: TLabel; ElScrollBarBarColorCombo: TElColorCombo; ElScrollBarUseXPThemesCB: TElCheckBox; procedure SampleElScrollBarScrollHintNeeded(Sender: TObject; TrackPosition: Integer; var Hint: TElFString); procedure ElScrollBarShowTrackHintCBClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure ElScrollBarFlatCBClick(Sender: TObject); procedure ElScrollbarSecondaryButtonsCBClick(Sender: TObject); procedure ElScrollBarDrawFramesCBClick(Sender: TObject); procedure ElScrollbarDrawArrowFramesCBClick(Sender: TObject); procedure ElScrollBarNoDisableButtonsCBClick(Sender: TObject); procedure ElScrollBarNoThunkenThumbCBClick(Sender: TObject); procedure ElScrollBarShowLeftArrowsCBClick(Sender: TObject); procedure ElScrollBarDrawBarsCBClick(Sender: TObject); procedure ElScrollBarShowRightArrowsCBClick(Sender: TObject); procedure ElScrollBarActiveFlatCBClick(Sender: TObject); procedure ElScrollBarThinFramesCBClick(Sender: TObject); procedure ElScrollBarMinValueSpinChange(Sender: TObject); procedure ElScrollBarMaxValueSpinChange(Sender: TObject); procedure ElScrollBarManualThumbModeCBClick(Sender: TObject); procedure ElScrollBarThumbSizeSpinChange(Sender: TObject); procedure ElScrollBarUseImageFormCBClick(Sender: TObject); procedure ElScrollBarOrientationComboChange(Sender: TObject); procedure ElScrollBarSecondaryButtonsComboChange(Sender: TObject); procedure ElScrollBarUseSystemMetricsCBClick(Sender: TObject); procedure ElScrollBarColorComboChange(Sender: TObject); procedure ElScrollBarArrowColorComboChange(Sender: TObject); procedure ElScrollBarBarColorComboChange(Sender: TObject); procedure ElScrollBarHotArrowColorComboChange(Sender: TObject); procedure ElScrollBarUseXPThemesCBClick(Sender: TObject); private NotFirstTime : boolean; public { Public declarations } end; var ElScrollBarDemoMainForm: TElScrollBarDemoMainForm; implementation {$R *.DFM} procedure TElScrollBarDemoMainForm.SampleElScrollBarScrollHintNeeded(Sender: TObject; TrackPosition: Integer; var Hint: TElFString); begin Hint := '(custom hint)'#13#10' Position: ' + IntToStr(TrackPosition); end; procedure TElScrollBarDemoMainForm.ElScrollBarShowTrackHintCBClick(Sender: TObject); begin sampleElScrollBar.ShowTrackHint := ElScrollBarShowTrackHintCB.Checked; end; procedure TElScrollBarDemoMainForm.FormActivate(Sender: TObject); begin if not NotFirstTime then begin ElScrollBarOrientationCombo.ItemIndex := 0; ElScrollBarSecondaryButtonsCombo.ItemIndex := 0; end; NotFirstTime := true; end; procedure TElScrollBarDemoMainForm.ElScrollBarFlatCBClick(Sender: TObject); begin sampleElScrollbar.Flat := ElScrollBarFlatCB.Checked; ElScrollBarActiveFlatCB.Enabled := ElScrollBarFlatCB.Checked; ElScrollBarthinFramesCB.Enabled := (not ElScrollBarFlatCB.Checked) and (ElScrollBarDrawFramesCB.Checked); end; procedure TElScrollBarDemoMainForm.ElScrollbarSecondaryButtonsCBClick(Sender: TObject); begin sampleElScrollBar.SecondaryButtons := ElScrollbarSecondaryButtonsCB.Checked; ElScrollbarSecondaryButtonsCombo.Enabled := ElScrollbarSecondaryButtonsCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarDrawFramesCBClick(Sender: TObject); begin SampleElScrollBar.ShowBorder := ElScrollBarDrawFramesCB.Checked; ElScrollBarDrawArrowFramesCB.Checked := SampleElScrollBar.DrawArrowFrames; ElScrollBarFlatCB.Enabled := SampleElScrollBar.ShowBorder; ElScrollBarThinFramesCB.Enabled := (not ElScrollBarFlatCB.Checked) and (ElScrollBarDrawFramesCB.Checked or ElScrollBarDrawArrowFramesCB.Checked); end; procedure TElScrollBarDemoMainForm.ElScrollbarDrawArrowFramesCBClick( Sender: TObject); begin SampleElScrollBar.DrawArrowFrames := ElScrollBarDrawArrowFramesCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarNoDisableButtonsCBClick( Sender: TObject); begin sampleElScrollBar.NoDisableButtons := ElScrollBarNoDisableButtonsCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarNoThunkenThumbCBClick( Sender: TObject); begin SampleElScrollBar.NoSunkenThumb := ElScrollBarNoThunkenThumbCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarShowLeftArrowsCBClick( Sender: TObject); begin sampleElScrollBar.ShowLeftArrows := ElScrollBarShowLeftArrowsCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarDrawBarsCBClick( Sender: TObject); begin sampleElScrollBar.DrawBars := ElScrollBarDrawBarsCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarShowRightArrowsCBClick( Sender: TObject); begin sampleElScrollBar.ShowRightArrows := ElScrollBarShowRightArrowsCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarActiveFlatCBClick( Sender: TObject); begin sampleElScrollBar.ActiveFlat := ElScrollBarActiveFlatCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarThinFramesCBClick( Sender: TObject); begin sampleElScrollBar.ThinFrame := ElScrollBarthinFramesCB.Checked; end; procedure TElScrollBarDemoMainForm.ElScrollBarMinValueSpinChange( Sender: TObject); begin SampleElScrollBar.Min := ElScrollBarMinValueSpin.Value; ElScrollBarMinValueSpin.Value := SampleElScrollBar.Min; end; procedure TElScrollBarDemoMainForm.ElScrollBarMaxValueSpinChange( Sender: TObject); begin SampleElScrollBar.Max := ElScrollBarMaxValueSpin.Value; ElScrollBarMaxValueSpin.Value := SampleElScrollBar.Max; end; procedure TElScrollBarDemoMainForm.ElScrollBarManualThumbModeCBClick( Sender: TObject); begin if ElScrollBarManualThumbModeCB.Checked then begin SampleElScrollBar.ThumbMode := etmFixed; ElScrollBarThumbSizeSpin.Value := SampleElScrollBar.ThumbSize; ElScrollBarThumbSizeSpin.Enabled := true; end else begin SampleElScrollBar.ThumbMode := etmAuto; ElScrollBarThumbSizeSpin.Enabled := false; end; end; procedure TElScrollBarDemoMainForm.ElScrollBarThumbSizeSpinChange( Sender: TObject); begin SampleElScrollBar.ThumbSize := ElScrollBarThumbSizeSpin.Value; end; procedure TElScrollBarDemoMainForm.ElScrollBarUseImageFormCBClick( Sender: TObject); begin if ElScrollBarUseImageFormCB.Checked then begin ElScrollBarImageForm.BackgroundType := bgtTileBitmap; sampleElScrollBar.ImageForm := ElScrollBarImageForm; end else begin sampleElScrollBar.ImageForm := nil; ElScrollBarImageForm.BackgroundType := bgtColorFill; end; end; procedure TElScrollBarDemoMainForm.ElScrollBarOrientationComboChange( Sender: TObject); begin sampleElScrollBar.Kind := TScrollBarKind(ElScrollBarOrientationCombo.ItemIndex); if sampleElScrollBar.Kind = sbHorizontal then samplePanel.SetBounds(4, 4, 121, 21) else samplePanel.SetBounds(4, 4, 21, 121); end; procedure TElScrollBarDemoMainForm.ElScrollBarSecondaryButtonsComboChange( Sender: TObject); begin SampleElScrollBar.SecondBtnKind := TElSecButtonsKind(ElScrollBarSecondaryButtonsCombo.ItemIndex); end; procedure TElScrollBarDemoMainForm.ElScrollBarUseSystemMetricsCBClick( Sender: TObject); begin SampleElScrollBar.UseSystemMetrics := ElScrollBarUseSystemMetricsCB.Checked; ElScrollBarManualThumbModeCB.Enabled := not SampleElScrollBar.UseSystemMetrics; ElScrollBarThumbSizeSpin.Enabled := ElScrollBarManualThumbModeCB.Enabled and ElScrollBarManualThumbModeCB.Checked; label4.Enabled := ElScrollBarThumbSizeSpin.Enabled; end; procedure TElScrollBarDemoMainForm.ElScrollBarColorComboChange(Sender: TObject); begin SampleElScrollBar.Color := ElScrollBarColorCombo.SelectedColor; end; procedure TElScrollBarDemoMainForm.ElScrollBarArrowColorComboChange( Sender: TObject); begin sampleElScrollBar.ArrowColor := ElScrollBarArrowColorCombo.SelectedColor; end; procedure TElScrollBarDemoMainForm.ElScrollBarBarColorComboChange( Sender: TObject); begin sampleElScrollBar.BarColor := ElScrollBarBarColorCombo.SelectedColor; end; procedure TElScrollBarDemoMainForm.ElScrollBarHotArrowColorComboChange(Sender: TObject); begin sampleElScrollBar.ArrowHotTrackColor := ElScrollBarHotArrowColorCombo.SelectedColor; end; procedure TElScrollBarDemoMainForm.ElScrollBarUseXPThemesCBClick( Sender: TObject); begin SampleElScrollBar.UseXPThemes := ElScrollBarUseXPThemesCB.Checked; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1997 Paolo Giacomuzzi } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} (* Version History 12/16/2000 Improved auto-hiding of the auto-hide bars. *) {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElAppBarForm; interface uses Windows, Messages, SysUtils, Classes, Forms, Dialogs, Controls, ExtCtrls, {$ifdef VCL_6_USED} Types, {$endif} ElAppBar, ShellApi, Menus; type // TAppBar class //////////////////////////////////////////////////////////// TElAppBarForm = class(TForm) protected FAppBar : TElAppBar; function GetEdge: TAppBarEdge; procedure SetAlwaysOnTop(bAlwaysOnTop: Boolean); procedure SetAutoHide(bAutoHide: Boolean); procedure SetEdge(abEdge: TAppBarEdge); procedure SetFlags(newValue: TAppBarFlags); procedure SetKeepSize(newValue: Boolean); procedure SetPreventOffScreen(newValue: Boolean); function GetAlwaysOnTop: Boolean; function GetAutoHide: Boolean; function GetAutoHideIsVisible: Boolean; function GetDockDims: TRect; function GetFlags: TAppBarFlags; function GetFloatRect: TRect; function GetHorzSizeInc: LongInt; procedure SetHorzSizeInc(Value: LongInt); function GetKeepSize: Boolean; function GetMaxHeight: LongInt; procedure SetMaxHeight(Value: LongInt); function GetMaxWidth: LongInt; procedure SetMaxWidth(Value: LongInt); function GetMinHeight: LongInt; procedure SetMinHeight(Value: LongInt); function GetMinWidth: LongInt; procedure SetMinWidth(Value: LongInt); function GetOnEdgeChanged: TNotifyEvent; procedure SetOnEdgeChanged(Value: TNotifyEvent); function GetOnForcedToDocked: TNotifyEvent; procedure SetOnForcedToDocked(Value: TNotifyEvent); function GetPreventOffScreen: Boolean; function GetTaskEntry: TElAppBarTaskEntry; procedure SetTaskEntry(Value: TElAppBarTaskEntry); function GetVertSizeInc: LongInt; procedure SetVertSizeInc(Value: LongInt); public constructor Create(AOwner : TComponent); override; procedure SetDockDims(rc: TRect); procedure SetFloatRect(rc: TRect); property AutoHideIsVisible: Boolean read GetAutoHideIsVisible; property DockDims: TRect read GetDockDims write SetDockDims; property FloatRect: TRect read GetFloatRect write SetFloatRect; published property AlwaysOnTop: Boolean read GetAlwaysOnTop write SetAlwaysOnTop; property AutoHide: Boolean read GetAutoHide write SetAutoHide; property Edge: TAppBarEdge read GetEdge write SetEdge; property Flags: TAppBarFlags read GetFlags write SetFlags; property HorzSizeInc: LongInt read GetHorzSizeInc write SetHorzSizeInc; property KeepSize: Boolean read GetKeepSize write SetKeepSize; property MaxHeight: LongInt read GetMaxHeight write SetMaxHeight; property MaxWidth: LongInt read GetMaxWidth write SetMaxWidth; property MinHeight: LongInt read GetMinHeight write SetMinHeight; property MinWidth: LongInt read GetMinWidth write SetMinWidth; property OnEdgeChanged: TNotifyEvent read GetOnEdgeChanged write SetOnEdgeChanged; property OnForcedToDocked: TNotifyEvent read GetOnForcedToDocked write SetOnForcedToDocked; property PreventOffScreen: Boolean read GetPreventOffScreen write SetPreventOffScreen default false; property TaskEntry: TElAppBarTaskEntry read GetTaskEntry write SetTaskEntry; property VertSizeInc: LongInt read GetVertSizeInc write SetVertSizeInc; end; implementation constructor TElAppBarForm.Create(AOwner : TComponent); begin inherited; FAppBar := TElAppBar.Create(Self); end; function TElAppBarForm.GetEdge: TAppBarEdge; begin Result := FAppBar.Edge; end; procedure TElAppBarForm.SetAlwaysOnTop(bAlwaysOnTop: Boolean); begin FAppBar.AlwaysOnTop := bAlwaysOnTop; end; procedure TElAppBarForm.SetAutoHide(bAutoHide: Boolean); begin FAppBar.Autohide := bAutoHide; end; procedure TElAppBarForm.SetDockDims(rc: TRect); begin {$ifdef BUILDER_USED} FAppBar.SetDockDims(rc); {$else} FAppBar.DockDims := rc; {$endif} end; procedure TElAppBarForm.SetEdge(abEdge: TAppBarEdge); begin FAppBar.Edge := abEdge; end; procedure TElAppBarForm.SetFlags(newValue: TAppBarFlags); begin FAppBar.Flags := newValue; end; procedure TElAppBarForm.SetFloatRect(rc: TRect); begin {$ifdef BUILDER_USED} FAppBar.SetFloatRect(rc); {$else} FAppBar.FloatRect := rc; {$endif} end; procedure TElAppBarForm.SetKeepSize(newValue: Boolean); begin FAppBar.KeepSize := newValue; end; procedure TElAppBarForm.SetPreventOffScreen(newValue: Boolean); begin FAppBar.PreventOffScreen := newValue; end; function TElAppBarForm.GetAlwaysOnTop: Boolean; begin Result := FAppBar.AlwaysOnTop; end; function TElAppBarForm.GetAutoHide: Boolean; begin Result := FAppBar.AutoHide; end; function TElAppBarForm.GetAutoHideIsVisible: Boolean; begin Result := FAppBar.AutoHideIsVisible; end; function TElAppBarForm.GetDockDims: TRect; begin {$ifdef BUILDER_USED} FAppBar.GetDockDims(Result); {$else} Result := FAppBar.DockDims; {$endif} end; function TElAppBarForm.GetFlags: TAppBarFlags; begin Result := FAppBar.Flags; end; function TElAppBarForm.GetFloatRect: TRect; begin {$ifdef BUILDER_USED} FAppBar.GetFloatRect(Result); {$else} Result := FAppBar.FloatRect; {$endif} end; function TElAppBarForm.GetHorzSizeInc: LongInt; begin Result := FAppBar.HorzSizeInc; end; procedure TElAppBarForm.SetHorzSizeInc(Value: LongInt); begin FAppBar.HorzSizeInc := Value; end; function TElAppBarForm.GetKeepSize: Boolean; begin Result := FAppBar.KeepSize; end; function TElAppBarForm.GetMaxHeight: LongInt; begin Result := FAppBar.MaxHeight; end; procedure TElAppBarForm.SetMaxHeight(Value: LongInt); begin FAppBar.MaxHeight := Value; end; function TElAppBarForm.GetMaxWidth: LongInt; begin Result := FAppBar.MaxWidth; end; procedure TElAppBarForm.SetMaxWidth(Value: LongInt); begin FAppBar.MaxWidth := Value; end; function TElAppBarForm.GetMinHeight: LongInt; begin Result := FAppBar.MinHeight; end; procedure TElAppBarForm.SetMinHeight(Value: LongInt); begin FAppBar.MinHeight := Value; end; function TElAppBarForm.GetMinWidth: LongInt; begin Result :=FAppBar.MinWidth; end; procedure TElAppBarForm.SetMinWidth(Value: LongInt); begin FAppBar.MinWidth := Value; end; function TElAppBarForm.GetOnEdgeChanged: TNotifyEvent; begin Result :=FAppBar.OnEdgeChanged; end; procedure TElAppBarForm.SetOnEdgeChanged(Value: TNotifyEvent); begin FAppBar.OnEdgeChanged := Value; end; function TElAppBarForm.GetOnForcedToDocked: TNotifyEvent; begin Result :=FAppBar.OnForcedToDocked; end; procedure TElAppBarForm.SetOnForcedToDocked(Value: TNotifyEvent); begin FAppBar.OnForcedToDocked := Value; end; function TElAppBarForm.GetPreventOffScreen: Boolean; begin Result :=FAppBar.PreventOffScreen; end; function TElAppBarForm.GetTaskEntry: TElAppBarTaskEntry; begin Result :=FAppBar.TaskEntry; end; procedure TElAppBarForm.SetTaskEntry(Value: TElAppBarTaskEntry); begin FAppBar.TaskEntry := Value; end; function TElAppBarForm.GetVertSizeInc: LongInt; begin Result :=FAppBar.VertSizeInc; end; procedure TElAppBarForm.SetVertSizeInc(Value: LongInt); begin FAppBar.VertSizeInc := Value; end; end.
PROGRAM ProcedureTest(INPUT, OUTPUT); {Тест процедуры ReadDigit} PROCEDURE ReadDigit(VAR F: TEXT; VAR D: INTEGER); {В D возвращается цифра, соответствующая цифре-символу, прочтённому из F} VAR Ch: CHAR; BEGIN {ReadDigit} D := -1; IF NOT EOLN THEN BEGIN READ(F, Ch); IF Ch = '0' THEN D := 0 ELSE IF Ch = '1' THEN D := 1 ELSE IF Ch = '2' THEN D := 2 ELSE IF Ch = '3' THEN D := 3 ELSE IF Ch = '4' THEN D := 4 ELSE IF Ch = '5' THEN D := 5 ELSE IF Ch = '6' THEN D := 6 ELSE IF Ch = '7' THEN D := 7 ELSE IF Ch = '8' THEN D := 8 ELSE IF Ch = '9' THEN D := 9 END END; {ReadDigit} PROCEDURE ReadNumber(VAR F: TEXT; VAR N: INTEGER); {В N возвращается число, прочитанное из F} VAR Digit: INTEGER; Overflow: BOOLEAN; BEGIN {ReadNumber} N := 0; Overflow := FALSE; IF NOT EOLN THEN BEGIN Digit := 0; WHILE NOT Overflow AND (Digit <> -1) DO BEGIN N := N * 10 + Digit; ReadDigit(F, Digit); Overflow := MAXINT < (N * 10 + Digit) END END; IF Overflow THEN N := -1 END; {ReadNumber} VAR Number: INTEGER; BEGIN {ProcedureTest} ReadNumber(INPUT, Number); IF Number = -1 THEN WRITE('Err, overflow!') ELSE WRITE('Entered number:', Number); WRITELN END. {ProcedureTest}
unit observer_pattern_interfaces; interface uses Classes,Typinfo,command_class_lib; type IObserver=interface procedure ObserverUpdate; end; IObservable=interface procedure AddObserver(who: IObserver); procedure DeleteObserver(who: IObserver); procedure NotifyObservers; end; TNoRefCount=class(TObject,IUnknown) protected function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; end; TObservableImplementor=class(TNoRefCount,IObservable) private fIntfList: TInterfaceList; public constructor Create; destructor Destroy; override; procedure AddObserver(who: IObserver); procedure DeleteObserver(who: IObserver); procedure NotifyObservers; end; //немного из другой оперы - расширение properties для отобр. в программе свойств //объекта. TAdvPropInfo=class public PropType: PPTypeInfo; GetProc: Pointer; SetProc: Pointer; StoredProc: Pointer; Index: Integer; Default: Longint; NameIndex: SmallInt; Name: ShortString; instance: TPersistent; //кому принадл. свойство title,hint: string; isAdditional: boolean; doc: TAbstractDocument; end; RegisterPropertyProc = procedure(PropInfo: TAdvPropInfo) of object; AddTitleAndHintProc=procedure(name,title,hint: string; aisAdditional: boolean=false) of object; UnRegisterPropertyProc = procedure(name: string) of object; IAdvancedProperties=interface ['{966861D4-EC7A-4900-9679-0BD30215B273}'] procedure RegisterProperties(proc: RegisterPropertyProc); procedure AddTitleAndHint(proc: AddTitleAndHintProc); procedure UnregisterProperties(proc: UnregisterPropertyProc); end; implementation uses windows; (* TNoRefCount *) function TNoRefCount._AddRef: Integer; begin Result:=-1; end; function TNoRefCount._Release: Integer; begin result:=-1; end; function TNoRefCount.QueryInterface(const IID: TGUID; out obj): HResult; begin if GetInterface(IID,obj) then Result:=0 else Result:=Windows.E_NOINTERFACE; end; (* TObserverSubjectImplementor *) constructor TObservableImplementor.Create; begin inherited Create; fIntfList:=TInterfaceList.Create; end; destructor TObservableImplementor.Destroy; begin fIntfList.Free; inherited Destroy; end; procedure TObservableImplementor.AddObserver(who: IObserver); begin fIntfList.Add(who); who.ObserverUpdate; //так сказать, ввести в курс дела end; procedure TObservableImplementor.DeleteObserver(who: IObserver); begin fIntfList.Remove(who); end; procedure TObservableImplementor.NotifyObservers; var i: Integer; begin for i:=0 to fIntfList.Count-1 do IObserver(fIntfList.Items[i]).ObserverUpdate; end; end.
unit vcmOperations; {* Компонент для определения списка операций. } { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmOperations - } { Начат: 13.03.2003 18:11 } { $Id: vcmOperations.pas,v 1.5 2011/07/29 15:08:37 lulin Exp $ } // $Log: vcmOperations.pas,v $ // Revision 1.5 2011/07/29 15:08:37 lulin // {RequestLink:209585097}. // // Revision 1.4 2010/09/15 18:15:01 lulin // {RequestLink:235047275}. // // Revision 1.3 2004/09/11 12:29:10 lulin // - cleanup: избавляемся от прямого использования деструкторов. // - new unit: vcmComponent. // // Revision 1.2 2003/11/30 15:15:31 law // - new behavior: добавлена генерация констант для операций модуля. // // Revision 1.1 2003/04/01 12:54:44 law // - переименовываем MVC в VCM. // // Revision 1.1 2003/03/12 15:29:18 law // - new component: _TvcmOperations. // {$I vcmDefine.inc } interface {$IfNDef NoVCM} uses Classes, vcmInterfaces, vcmComponent, vcmOperationsCollection ; type TvcmCustomOperations = class(TvcmComponent) {* Компонент для определения списка операций. } private // internal fields f_Operations: TvcmOperationsCollection; protected // property methods function pm_GetOperations: TvcmOperationsCollection; procedure pm_SetOperations(aValue: TvcmOperationsCollection); {-} protected // internal methods procedure Cleanup; override; {-} public // public methods constructor Create(anOwner: TComponent); override; {-} procedure RegisterInRep; {-} public // public properties property Operations: TvcmOperationsCollection read pm_GetOperations write pm_SetOperations; {* - коллекция операций. } end;//TvcmCustomOperations {$EndIf NoVCM} implementation {$IfNDef NoVCM} uses SysUtils ; // start class TvcmCustomOpertions constructor TvcmCustomOperations.Create(anOwner: TComponent); //override; {-} begin inherited; f_Operations := TvcmOperationsCollection.Create(Self); end; procedure TvcmCustomOperations.Cleanup; //override; {-} begin FreeAndNil(f_Operations); inherited; end; function TvcmCustomOperations.pm_GetOperations: TvcmOperationsCollection; {-} begin Result := f_Operations; end; procedure TvcmCustomOperations.pm_SetOperations(aValue: TvcmOperationsCollection); {-} begin f_Operations.Assign(aValue); end; procedure TvcmCustomOperations.RegisterInRep; {-} begin if (Operations <> nil) then Operations.RegisterInRep; end; {$EndIf NoVCM} end.
unit TestVK_API; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Data.DBXJSON, RegularExpressions, uVK_API, IdHTTP, Generics.Collections, IdException, uGnLog, uGnGeneral, SysUtils, DateUtils, Classes; type TMyHttp = class(TComponent, IHttp) private FLastUrl: string; FAnswer: string; public function Get(const AUrl: string): string; property LastUrl: string read FLastUrl; property Answer: string read FAnswer write FAnswer; end; TestTVK = class(TTestCase) strict private FHttp: TMyHttp; FVK: TVK; public procedure SetUp; override; procedure TearDown; override; published procedure TestPages_GetTitles; procedure TestGroups_GetById; procedure TestGroups_Search; procedure TestWall_Get; end; implementation const cAccessToken = 'adfqf3'; cGoodAnswer = 'answer'; procedure TestTVK.SetUp; begin FHttp := TMyHttp.Create(nil); FVK := TVK.Create(cAccessToken, FHttp); end; procedure TestTVK.TearDown; begin FreeAndNil(FHttp); FreeAndNil(FVK); end; procedure TestTVK.TestPages_GetTitles; var ReturnValue: string; AGid: string; begin AGid := '13214325'; FHttp.Answer := cGoodAnswer; ReturnValue := FVK.Pages_GetTitles(AGid); CheckEqualsString('https://api.vk.com/method/pages.getTitles?access_token=' + cAccessToken + '&gid=' + AGid, FHttp.LastUrl); CheckEqualsString(cGoodAnswer, ReturnValue); end; procedure TestTVK.TestGroups_GetById; var ReturnValue: string; AGid: string; begin // TODO: Setup method call parameters ReturnValue := FVK.Groups_GetById(AGid); // TODO: Validate method results end; procedure TestTVK.TestGroups_Search; var ReturnValue: string; Aq: string; begin // TODO: Setup method call parameters ReturnValue := FVK.Groups_Search(Aq); // TODO: Validate method results end; procedure TestTVK.TestWall_Get; var ReturnValue: string; AExtended: string; AFilter: string; ACount: string; AOffset: string; AOwnerId: string; begin // TODO: Setup method call parameters ReturnValue := FVK.Wall_Get(AOwnerId, AOffset, ACount, AFilter, AExtended); // TODO: Validate method results end; { TMyHttp } function TMyHttp.Get(const AUrl: string): string; begin FLastUrl := AUrl; Result := FAnswer; end; initialization // Register any test cases with the test runner RegisterTest(TestTVK.Suite); end.
unit Ip2Country; interface uses Windows, SysUtils, Classes, Contnrs, Lookups; type TIp2Country = class private FIndex: AnsiString; FIndexCount: integer; FData: TIntToStrLookup; FDataLen: Cardinal; FDataOffset: Cardinal; FStream: TFileStream; FLastEntry: AnsiString; protected function FindRecord(Data, Search: AnsiString; RecSize: integer): AnsiString; procedure FindIndexPos(IP: AnsiString; var Pos, Len: Cardinal); function GetDataEntry(Pos, Len: Cardinal): AnsiString; public constructor Create(DataFile: AnsiString = ''); destructor Destroy; override; class function a2bin(IP: AnsiString): AnsiString; class function bin2a(bin: AnsiString): AnsiString; function LookupBin(bin: AnsiString): AnsiString; function Lookup(IP: AnsiString): AnsiString; procedure Preload; end; implementation type PIndexRecord = ^TIndexRecord; TIndexRecord = record IP: Cardinal; Position: Cardinal; Length: Cardinal; end; { TIp2Country } // Initialize and open the data file constructor TIp2Country.Create(DataFile: AnsiString); var buf: array[1..2] of Cardinal; begin if DataFile = '' then DataFile := 'ip2country.dat'; FData := TIntToStrLookup.Create; FStream := TFileStream.Create(DataFile, fmOpenRead); // Read the index and data length FStream.Read(PAnsiChar(@buf[1])^, 8); FDataOffset := buf[1] + 8; FDataLen := buf[2]; // Read the entire index into memory SetLength(FIndex, buf[1]); FStream.Read(PAnsiChar(FIndex)^, Length(FIndex)); FIndexCount := Length(FIndex) div 12; end; destructor TIp2Country.Destroy; begin if FStream <> nil then FStream.Free; FData.Free; inherited; end; // Translate a dotted IP into a binary format class function TIp2Country.a2bin(IP: AnsiString): AnsiString; var i, c: integer; a: array[1..4] of AnsiString; begin c := 1; for i := 1 to Length(IP) do if IP[i] = '.' then Inc(c) else if (IP[i] in ['0'..'9']) and (c <= 4) then a[c] := a[c] + IP[i] else raise Exception.Create('Invalid IP address: ' + IP); Result := Chr(StrToInt(a[1])) + Chr(StrToInt(a[2])) + Chr(StrToInt(a[3])) + Chr(StrToInt(a[4])); end; // Translate a binary IP into a dotted AnsiString class function TIp2Country.bin2a(bin: AnsiString): AnsiString; begin Result := IntToStr(Ord(bin[1])) + '.' + IntToStr(Ord(bin[2])) + '.' + IntToStr(Ord(bin[3])) + '.' + IntToStr(Ord(bin[4])); end; // Lookup the index for a particular IP address. Returns the position and length // in the data file. procedure TIp2Country.FindIndexPos(IP: AnsiString; var Pos, Len: Cardinal); var index: AnsiString; p: PIndexRecord; begin index := FindRecord(FIndex, IP, 12); p := PIndexRecord(PAnsiChar(index)); Pos := p.Position; Len := p.Length; end; // Find a particular record. Uses a data AnsiString with records of a particular // record size. Uses a binary search algorithm, where we maintain an interval // and divide in half each attempt - yielding effectively O(log2 n) efficiency. // Always tries to return an additional 4 bytes beyond the record size - this // will be the IP address from the *next* block, which we can use as an upper // bound to determine if we can cache the next lookup. function TIp2Country.FindRecord(Data, Search: AnsiString; RecSize: integer): AnsiString; var i, l, h, len, c: integer; s2: AnsiString; r: AnsiString; begin l := 0; len := Length(Data) div RecSize; h := len - 1; while l <= h do begin i := (l + h) shr 1; Result := Copy(Data, i*RecSize + 1, RecSize + 4); r := Copy(Result, 1, 4); c := CompareStr(Search, r); if c = 0 then exit else if c > 0 then begin if i+1 >= len then exit; s2 := Copy(Data, (i+1)*RecSize + 1, RecSize + 4); c := CompareStr(Search, Copy(s2, 1, 4)); if c = 0 then begin Result := s2; exit; end else if c < 0 then exit; l := i + 1; end else h := i - 1; end; raise Exception.Create('Binary find failure'); end; // Get a particular data block - load it from disk if necessary; if it's // already in memory, just return it function TIp2Country.GetDataEntry(Pos, Len: Cardinal): AnsiString; var s: AnsiString; begin if not FData.Exists(Pos) then begin FStream.Seek(Pos + FDataOffset, soFromBeginning); SetLength(s, Len + 6); FStream.Read(PAnsiChar(s)^, Len + 6); FData.Add(Pos, s); end; Result := FData.Value(Pos); end; // Look up a dotted IP address and return the two-letter country code. // If the IP address is in the same IP block as the last IP, we cache the // result without doing a database lookup. So try to do lookups in sort order, // this will improve access times. function TIp2Country.Lookup(IP: AnsiString): AnsiString; begin Result := LookupBin(a2bin(IP)); end; // Look up a binary IP address (see a2bin) and return the two-letter country // code. function TIp2Country.LookupBin(bin: AnsiString): AnsiString; var pos, len: Cardinal; data: AnsiString; begin if (Length(FLastEntry) = 10) and (CompareStr(bin, Copy(FLastEntry, 1, 4)) >= 0) and (CompareStr(bin, Copy(FLastEntry, 7, 4)) < 0) then begin Result := Copy(FLastEntry, 5, 2); exit; end; FindIndexPos(bin, pos, len); data := GetDataEntry(pos, len); FLastEntry := FindRecord(data, bin, 6); Result := Copy(FLastEntry, 5, 2); end; // Preload the database into memory for fastest access. procedure TIp2Country.Preload; var data: AnsiString; pix: PIndexRecord; i: integer; begin if FStream = nil then exit; FStream.Seek(FDataOffset, soFromBeginning); SetLength(data, FDataLen); FStream.Read(PAnsiChar(data)^, FDataLen); pix := PIndexRecord(PAnsiChar(FIndex)); for i := 0 to FIndexCount - 1 do begin if not FData.Exists(pix.Position) then FData.Add(pix.Position, Copy(data, pix.Position + 1, pix.Length + 6)); Inc(pix); end; FreeAndNil(FStream); end; initialization if TIp2Country.a2bin('194.218.238.1') <> #$C2#$DA#$EE#$01 then raise Exception.Create('a2bin test failed'); if TIp2Country.bin2a(#$C2#$DA#$EE#$01) <> '194.218.238.1' then raise Exception.Create('bin2a test failed'); end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clUploader; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$ELSE} System.Classes, {$ENDIF} clMultiDC, clSingleDC, clDCUtils, clMultiUploader, clHttpRequest; type TclSingleUploadItem = class(TclUploadItem) protected function GetForceRemoteDir: Boolean; override; function GetControl: TclCustomInternetControl; override; end; TclUploader = class(TclSingleInternetControl) private FForceRemoteDir: Boolean; function GetUploadItem(): TclSingleUploadItem; function GetHttpResponse: TStrings; function GetHttpResponseStream: TStream; function GetUseSimpleRequest: Boolean; procedure SetHttpResponseStream(const Value: TStream); procedure SetUseSimpleRequest(const Value: Boolean); function GetRequestMethod: string; procedure SetRequestMethod(const Value: string); protected function GetInternetItemClass(): TclInternetItemClass; override; public property HttpResponse: TStrings read GetHttpResponse; property HttpResponseStream: TStream read GetHttpResponseStream write SetHttpResponseStream; published property ThreadCount default 1; property UseSimpleRequest: Boolean read GetUseSimpleRequest write SetUseSimpleRequest default False; property RequestMethod: string read GetRequestMethod write SetRequestMethod; property ForceRemoteDir: Boolean read FForceRemoteDir write FForceRemoteDir default False; end; implementation { TclSingleUploadItem } type TCollectionAccess = class(TCollection); function TclSingleUploadItem.GetControl: TclCustomInternetControl; begin Result := (TCollectionAccess(Collection).GetOwner() as TclCustomInternetControl); end; function TclSingleUploadItem.GetForceRemoteDir: Boolean; begin Result := (Control as TclUploader).ForceRemoteDir; end; { TclUploader } function TclUploader.GetInternetItemClass: TclInternetItemClass; begin Result := TclSingleUploadItem; end; function TclUploader.GetHttpResponse: TStrings; begin Result := GetUploadItem().HttpResponse; end; function TclUploader.GetHttpResponseStream: TStream; begin Result := GetUploadItem().HttpResponseStream; end; function TclUploader.GetUploadItem(): TclSingleUploadItem; begin Result := (GetInternetItem() as TclSingleUploadItem); end; function TclUploader.GetUseSimpleRequest: Boolean; begin Result := GetUploadItem().UseSimpleRequest; end; procedure TclUploader.SetHttpResponseStream(const Value: TStream); begin GetUploadItem().HttpResponseStream := Value; end; procedure TclUploader.SetUseSimpleRequest(const Value: Boolean); begin GetUploadItem().UseSimpleRequest := Value; end; function TclUploader.GetRequestMethod: string; begin Result := GetUploadItem().RequestMethod; end; procedure TclUploader.SetRequestMethod(const Value: string); begin GetUploadItem().RequestMethod := Value; end; end.
unit QReportSetupDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ReportSetupForm, ffstypes; type TQReportSetupDialog = class(TComponent) private FReportFormat: TFFSRptFormat; procedure SetReportFormat(const Value: TFFSRptFormat); private FSingle: boolean; FTINotes: boolean; FLoanNotes: boolean; FDestination: TFFSReportDest; FReportFileName: string; FViewCaption: TCaption; FSaveDir: string; FTIHist: boolean; FCaption3: string; FCaption1: string; FCaption2: string; procedure SetSingle(const Value: boolean); procedure SetLoanNotes(const Value: boolean); procedure SetTINotes(const Value: boolean); procedure SetReportFileName(const Value: string); procedure SetViewCaption(const Value: TCaption); { Private declarations } procedure ViewReport; procedure PrintReport; procedure SetSaveDir(const Value: string); procedure SetTIHist(const Value: boolean); procedure SetCaption1(const Value: string); procedure SetCaption2(const Value: string); procedure SetCaption3(const Value: string); procedure SetDestination(const Value: TFFSReportDest); property ReportFormat:TFFSRptFormat read FReportFormat write SetReportFormat; protected { Protected declarations } public { Public declarations } property Destination : TFFSReportDest read FDestination write SetDestination; procedure ShowReport; function Execute:boolean; published { Published declarations } property Single:boolean read FSingle write SetSingle; property LoanNotes:boolean read FLoanNotes write SetLoanNotes; property TINotes:boolean read FTINotes write SetTINotes; property TIHist:boolean read FTIHist write SetTIHist; property ReportFileName:string read FReportFileName write SetReportFileName; property ViewCaption:TCaption read FViewCaption write SetViewCaption; property SaveDir:string read FSaveDir write SetSaveDir; property Caption1:string read FCaption1 write SetCaption1; property Caption2:string read FCaption2 write SetCaption2; property Caption3:string read FCaption3 write SetCaption3; end; procedure Register; implementation uses ffsRptViewer; function TQReportSetupDialog.Execute: boolean; var frmReportSetup: TfrmReportSetup; begin result := false; frmReportSetup := TfrmReportSetup.create(self, single); try if caption1 > '' then frmReportSetup.cbxLoanNotes.Caption := caption1; frmReportSetup.cbxLoanNotes.Checked := LoanNotes; if caption2 > '' then frmReportSetup.cbxTINotes.Caption := caption2; frmReportSetup.cbxTINotes.Checked := TINotes; if caption3 > '' then frmReportSetup.cbxTIHist.Caption := caption3; frmReportSetup.cbxTIHist.Checked := TIHist; if frmReportSetup.ShowModal = mrOk then begin LoanNotes := frmReportSetup.cbxLoanNotes.Checked; TINotes := frmReportSetup.cbxTINotes.Checked; TIHist := frmReportSetup.cbxTIHist.Checked; FDestination := frmReportSetup.Destination; result := true; end; finally frmReportSetup.Free; end; end; procedure TQReportSetupDialog.PrintReport; //var // aaf: TAceAceFile; // ap : TAcePrinter; // hv : THtmlviewer; begin (* case ReportFormat of rfAce : begin ap := TAcePrinter.Create; aaf := TAceAceFile.Create; aaf.loadfromfile(ReportFileName); ap.LoadPages(aaf, 1, aaf.pages.count); ap.free; aaf.free; end; rfHTML : begin hv := THtmlViewer.Create(self); hv.LoadFromFile(ReportFileName); hv.Print(1,999999); hv.free; end; end; *) end; procedure TQReportSetupDialog.SetCaption1(const Value: string); begin FCaption1 := Value; end; procedure TQReportSetupDialog.SetCaption2(const Value: string); begin FCaption2 := Value; end; procedure TQReportSetupDialog.SetCaption3(const Value: string); begin FCaption3 := Value; end; procedure TQReportSetupDialog.SetDestination(const Value: TFFSReportDest); begin FDestination := Value; end; procedure TQReportSetupDialog.SetLoanNotes(const Value: boolean); begin FLoanNotes := Value; end; procedure TQReportSetupDialog.SetReportFileName(const Value: string); begin FReportFileName := Value; ReportFormat := rfAce; // #Miller - Need to possibly view ace reports ReportFormat := rfHtml; end; procedure TQReportSetupDialog.SetReportFormat(const Value: TFFSRptFormat); begin FReportFormat := Value; end; procedure TQReportSetupDialog.SetSaveDir(const Value: string); begin FSaveDir := Value; end; procedure TQReportSetupDialog.SetSingle(const Value: boolean); begin FSingle := Value; end; procedure TQReportSetupDialog.SetTIHist(const Value: boolean); begin FTIHist := Value; end; procedure TQReportSetupDialog.SetTINotes(const Value: boolean); begin FTINotes := Value; end; procedure TQReportSetupDialog.SetViewCaption(const Value: TCaption); begin FViewCaption := Value; end; procedure TQReportSetupDialog.ShowReport; begin case destination of rdScreen : ViewReport; rdPrinter : PrintReport; end; end; procedure TQReportSetupDialog.ViewReport; var hview : TfrmFFSRptViewer; begin case ReportFormat of rfHtml : begin hview := TfrmFFSRptViewer.Create(self); try hview.Viewer.LoadFromFile(ReportFileName); hview.Caption := ViewCaption; hView.ShowModal; finally hView.free; end; end; rfAce : begin (* Viewer := TAceViewer.Create(self); Viewer.SaveFileDialog.InitialDir := SaveDir; Viewer.Caption := ViewCaption; Viewer.LeftPreview.LoadFromFile(ReportFileName); Viewer.WindowState := wsMaximized; Viewer.UpdatePage; Viewer.ShowModal; Viewer.free; *) end; end; end; procedure Register; begin RegisterComponents('FFS Dialogs', [TQReportSetupDialog]); end; end.
unit GlobalPAFData; interface type ShortString = String[15]; LongString = String[50]; XLongString = UnicodeString; TGlobalPAFData = class procedure Clear; protected FStartTime, FEndTime, FBestDatum: TDateTime; FUsRum, FLevtId, FTdbTyp1, // Rum FTdbTyp2, // Läkarsign FTdbTyp3, // besökstyp a=Akut etc. FTdbTyp4, // Använd ej? FTdbTyp5, // Kommentar Fpid, FBid, FRid, FRemSign, FRemUsr, FTdbUsr, FUndLak, FNotes, FProdkod, FBestId: ShortString; FFrageText, FAnamnes: XLongString; FLevttxt, FBestLak, FBestTxt, FProdtext, FPatNamn, FCAdress, FBAdress, FPAdress, FHTele, FATele: LongString; FUtid, // Undersökningens tidsåtgång FPrioritet, FKBrevFlg, FRBrevFlg, FProdFlg, FSpecFlg, FTaxtFlg, FBlockFlg, FAlNr, FALlNr: Integer; FAkut, FAnnanAvd, FAlladata: Boolean; published property BestDatum: TDateTime read FBestDatum write FBestDatum; property StartTime: TDateTime read FStartTime write FStartTime; property EndTime: TDateTime read FEndTime write FEndTime; property UsRum: ShortString read FUsRum write FUsRum; property LevtId: ShortString read FLevtId write FLevtId; property TdbTyp1: ShortString read FTdbTyp1 write FTdbTyp1; // Rum property TdbTyp2: ShortString read FTdbTyp2 write FTdbTyp2; // Läkarsign property TdbTyp3: ShortString read FTdbTyp3 write FTdbTyp3; // Besökstyp ' a=Akut etc. property TdbTyp4: ShortString read FTdbTyp4 write FTdbTyp4; // Använd ej? property TdbTyp5: ShortString read FTdbTyp5 write FTdbTyp5; // Kommentar property pid: ShortString read Fpid write Fpid; property Bid: ShortString read FBid write FBid; property Rid: ShortString read FRid write FRid; property RemSign: ShortString read FRemSign write FRemSign; property RemUsr: ShortString read FRemUsr write FRemUsr; property TdbUsr: ShortString read FTdbUsr write FTdbUsr; property UndLak: ShortString read FUndLak write FUndLak; property Notes: ShortString read FNotes write FNotes; property Prodkod: ShortString read FProdkod write FProdkod; property BestId: ShortString read FBestId write FBestId; property FrageText: string read FFrageText write FFrageText; property Anamnes: String read FAnamnes write FAnamnes; property Levttxt: LongString read FLevttxt write FLevttxt; property BestLak: LongString read FBestLak write FBestLak; property BestTxt: LongString read FBestTxt write FBestTxt; property Prodtext: LongString read FProdtext write FProdtext; // property EfterNamn: longString read FEfterNamn write FEfterNamn; property PatNamn: LongString read FPatNamn write FPatNamn; property CAdress: LongString read FCAdress write FCAdress; property BAdress: LongString read FBAdress write FBAdress; property PAdress: LongString read FPAdress write FPAdress; property HTele: LongString read FHTele write FHTele; property ATele: LongString read FATele write FATele; property Utid: Integer read FUtid write FUtid; property Prioritet: Integer read FPrioritet write FPrioritet; property KBrevFlg: Integer read FKBrevFlg write FKBrevFlg; property RBrevFlg: Integer read FRBrevFlg write FRBrevFlg; property ProdFlg: Integer read FProdFlg write FProdFlg; property SpecFlg: Integer read FSpecFlg write FSpecFlg; property TaxtFlg: Integer read FTaxtFlg write FTaxtFlg; property BlockFlg: Integer read FBlockFlg write FBlockFlg; property ALNr: Integer read FAlNr write FAlNr; property ALlNr: Integer read FALlNr write FALlNr; property Akut: Boolean read FAkut write FAkut; property AnnanAvd: Boolean read FAnnanAvd write FAnnanAvd; property Alladata: Boolean read FAlladata write FAlladata; end; implementation { TGlobalPAFData } procedure TGlobalPAFData.Clear; begin FBestDatum := 0; FUsRum := ''; FLevtId := ''; FTdbTyp1 := ''; FTdbTyp2 := ''; FTdbTyp3 := ''; FTdbTyp4 := ''; FTdbTyp5 := ''; Fpid := ''; FBid := ''; FRid := ''; FRemSign := ''; FRemUsr := ''; FTdbUsr := ''; FUndLak := ''; FNotes := ''; FProdkod := ''; FBestId := ''; FFrageText := ''; FAnamnes := ''; FLevttxt := ''; FBestLak := ''; FBestTxt := ''; FProdtext := ''; FPatNamn := ''; FCAdress := ''; FBAdress := ''; FPAdress := ''; FHTele := ''; FATele := ''; FPrioritet := 0; FKBrevFlg := 0; FRBrevFlg := 0; FProdFlg := 0; FSpecFlg := 0; FTaxtFlg := 0; FBlockFlg := 0; FAlNr := 0; FALlNr := 0; FAkut := False; FAnnanAvd := False; FAlladata := False; end; end.
unit rc4; interface const DecChars : string = #1#2#3#4#5#6#7#8#9#10#11#12#13#15 + '¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ'; type TRC4 = class public constructor Load(var cypherAry); private fBytCypherAry : array[0..255] of byte; fHasKey : boolean; private //procedure InitializeCypher; procedure SetKey(pStrKey : string); public function Apply(pStrMessage : string) : string; function toHex(pStrMessage : string) : string; function toBin(pStrMessage : string) : string; function genKey(len : integer) : string; public property Key : string write SetKey; end; implementation // TRC4 constructor TRC4.Load(var cypherAry); begin inherited Create; move(cypherAry, fBytCypherAry[0], sizeof(fBytCypherAry[0])); fHasKey := true; end; procedure TRC4.SetKey(pStrKey : string); var lLngKeyLength : integer; lLngIndex : integer; BytKeyAry : array[0..255] of byte; lBytJump : integer; lBytIndex : integer; lBytTemp : byte; begin // if the key is diff and not empty, change it if pStrKey <> '' then begin fHasKey := true; lLngKeyLength := Length(pStrKey); // spread the key all over the array for lLngIndex := 0 To 255 do BytKeyAry[lLngIndex] := byte(pStrKey[lLngIndex mod lLngKeyLength + 1]); // init the array for lBytIndex := 0 To 255 do fBytCypherAry[lBytIndex] := lBytIndex; // Switch values of Cypher arround based off of index and Key value lBytJump := 0; for lBytIndex := 0 to 255 do begin // Figure index To switch lBytJump := (lBytJump + fBytCypherAry[lBytIndex] + BytKeyAry[lBytIndex]) mod 256; // Do the switch lBytTemp := fBytCypherAry[lBytIndex]; fBytCypherAry[lBytIndex] := fBytCypherAry[lBytJump]; fBytCypherAry[lBytJump] := lBytTemp; end; end; end; function TRC4.Apply(pStrMessage : string) : string; var lBytIndex : integer; lBytJump : integer; lBytTemp : byte; lBytY : byte; lLngT : integer; lLngX : integer; len : integer; TmpCypher : array[0..255] of byte; begin len := length(pStrMessage); if fHasKey and (len > 0) then begin SetLength(result, len); // save the cypherArray move(fBytCypherAry[0], TmpCypher[0], sizeof(fBytCypherAry)); lBytIndex := 0; lBytJump := 0; for lLngX := 1 To len do begin lBytIndex := (lBytIndex + 1) mod 256; // wrap index lBytJump := (lBytJump + TmpCypher[lBytIndex]) mod 256; // ' wrap J+S() // Add/Wrap those two lLngT := (11 + TmpCypher[lBytIndex] + TmpCypher[lBytJump]) mod 256; // Switcheroo lBytTemp := TmpCypher[lBytIndex]; TmpCypher[lBytIndex] := TmpCypher[lBytJump]; TmpCypher[lBytJump] := lBytTemp; lBytY := TmpCypher[lLngT]; // Character Encryption ... result[lLngX] := char(byte(pStrMessage[lLngX]) xor lBytY); end; end else result := pStrMessage; end; function TRC4.toHex(pStrMessage : string) : string; const HEX_DIGITS : array[0..15] of char = '0123456789ABCDEF'; var len : integer; i : integer; tmp : byte; begin len := Length(pStrMessage); if pStrMessage <> '' then begin SetLength(result, 2*len); for i := 1 to len do begin tmp := byte(pStrMessage[i]); result[2*i-1] := HEX_DIGITS[(tmp and $0F)]; result[2*i] := HEX_DIGITS[(tmp and $F0) shr 4]; end; end else result := ''; end; function TRC4.toBin(pStrMessage : string) : string; function htoi(l, h : char) : char; var l1 : byte; h1 : byte; begin l1 := ord(l); if l1 >= ord('A') then l1 := 10 + l1 - ord('A') else l1 := l1 - ord('0'); h1 := ord(h); if h1 >= ord('A') then h1 := 10 + h1 - ord('A') else h1 := h1 - ord('0'); result := char(byte(l1) or (byte(h1) shl 4)); end; var len : integer; i : integer; begin len := Length(pStrMessage); if (len > 0) and (len mod 2 = 0) then begin SetLength(result, len div 2); for i := 1 to len div 2 do result[i] := htoi(pStrMessage[2*i-1], pStrMessage[2*i]); end else result := ''; end; function TRC4.genKey(len : integer) : string; var i : integer; begin SetLength(result, len); for i := 1 to len do result[i] := char(ord('0') + random(ord('z') - ord('0'))); end; { procedure TRC4.InitializeCypher; var lBytJump : integer; lBytIndex : integer; lBytTemp : byte; begin // init the array with the a[i]=i for lBytIndex := 0 To 255 do fBytCypherAry[lBytIndex] := lBytIndex; // Switch values of Cypher arround based off of index and Key value lBytJump := 0; for lBytIndex := 0 to 255 do begin // Figure index To switch lBytJump := (lBytJump + fBytCypherAry[lBytIndex] + fBytKeyAry[lBytIndex]) mod 256; // Do the switch lBytTemp := fBytCypherAry[lBytIndex]; fBytCypherAry[lBytIndex] := fBytCypherAry[lBytJump]; fBytCypherAry[lBytJump] := lBytTemp; end; end; procedure TRC4.SetKey(pStrKey : string); var lLngKeyLength : integer; lLngIndex : integer; begin // if the key is diff and not empty, change it if (pStrKey <> '') and (pStrKey <> fStrKey) then begin fStrKey := pStrKey; lLngKeyLength := Length(pStrKey); // spread the key all over the array for lLngIndex := 0 To 255 do fBytKeyAry[lLngIndex] := byte(pStrKey[lLngIndex mod lLngKeyLength + 1]); end; end; } initialization randomize; end.