text
stringlengths
14
6.51M
// -------------------------------------------------------------------------- // 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 Cantidad; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QcurrEdit, IniFiles, QTypes, QMenus; type TfrmCantidad = class(TForm) grpCantidad: TGroupBox; lblTexto: TLabel; txtCantidad: TcurrEdit; btnAceptar: TBitBtn; btnCancelar: TBitBtn; btnCalc: TBitBtn; cbfiscal: TCheckBox; clabel: TLabel; concepto: TEdit; r1: TLabel; v1: TLabel; r2: TLabel; v2: TLabel; r3: TLabel; v3: TLabel; r4: TLabel; v4: TLabel; r5: TLabel; v5: TLabel; pre: TLabel; ra1: TLabel; ra2: TLabel; ra3: TLabel; ra4: TLabel; ra5: TLabel; rango: TLabel; cajas: TcurrEdit; cajch: TCheckBox; fast: TPopupMenu; fasfc: TMenuItem; procedure btnAceptarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnCalcClick(Sender: TObject); procedure cajasChange(Sender: TObject); procedure cajchClick(Sender: TObject); procedure fasfcClick(Sender: TObject); private procedure RecuperaConfig; public rCantidad : real; rmotivo: string; // modificacion 21/07/09 bDecimales : boolean; retiro: boolean; /// modificacion 21/07/2009 sTitulo : String; fac:real; rkg: real; end; var frmCantidad: TfrmCantidad; implementation uses Calc, Compras; {$R *.xfm} procedure TfrmCantidad.btnAceptarClick(Sender: TObject); begin btnAceptar.SetFocus; if(Length(txtCantidad.Text) > 0) then begin //if(not bDecimales) then //rCantidad := Int(txtCantidad.Value) //else rCantidad := txtCantidad.Value; rmotivo := concepto.Text;// modificacion 21/07/09 rkg := 0; end end; procedure TfrmCantidad.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('Cantidad', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Cantidad', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; Free; end; end; procedure TfrmCantidad.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('Cantidad', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Cantidad', 'Posx', IntToStr(Left)); Free; end; end; procedure TfrmCantidad.FormShow(Sender: TObject); begin Caption := sTitulo; if (retiro) then begin concepto.Visible:= true; clabel.Visible:= true; end; if(bDecimales) then txtCantidad.Mask := '#,##0.000' else txtCantidad.Mask := '#,##0'; txtCantidad.Value := rCantidad; txtCantidad.SetFocus; txtCantidad.SelectAll; end; procedure TfrmCantidad.btnCancelarClick(Sender: TObject); begin rCantidad := -1; end; procedure TfrmCantidad.FormCreate(Sender: TObject); begin RecuperaConfig; end; procedure TfrmCantidad.btnCalcClick(Sender: TObject); begin with TFrmCalculadora.Create(Self) do try ShowModal; if(bUtilizar) then txtCantidad.Value := eResultado; finally Free; end; btnAceptar.SetFocus; end; procedure TfrmCantidad.cajasChange(Sender: TObject); begin if (cajas.Value <> 0) then begin txtCantidad.Value := (cajas.Value * fac) + txtCantidad.Value ; end; end; procedure TfrmCantidad.cajchClick(Sender: TObject); begin if cajch.Checked then begin txtcantidad.Enabled:= false; cajas.Enabled:= true; cajas.Value := 0; txtcantidad.Value := 0; end else begin txtcantidad.Enabled:= true; cajas.Value:=0; cajas.Enabled:= false; txtcantidad.Value := 1; end; end; procedure TfrmCantidad.fasfcClick(Sender: TObject); begin if cajch.Checked then begin cajch.Checked:= false; txtcantidad.Enabled:= true; cajas.Value:=0; cajas.Enabled:= false; txtcantidad.Value := 1; txtcantidad.SetFocus; end else begin cajch.Checked:= true; txtcantidad.Enabled:= false; cajas.Enabled:= true; cajas.Value := 0; txtcantidad.Value := 0; cajas.SetFocus; end; end; end.
unit XML_Parser; interface uses Classes, SysUtils; type TXML_Parser = class private opening_sequences, closing_sequences : TStringList; function loadXML(filename:string) : string; function updateIndex(text, pattern:string; index:integer) : integer; procedure parseSection public constructor create; procedure parseXML(filename:string); end; implementation uses StringFunctions, Dialogs; constructor TXML_Parser.create; begin opening_sequences := TStringList.create; closing_sequences := TStringList.create; opening_sequences.add('<'); closing_sequences.add('>'); opening_sequences.add('\"'); closing_sequences.add('\"'); opening_sequences.add('>'); closing_sequences.add('<'); end; procedure TXML_Parser.parseXML(filename:string); var xml : string; line : string; index : integer; begin xml := loadXML(filename); index := 1; line := getNextSection(xml, opening_sequences, closing_sequences, index); while (AnsiCompareStr(line, '') <> 0) do begin //ShowMessage(line); index := updateIndex(xml, line, index); line := getNextSection(xml, opening_sequences, closing_sequences, index); end; end; function TXML_Parser.loadXML(filename:string) : string; var f : TextFile; text : string; begin AssignFile(f, filename); Result := ''; Reset(f); while not eof(f) do begin readln(f, text); result := result + text; end; CloseFile(f); end; function TXML_Parser.updateIndex(text, pattern:string; index:integer) : integer; begin result := findSinglePatternAfterIndex(text, pattern, index); if(result = -1) then ShowMessage('XML_Parser Error :: findSinglePatternAfterIndex returned -1') else result := result + length(pattern) - 1; end; end.
program MinPrioQueueMain; {$MODE OBJFPC} uses uMinPrioQueue; type TIntegerArray = Array of Integer; function NewNode(const aName: String; const aEdges: TNodeArray): TNode; begin Result.Init(aName, aEdges); end; function NewQueueNode(const aNode: TNode; const aKey: Integer): TQueueNode; begin Result.Init(aNode, aKey); end; procedure Main; var queue: TMinPrioQueue; n0, n1, n2, n3, min: TNode; begin queue := TMinPrioQueue.Create; n0 := NewNode('new york', TNodeArray.Create(n1, n2)); n1 := NewNode('london', TNodeArray.Create(n2)); n2 := NewNode('moscu', TNodeArray.Create(n1, n3)); n3 := NewNode('other city', nil); try queue.Insert(NewQueueNode(n0, 40); queue.Insert(NewQueueNode(n1, 20); queue.Insert(NewQueueNode(n2, 10); queue.Insert(NewQueueNode(n3, 40); min := queue.GetMin; DecreaseKey(n2.edges[1], 5); min2 := queue.GetMin; finally queue.Free; end; WriteLn('min.name=',min.name,' min.idx=',min.idx); WriteLn('min2.name=',min2.name,' min2.idx=',min2.idx); end; begin Main; end.
{$I ok_sklad.inc} unit WaybillInClass; interface uses WayBillClass, WBMetaItem, MetaClass; type TWaybillInClass = class(TWayBillClass) private FWarehouseID: Integer; // common WH if all positions are from/to the same place public constructor Create(const AParent: TMetaClass); overload; constructor Create(AID: Integer); overload; //destructor Destroy; procedure Clear; function Load(const AID: integer): Boolean; function Save: Boolean; end; // TWaybillInClass //============================================================================================== //============================================================================================== //============================================================================================== //============================================================================================== implementation uses sysUtils, Forms, Controls, prFun, {prConst, ClientData, ssFun, ShellAPI, StdConvs, ssRegUtils, ssStrUtil, okMoneyFun, } udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; //============================================================================================== procedure TWayBillInClass.Clear; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWayBillInClass.Clear') else _udebug := nil;{$ENDIF} inherited; FWarehouseID := -1; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== constructor TWayBillInClass.Create(const AParent: TMetaClass); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWayBillInClass.Create') else _udebug := nil;{$ENDIF} inherited; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== constructor TWayBillInClass.Create(AID: Integer); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWayBillInClass.Create(' + IntToStr(AID) + ')') else _udebug := nil;{$ENDIF} Create(Self); Load(AID); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TWayBillInClass.Load(const AID: integer): Boolean; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWayBillInClass.Load') else _udebug := nil;{$ENDIF} Result := False; (* Screen.Cursor := crSQLWait; Clear; Fid := AID; with newDataSet do try ProviderName := 'pWaybill_Get'; FetchParams; Params.ParamByName('wbillid').AsInteger := AID; Open; if IsEmpty then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; FNumber := fieldbyname('num').AsString; FDEFNUM := fieldbyname('defnum').AsInteger; FDate := fieldbyname('ondate').AsDateTime; FBusinessPartner.Clear; FBusinessPartner.loadData(fieldbyname('kaid').AsInteger); if not fieldbyname('personid').IsNull then FPersonID := fieldbyname('personid').AsInteger; FReason := fieldbyname('REASON').asstring; FNotes := FieldByName('notes').AsString; FCurrencyID := fieldbyname('CURRID').AsInteger; FCurrencyRate := FieldByName('onvalue').AsFloat; FPosted := (fieldbyname('CHECKED').AsInteger = 1); FVAT := fieldbyname('NDS').AsFloat; if FieldByName('attnum').AsString = '' then FWarehouseID := 0 else try FWarehouseID := StrToInt(FieldByName('attnum').AsString); except end; Close; // pWaybill_Get { ProviderName := 'pDocsRel_WB_WB_Get'; FetchParams; Params.ParamByName('wbillid').AsInteger := FID; Params.ParamByName('doctype').AsInteger := 16; Open; if not IsEmpty then FOrderID := FieldByName('wbillid').AsInteger else FOrderID := 0; Close; ProviderName := 'pDocsRel_WB_Contr_Get'; FetchParams; Params.ParamByName('wbillid').AsInteger := FID; Params.ParamByName('doctype').AsInteger := 8; Open; if not IsEmpty then begin edContr.DocID := FieldByName('rdocid').AsInteger; FContrDocID := edContr.DocID; end else edContr.DocID := 0; Close; } ProviderName := prvDet; FetchParams; Params.ParamByName('wbillid').AsInteger := FID; Open; while not Eof do begin if mdDet.FieldByName('fullprice').IsNull then mdDet.FieldByName('fullprice').AsFloat := mdDet.FieldByName('price').AsFloat; UpdatePos; end; Close; ProviderName := 'pWayBillPay_Get';// Чтение платежа FetchParams; Params.ParamByName('WBILLID').AsInteger := FID; Open; if not IsEmpty then begin PayDocChecked := (FieldByName('Checked').AsInteger = 1); if not FieldByName('mpersonid').IsNull then lcbPayMPerson.KeyValue := FieldByName('mpersonid').AsInteger; PayDocId := FieldByName('PayDocId').AsInteger; OldPayDocID := PayDocID; PayDocDate := fieldbyname('OnDate').AsDateTime; edPayNum.Text := fieldbyname('DocNum').AsString; lcbPayType.KeyValue := fieldbyname('PTypeId').AsInteger; cbPayCurr.KeyValue := FieldByName('CurrId').AsInteger; edPaySumm.Value := FieldByName('Total').AsFloat; if cdsPayType.Locate('PTypeId',fieldbyname('CurrId').AsInteger,[]) then if not FieldByName('accid').IsNull then lcbAccount.KeyValue := FieldByName('accid').AsInteger else lcbAccount.Clear; if not FieldByName('cashid').IsNull then lcbCashDesks.KeyValue := FieldByName('cashid').AsInteger else lcbCashDesks.Clear; end //if not IsEmpty else begin PayDocChecked := False; PayDocId := 0; chbPay.Enabled := False; chbPay.Checked := False; chbPay.Enabled := True; edPayNum.Text := ''; edPaySumm.Value := 0; end; Close; FModified := false; finally Free; end; *) {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TWayBillInClass.Save: Boolean; var NewRecord: boolean; tmpid:integer; FPosID, intTmp: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWayBillInClass.Save') else _udebug := nil;{$ENDIF} Result := False; (* if not CheckDocDate(edDate.Date) then begin // in future? {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; with newDataSet do begin try Screen.Cursor := crSQLWait; NewRecord := (ID = 0); if NewRecord then FID := GetMaxID(dmData.SConnection, 'waybilllist', 'wbillid'); TrStart; try if NewRecord then ProviderName := 'pWaybill_InsEx' else ProviderName := 'pWaybill_UpdEx'; FetchParams; Params.ParamByName('WBILLID').AsInteger := FID; Params.ParamByName('NUM').AsString := FNumber; if FDefNum > 0 then Params.ParamByName('DEFNUM').AsInteger := FDefNum else Params.ParamByName('DEFNUM').AsInteger := GetNextDefNum(dmData.SConnection,1); Params.ParamByName('ONDATE').AsDateTime := FDate; Params.ParamByName('KAID').AsInteger := FBusinessPartner.ID; Params.ParamByName('CURRID').AsInteger := FCurrencyID; Params.ParamByName('ONVALUE').AsFloat := FCurrencyRate; Params.ParamByName('ATTNUM').AsString := ''; // warehouse for entire doc Params.ParamByName('ATTDATE').AsDate := 0; Params.ParamByName('REASON').AsString := FReason; Params.ParamByName('notes').AsString := FNotes; Params.ParamByName('PERSONID').AsInteger := FPersonID; Params.ParamByName('CHECKED').AsInteger := integer(FPosted); Params.ParamByName('WTYPE').AsInteger := 1; //тип накладной 1-приходная; -1-расходная; Params.ParamByName('DELETED').AsInteger := 0; Params.ParamByName('SUMMALL').AsFloat := RoundToA(FPositions.Total, -2); Params.ParamByName('SUMMINCURR').AsFloat := FPositions.TotalInDefCurr; Params.ParamByName('NDS').AsFloat := roundtoa(FVAT, -2); Params.ParamByName('RECEIVED').AsString := ''; Params.ParamByName('TODATE').DataType := ftDateTime; Params.ParamByName('TODATE').Clear; Params.ParamByName('entid').DataType := ftInteger; Params.ParamByName('entid').Clear; Execute;//Записали в waybilllist if not FPositions.Save then raise Exception.Create('Positions saving problem'); then begin // Запись позиций в накладную ProviderName := 'pWaybillDet_Del'; FetchParams; Params.ParamByName('WBILLID').AsInteger := ID; Execute; //Удалили позиции ProviderName := 'pWaybillSvc_Del'; FetchParams; Params.ParamByName('wbillid').AsInteger := FID; Execute; BM := mdDet.GetBookmark; mdDet.DisableControls; mdDet.First; // Запись позиций из mdDet в waybilldet while not mdDet.Eof do begin if mdDet.FieldByName('postype').AsInteger = 0 then begin if (FOrderID > 0) and NewRecord then begin FPosID := GetMaxID(dmData.SConnection, 'waybilldet', 'posid'); ProviderName := 'pWaybillDet_CopyPos'; FetchParams; Params.ParamByName('posid').AsInteger := FPosID; Params.ParamByName('oldposid').AsInteger := mdDet.FieldByName('posid').AsInteger; Execute; ProviderName := 'pPosRel_Ins'; FetchParams; Params.ParamByName('posid').AsInteger := FPosID; Params.ParamByName('cposid').AsInteger := mdDet.FieldByName('posid').AsInteger; Execute; ProviderName := 'pWaybillDet_UpdExIn'; end else ProviderName := 'pWaybillDet_InsIn'; FetchParams; if (FOrderID > 0) and NewRecord then FPosID := mdDet.FieldByName('posid').AsInteger else FPosID := GetMaxID(dmData.SConnection, 'waybilldet', 'posid'); Params.ParamByName('posid').AsInteger := FPosID; if FPosID < 0 then raise Exception.Create(rs('fmWaybill', 'ErrorAddPos')); tmpid := Params.ParamByName('POSID').AsInteger; Params.ParamByName('wbillid').AsInteger := FID; Params.ParamByName('MATID').AsInteger := mdDet.fieldbyname('MATID').AsInteger; Params.ParamByName('WID').AsInteger := mdDet.fieldbyname('WID').AsInteger; Params.ParamByName('AMOUNT').AsFloat := RoundToA(strtofloat(mdDet.fieldbyname('AMOUNT').AsString), MatDisplayDigits); Params.ParamByName('onvalue').AsFloat := StrToFloat(mdDet.fieldbyname('onvalue').AsString); Params.ParamByName('PRICE').AsFloat := RoundToA(strtofloat(mdDet.fieldbyname('PRICE').AsString), -6); Params.ParamByName('baseprice').AsFloat := RoundToA(strtofloat(mdDet.fieldbyname('fullprice').AsString), -6); Params.ParamByName('DISCOUNT').DataType := ftFloat; Params.ParamByName('DISCOUNT').Clear; Params.ParamByName('NDS').AsFloat := StrToFloat(mdDet.FieldByName('nds').AsString); Params.ParamByName('CurrId').AsInteger := cbCurr.KeyValue; Params.ParamByName('OnDate').AsDateTime := edDate.Date + edTime.Time; Params.ParamByName('PTypeID').DataType := ftInteger; Params.ParamByName('PTypeID').Clear; Params.ParamByName('NUM').AsInteger := mdDet.RecNo; Params.ParamByName('total').AsFloat := 0; Execute;//Записываем очередную позицию //write s/n if not mdDet.fieldbyname('sn').IsNull then begin ProviderName := 'rSN_Ins'; FetchParams; Params.ParamByName('sid').AsInteger := GetMaxID(dmData.SConnection, 'serials', 'sid'); Params.ParamByName('posid').AsInteger := FPosID; Params.ParamByName('serialno').AsString := mdDet.fieldbyname('sn').AsString; Execute; end;//if ProviderName := 'pWaybillDetAP_Del'; // clear old positions in waybilldetaddprops FetchParams; Params.ParamByName('posid').AsInteger := FPosID; Execute; if (mdDet.FieldByName('producer').AsString <> '') or (mdDet.FieldByName('certnum').AsString <> '') or (mdDet.FieldByName('gtd').AsString <> '') or (mdDet.FieldByName('certdate').AsDateTime <> 0) then begin ProviderName := 'pWaybillDetAP_Ins'; FetchParams; Params.ParamByName('posid').AsInteger := FPosID; Params.ParamByName('producer').AsString := mdDet.FieldByName('producer').AsString; Params.ParamByName('certnum').AsString := mdDet.FieldByName('certnum').AsString; Params.ParamByName('gtd').AsString := mdDet.FieldByName('gtd').AsString; if mdDet.FieldByName('certdate').AsDateTime = 0 then begin Params.ParamByName('certdate').DataType := ftDateTime; Params.ParamByName('certdate').Clear; end else Params.ParamByName('certdate').AsDateTime := mdDet.FieldByName('certdate').AsDateTime; Params.ParamByName('cardid').DataType := ftInteger; Params.ParamByName('cardid').Clear; Execute; end; end // if mdDet.FieldByName('postype').AsInteger = 0 else begin ProviderName := 'pWaybillSvc_InsIn'; FetchParams; FPosID := GetMaxID(dmData.SConnection, 'waybillsvc', 'posid'); Params.ParamByName('posid').AsInteger := FPosID; Params.ParamByName('wbillid').AsInteger := FID; Params.ParamByName('svcid').AsInteger := mdDet.fieldbyname('matid').AsInteger; Params.ParamByName('amount').AsFloat := RoundToA(StrToFloat(mdDet.fieldbyname('amount').AsString), MatDisplayDigits); Params.ParamByName('price').AsFloat := StrToFloat(mdDet.fieldbyname('price').AsString); Params.ParamByName('norm').AsFloat := StrToFloat(mdDet.fieldbyname('norm').AsString); Params.ParamByName('discount').AsFloat := StrToFloat(mdDet.fieldbyname('discount').AsString); Params.ParamByName('nds').AsFloat := StrToFloat(mdDet.fieldbyname('NDS').AsString); Params.ParamByName('currid').AsInteger := cbCurr.KeyValue; Params.ParamByName('num').AsInteger := mdDet.RecNo; Params.ParamByName('svctoprice').AsInteger := mdDet.FieldByName('svctoprice').AsInteger; if not mdDet.FieldByName('personid').IsNull then Params.ParamByName('personid').AsInteger := mdDet.FieldByName('personid').AsInteger else begin Params.ParamByName('personid').DataType := ftInteger; Params.ParamByName('personid').Clear; end; Execute; end; mdDet.Next; end;//while not mdDet.Eof mdDet.GotoBookmark(BM); FreeBookmark(BM); mdDet.EnableControls; FPosModified := False; end; //if FPosModified if (FOrderID > 0) and NewRecord then begin ProviderName := 'pDocsRel_WB_Acc_Ins'; FetchParams; Params.ParamByName('wbillid').AsInteger := FID; Params.ParamByName('accid').AsInteger := FOrderID; Execute; ProviderName := 'pOrder_UpdStatus'; FetchParams; Params.ParamByName('wbillid').AsInteger := FOrderID; if chbPosting.Checked then Params.ParamByName('checked').AsInteger := 1 else Params.ParamByName('checked').AsInteger := 2; Execute; end; if FOrderID = 0 then begin if chbPosting.Checked then begin //Если документ проведён то //1)Удаление из оборотов //записываем позиции на склад ProviderName := 'pWMatTurn_Del'; FetchParams; Params.ParamByName('WBILLID').AsInteger := FID; Execute; //4)Запись в обороты ProviderName := 'pWMatTurn_Ins'; FetchParams; Params.ParamByName('WBILLID').AsInteger := FID; Execute; end // if chbPosting.Checked else begin //Если документ не проведён, то удаляем позиции со склада //1)Удаление из оборотов ProviderName := 'pWMatTurn_Del'; FetchParams; Params.ParamByName('WBILLID').AsInteger := FID; Execute; end;//else if chbPosting.Checked end // if FOrderID = 0 (no related order) else begin // have related order ProviderName := 'pWMatTurn_Upd'; FetchParams; Params.ParamByName('wbillid').AsInteger := FID; if chbPosting.Checked then Params.ParamByName('turntype').AsInteger := matTurnIn else Params.ParamByName('turntype').AsInteger := matTurnOrdered; Execute; end; if not NewRecord and (FContrDocID > 0) then begin ProviderName := 'pDocsRel_WB_Contr_Del'; FetchParams; Params.ParamByName('docid').AsInteger := FContrDocID; Params.ParamByName('wbillid').AsInteger := FID; Execute; end; if edContr.DocID > 0 then begin ProviderName := 'pDocsRel_WB_Contr_Ins'; FetchParams; Params.ParamByName('docid').AsInteger := edContr.DocID; Params.ParamByName('wbillid').AsInteger := FID; Execute; end; FModified := False; TrCommit; except on e:exception do begin TrRollback; raise; end; end; if chbPosting.Checked and (edContr.DocID > 0) then DoRecalcContract(dmData.SConnection, edContr.DocID); DoRecalcKASaldo(dmData.SConnection, edKAgent.KAID, edDate.Date, rs('fmWaybill', 'RecalcBallance')); if (FOrderID > 0) and NewRecord then begin SendMessage(MainHandle, WM_REFRESH, FOrderID, 0); RefreshFun('TfmWaybill', 0); end else SendMessage(MainHandle, WM_REFRESH, ID, 0); RefreshFun('TfmWMat', 0); RefreshFun('TfmPayDoc', 0); RefreshFun('TfmFinance', 0); {if RefreshAllClients then begin dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_WBIN); dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_WMAT); dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_KAGENTS); end; } finally Free; Screen.Cursor := crDefault; end; end;// with TClientDataSet.Create(nil) *) {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end;//FormCloseQuery //============================================================================================== (* procedure TWayBillInClass.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); var FPaySum: Extended; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.ActionListUpdate') else _udebug := nil;{$ENDIF} if (chbPay.Checked)and(not PayDocChecked) then begin try FPaySum := StrToFloat(edPaySumm.EditingText); except FPaySum := 0; end; end else begin FPaySum := 1; end; if edContr.Obj.DocID>0 then cbPayCurr.Enabled := false; if FGridRefresh then begin dbgWaybillDet.BeginUpdate; try GetSummAll; if (not PayDocChecked)and(chbPay.Checked)and(not FPaySummChange)and(dbgWaybillDet.Tag<>0) then begin edPaySumm.Tag := 1; edPaySumm.Value := roundtoa(ALLSUMM,-2); edPaySumm.Tag := 0; end; dbgWaybillDet.Tag := dbgWaybillDet.Tag+1; finally dbgWaybillDet.EndUpdate; end; end; //******************** //ssBevel10.Visible := colSummDef.Visible; lSummCurr.Visible := cbCurr.KeyValue <> BaseCurrID; //bvlCurrency.Visible := colSummDef.Visible; lTotalCurr.Visible := cbCurr.KeyValue <> BaseCurrID; //******************** aOk.Enabled := (Trim(edNum1.Text) <> '') and (edDate.Text <> '') and (edKAgent.KAID > 0) and (cbCurr.KeyValue > 0) and (not mdDet.IsEmpty) and ((chbPay.Checked and (FPaySum > 0) and (Trim(edPayNum.Editor.EditingText) <> '')) or not chbPay.Checked); aSelectAll.Enabled := not mdDet.IsEmpty; aApply.Enabled := aOk.Enabled and (FModified or FPosModified or FPayDocModified) and (FOrderID = 0); aCIns.Enabled := FOrderID = 0; itmAdd.Enabled := FOrderID = 0; aCDel.Enabled := not mdDet.IsEmpty and (FOrderID = 0); aCUpd.Enabled := not mdDet.IsEmpty and (dbgWaybillDet.SelectedCount = 1); //dbgWaybillDet.Enabled := not mdDet.IsEmpty; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aCDelExecute(Sender: TObject); var FItem: TListItem; i: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aCDelExecute') else _udebug := nil;{$ENDIF} //dbgWaybillDet.SetFocus; if ((dbgWaybillDet.SelectedCount = 1) and (mrYes <> ssMessageDlg(rs('Common', 'DelConfirm'), ssmtWarning, [ssmbYes, ssmbNo]))) or ((dbgWaybillDet.SelectedCount > 1) and (mrYes <> ssMessageDlg(Format(rs('Common', 'DelConfirmEx'), [dbgWaybillDet.SelectedCount]), ssmtWarning, [ssmbYes, ssmbNo]))) then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; Screen.Cursor := crSQLWait; mdDet.DisableControls; try for i := 0 to dbgWaybillDet.SelectedCount - 1 do begin if mdDet.Locate('posid', dbgWaybillDet.SelectedNodes[i].Values[colPosID.Index], []) then if ((mdDet.FindField('locked') <> nil) and (mdDet.FieldByName('locked').AsInteger <> 1)) or (mdDet.FindField('locked') = nil) then mdDet.Delete; end; LocateAfterDel; RecalcSvc; FGridRefresh := True; finally Screen.Cursor := crDefault; mdDet.EnableControls; SelectFocusedNode; RealignGrid; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aCUpdExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aCUpdExecute') else _udebug := nil;{$ENDIF} Screen.Cursor := crSQLWait; case mdDet.FieldByName('postype').AsInteger of 0: with TfrmEditPosition.Create(frmEditPosition) do try ParentNameEx := Self.ParentNameEx; OnDate := Self.OnDate; WID := lcbWH.WID; dbgWaybillDet.SetFocus; PosNDS := FVAT; NDSPayer := CurrEnt.NDSPayer; ParentHandle := Self.Handle; CurrID := cbCurr.KeyValue; Kurs := CurKurs; parentMdDet := mdDet; //Tag := integer(mdDet); CurrName := cdsCurr.fieldbyname('shortname').AsString; CurrDefName := BaseCurrName; CurrShortName := defCurrShortName; {if trim(stCurrShortName.Caption)='' then begin stCurrShortName.Caption := cdsCurr.fieldbyname('shortname').AsString; stCurrShortNameOutNds.Caption := cdsCurr.fieldbyname('shortname').AsString; end;} ByOrder := FOrderID > 0; id := mdDet.FieldByName('posid').AsInteger; Screen.Cursor := crDefault; ShowModal; finally Free; Screen.Cursor := crDefault; end;//try 1: with TfrmEditPositionSvc.Create(nil) do try ParentHandle := Self.Handle; ParentNameEx := Self.ParentNameEx; OnDate := Int(edDate.Date) + Frac(edTime.Time); FRateValue := Self.edRate.Value; CurrID := Self.cbCurr.KeyValue; mdDet := Self.mdDet; chbSvcToPrice.Enabled := True; PosNDS := StrToFloat(mdDet.fieldbyname('NDS').AsString); ID := Self.mdDet.FieldByName('posid').AsInteger; ShowModal; finally Free; Screen.Cursor := crDefault; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //Запись в mdDet NDS и Currid //============================================================================================== (* function TWayBillInClass.ChangeMats: boolean; var BM:TBookmark; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.ChangeMats') else _udebug := nil;{$ENDIF} Result := True; with mdDet do begin BM := GetBookmark; DisableControls; try try First; while not Eof do begin Edit; FieldByName('NDS').AsFloat := FVAT; FieldByName('CurrId').AsFloat := cbCurr.KeyValue; Post; Next; end;//while except Result := False; end; finally GotoBookmark(BM); FreeBookmark(BM); EnableControls; end; end;//while {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aAddKAExecute(Sender: TObject); var aid: integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aAddKAExecute') else _udebug := nil;{$ENDIF} if edContr.Editor.Focused then edContr.ShowRef else if lcbWH.Combo.Focused then lcbWH.ShowRef else if FCurrCtrl = lcbPersonName then begin try aid := lcbPersonName.KeyValue; except aid := 0; end; lcbPersonName.SetFocus; lcbPersonName.Tag := 1; ShowModalRef(Self, rtPersons, vtKAgent, 'TfmKAgent', Self.OnDate, aid); lcbPersonName.Tag := 0; end else if FCurrCtrl = lcbPayType then begin ShowFinance(Self, Date, 1); end else if FCurrCtrl = lcbCashDesks then begin try aid := lcbCashDesks.KeyValue; except aid := 0; end; lcbCashDesks.SetFocus; ShowModalRef(Self, rtCashDesks, vtCashDesks, 'TfmCashDesks', Self.OnDate, aid); end else if FCurrCtrl = lcbPayMPerson then begin try aid := lcbPayMPerson.KeyValue; except aid := 0; end; lcbPayMPerson.SetFocus; lcbPayMPerson.Tag := 1; ShowModalRef(Self, rtPersons, vtKAgent, 'TfmKAgent', Self.OnDate, aid); lcbPayMPerson.Tag := 0; end else if edKAgent.Editor.Focused then edKAgent.ShowRef; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.chbPayPropertiesChange(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.chbPayPropertiesChange') else _udebug := nil;{$ENDIF} // Заполнение полей if chbPay.Enabled then begin if (chbPay.Checked)then begin if PDOutAutoNum and (OldPayDocID = 0) then begin FCurrPayNum := GetDocNum(dmData.SConnection,dtPDOut,1); edPayNum.Text := PDOutPrefix+IntToStr(FCurrPayNum)+PDOutSuffix; end else edPayNum.Text := FPayNum; edPaySumm.Tag := 1; edPaySumm.Value := roundtoa(AllSummCurr, -2); edPaySumm.Tag := 0; //cbPayCurr.KeyValue := BaseCurrID; end//if (chbPay.Checked) else begin if PDOutAutoNum and (OldPayDocID = 0) then begin if GetDocNum(dmData.SConnection, dtPDOut, 0) = FCurrPayNum then GetDocNum(dmData.SConnection, dtPDOut, -1); end; edPayNum.Text := ''; edPaySumm.Tag := 1; edPaySumm.Value := 0; edPaySumm.EditText := ''; edPaySumm.Tag := 0; //cbPayCurr.KeyValue := BaseCurrID; FPaySummChange := false; end;//else FPayDocModified := true; end;//if chbPay.Enabled {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aAddMatExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aAddMatExecute') else _udebug := nil;{$ENDIF} Screen.Cursor := crSQLWait; with TfrmEditPosition.Create(frmEditPosition) do try ParentNameEx := Self.ParentNameEx; OnDate := edDate.Date + edTime.Time; WID := lcbWH.WID; PosNDS := FVAT; NDSPayer := CurrEnt.NDSPayer; ParentHandle := Self.Handle; CurrID := Self.cbCurr.KeyValue; Kurs := CurKurs; parentMdDet := mdDet; //Tag := integer(mdDet); ByOrder := FOrderID > 0; id := 0; CurrDefName := BaseCurrName; CurrShortName := defCurrShortName; CurrName := cdsCurr.fieldbyname('shortname').AsString; {if trim(stCurrShortName.Caption)='' then begin stCurrShortName.Caption := cdsCurr.fieldbyname('shortname').AsString; stCurrShortNameOutNds.Caption := cdsCurr.fieldbyname('shortname').AsString; end;//if } Screen.Cursor := crDefault; ShowModal; finally if not mdDet.IsEmpty then begin //dbgWaybillDet.Enabled := true; dbgWaybillDet.SetFocus; end; Free; Screen.Cursor := crDefault; end;//try {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aAddSvcExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aAddSvcExecute') else _udebug := nil;{$ENDIF} with TfrmEditPositionSvc.Create(nil) do try ParentHandle := Self.Handle; ParentNameEx := Self.ParentNameEx; OnDate := Int(edDate.Date) + Frac(edTime.Time); FRateValue := Self.edRate.Value; CurrID := Self.cbCurr.KeyValue; mdDet := Self.mdDet; PosNDS := NDS; chbSvcToPrice.Enabled := True; ShowModal; dbgWaybillDet.SetFocus; finally Free; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aAddMatListExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aAddMatListExecute') else _udebug := nil;{$ENDIF} DocInfo.CurrName := cbCurr.Text; DocInfo.CurrID := cbCurr.KeyValue; DocInfo.CurrRate := edRate.Value; //DocInfo.WID := DocInfo.OnDate := edDate.Date; if CurrEnt.NDSPayer then DocInfo.NDS := FVAT else DocInfo.NDS := 0; if (edKAgent.KAID <> 0) and (edKAgent.Obj.PTypeID > 0) then DocInfo.PTypeID := edKAgent.Obj.PTypeID else DocInfo.PTypeID := GetDefPriceType; ShowModalRef(Self, rtMat, vtMat, 'TfmMaterials', Self.OnDate, 0, Integer(@DocInfo)); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.FillMatsFromRef(DS: TssMemoryData); var FPosID: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.FillMatsFromRef') else _udebug := nil;{$ENDIF} with mdDet do begin if not mdDet.Active then mdDet.Open; DS.First; mdDet.DisableControls; while not DS.Eof do begin FPosID := dsNextPosID(mdDet); Append; FieldByName('posid').AsInteger := FPosID; FieldByName('matid').AsInteger := DS.FieldByName('matid').AsInteger; FieldByName('postype').AsInteger := DS.Tag; if DS.Tag = 1 then FieldByName('norm').AsFloat := 1; FieldByName('discount').AsFloat := 0; FieldByName('matname').AsString := DS.FieldByName('name').AsString; FieldByName('msrname').AsString := DS.FieldByName('msrname').AsString; FieldByName('artikul').AsString := DS.FieldByName('artikul').AsString; FieldByName('amount').AsFloat := DS.FieldByName('amount').AsFloat; FieldByName('price').AsFloat := DS.FieldByName('price').AsFloat; FieldByName('fullprice').AsFloat := DS.FieldByName('price').AsFloat; if CurrEnt.NDSPayer then FieldByName('nds').AsFloat := FVAT else FieldByName('nds').AsFloat := 0; FieldByName('currid').AsInteger := cbCurr.KeyValue; FieldByName('wid').AsInteger := lcbWH.WID; FieldByName('whname').AsString := lcbWH.Combo.Text; FieldByName('currname').AsString := cbCurr.Text; FieldByName('onvalue').AsFloat := edRate.Value; FieldByName('producer').AsString := DS.FieldByName('producer').AsString; FieldByName('barcode').AsString := DS.FieldByName('barcode').AsString; Post; UpdatePos; DS.Next; end; end; RecalcSvc; mdDet.EnableControls; FGridRefresh := True; dbgWaybillDet.Adjust(nil, [colPosType, colRecNo]); dbgWaybillDet.ClearSelection; if dbgWaybillDet.FocusedNode <> nil then dbgWaybillDet.FocusedNode.Selected := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* function TWayBillInClass.CreateByOrder(AID: Integer): Integer; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.CreateByOrder') else _udebug := nil;{$ENDIF} Result := 0; with newDataSet do try mdDet.Close; mdDet.Open; FOrderID := AID; ProviderName := 'pWaybill_Get'; FetchParams; Params.ParamByName('wbillid').AsInteger := AID; Open; edKAgent.OnChange := nil; edKAgent.KAID := FieldByName('kaid').AsInteger; edKAgent.OnChange := edKAgentChange; edKAgent.Enabled := False; edContr.Enabled := False; edReason.Text := rs('fmWaybill', 'ByOrder',1) + amountPrefix + FieldByName('num').AsString; edDate.Date := Self.OnDate; cbCurr.KeyValue := FieldByName('currid').AsInteger; if FieldByName('attnum').AsString <> '' then lcbWH.WID := FieldByName('attnum').AsInteger; edRate.Value := FieldByName('onvalue').AsFloat; Close; ProviderName := 'pDocsRel_WB_Contr_Get'; FetchParams; Params.ParamByName('wbillid').AsInteger := AID; Params.ParamByName('doctype').AsInteger := 8; Open; if not IsEmpty then begin edContr.DocID := FieldByName('rdocid').AsInteger; end; Close; ProviderName := prvDet; FetchParams; Params.ParamByName('wbillid').AsInteger := AID; Open; mdDet.LoadFromDataSet(Fields[0].DataSet); mdDet.First; while not mdDet.Eof do begin mdDet.Edit; mdDet.FieldByName('fullprice').AsFloat := mdDet.FieldByName('price').AsFloat; mdDet.Post; UpdatePos; mdDet.Next; end; mdDet.First; if not mdDet.IsEmpty then begin if dbgWaybillDet.FocusedNode = nil then dbgWaybillDet.FocusedAbsoluteIndex := 0; dbgWaybillDet.FocusedNode.Selected := True; end; Close; finally Free; end; cbCurr.Enabled := False; FRateChanged := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.aAddSvcListExecute(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.aAddSvcListExecute') else _udebug := nil;{$ENDIF} DocInfo.CurrName := cbCurr.Text; DocInfo.CurrID := cbCurr.KeyValue; DocInfo.CurrRate := edRate.Value; DocInfo.OnDate := edDate.Date; if CurrEnt.NDSPayer then DocInfo.NDS := FVAT else DocInfo.NDS := 0; if (edKAgent.KAID <> 0) and (edKAgent.Obj.PTypeID > 0) then DocInfo.PTypeID := edKAgent.Obj.PTypeID else DocInfo.PTypeID := GetDefPriceType; ShowModalRef(Self, rtServices, vtServices, 'TfmServices', Self.OnDate, 0, Integer(@DocInfo)); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.UpdatePos; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.UpdatePos') else _udebug := nil;{$ENDIF} inherited; with mdDet do begin if FieldByName('postype').AsInteger = 1 then begin if mdSvc.Locate('posid', FieldByName('posid').AsInteger, []) then mdSvc.Edit else mdSvc.Append; mdSvc.FieldByName('posid').AsInteger := FieldByName('posid').AsInteger; mdSvc.FieldByName('amount').AsFloat := FieldByName('amount').AsFloat; mdSvc.FieldByName('norm').AsFloat := FieldByName('norm').AsFloat; mdSvc.FieldByName('svctoprice').AsInteger := FieldByName('svctoprice').AsInteger; mdSvc.FieldByName('price').AsFloat := FieldByName('price').AsFloat; mdSvc.FieldByName('total').AsFloat := FieldByName('sumcurr').AsFloat; mdSvc.FieldByName('totalwithnds').AsFloat := FieldByName('sumwithnds').AsFloat; mdSvc.Post; RecalcSvc; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== (* procedure TWayBillInClass.RecalcSvc; var FTotAmount, FSvcSum: Extended; BM: TBookmark; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWayBillInClass.RecalcSvc') else _udebug := nil;{$ENDIF} FTotAmount := 0; with mdDet do try DisableControls; BM := mdDet.GetBookmark; First; while not Eof do begin if FieldByName('postype').AsInteger = 0 then FTotAmount := FTotAmount + FieldByName('amount').AsFloat * FieldByName('fullprice').AsFloat; Next; end; if FTotAmount = 0 then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; FSvcSum := GetDSSummCurr(mdSvc, 'total', 'svctoprice', 1); First; while not Eof do begin if FieldByName('postype').AsInteger = 0 then begin Edit; FieldByName('price').AsFloat := FieldByName('fullprice').AsFloat + FSvcSum {* FieldByName('amount').AsFloat} * FieldByName('fullprice').AsFloat / FTotAmount; Post; UpdatePos; end; Next; end; finally GotoBookmark(BM); FreeBookmark(BM); EnableControls; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; *) //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('WaybillInClass', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit GX_eQuoteSupport; interface uses Classes, StrUtils, SysUtils; procedure QuoteLines(Lines: TStrings; EndOfLine: string; IndentStart: Integer); procedure UnquoteLines(Lines: TStrings; IndentStart: Integer = 0); implementation uses GX_GenericUtils; function HasConcatOperators(s: string): Boolean; begin Result := Pos('+', s) <> 0; end; function HasComplexCode(s: string): Boolean; var i: Integer; begin Result := False; for i := 1 to Length(s) do begin if CharInSet(s[i], ['(', ')', '/', '{', '}']) then begin Result := True; Exit; end; end; end; function PosFirstNonSpace(s: string): Integer; var i: Integer; begin Result := 0; for i := 1 to Length(s) do if s[i] <> ' ' then begin Result := i; Exit; end; end; function EscapeQuotes(s: string): string; begin Result := StringReplace(s, '''', '''''', [rfReplaceAll]); end; function UnquoteLine(Input: string):string; var p: Integer; len: Integer; ch: Char; Output: string; LastStringEnd: Integer; function GetNextCh: Boolean; begin Result := True; if p > len then begin ch := #0; Result := False; end else begin ch := Input[p]; inc(p); end; end; function PeekNextCh: Char; begin if (p) > len then Result := #0 else Result := Input[p]; end; procedure GetBraceComment; begin repeat Output := Output + ch; until (ch = '}') or (not GetNextCh); end; procedure GetParenComment; begin repeat Output := Output + ch; until ((ch = '*') and (PeekNextCh = ')')) or (not GetNextCh); if ch = '*' then begin GetNextCh; Output := Output + ch; end; end; procedure GetSlashesComment; begin repeat Output := Output + ch; until (not GetNextCh); end; function GetString: Boolean; begin Result := False; if ch <> '''' then Exit; while GetNextCh do begin if ch = '''' then if PeekNextCh = '''' then GetNextCh else Break; Output := Output + ch; Result := True; end; end; procedure GetCodeString; begin Output := Output + ch; while GetNextCh do begin if ch = '''' then if PeekNextCh = '''' then GetNextCh else begin Output := Output + ch; Break; end; Output := Output + ch; end; end; procedure GetCode; var ParenCount: Integer; begin ParenCount := 0; while GetNextCh do case ch of '(': if PeekNextCh = '*' then GetParenComment else begin inc(ParenCount); Output := Output + ch; end; '{': GetBraceComment; '/': if PeekNextCh = '/' then GetSlashesComment; '''': if ParenCount > 0 then GetCodeString else Break; ')': begin if ParenCount > 0 then dec(ParenCount); Output := Output + ch; end else Output := Output + ch; end; end; begin Output := ''; p := 1; len := Length(Input); LastStringEnd := -1; while p <= len do begin GetCode; if GetString then LastStringEnd := Length(Output); end; // Trim off end of line code if LastStringEnd <> -1 then if (HasConcatOperators(Copy(Output, LastStringEnd+1, MaxInt))) and (not HasComplexCode(Copy(Output, LastStringEnd+1, MaxInt))) then Delete(Output, LastStringEnd+1, MaxInt); Result := TrimRight(Output); end; procedure QuoteLines(Lines: TStrings; EndOfLine: string; IndentStart: Integer); var i, p: Integer; Indent: Integer; begin Lines[0] := ''''+ TrimRight(Lines[0]) + EndOfLine; Indent := IndentStart; // Make sure quotes won't happen in the middle of some text for i := 1 to Lines.Count - 1 do begin p := PosFirstNonSpace(Lines[i]); if (p > 0) and (Indent > p) then Indent := p; end; // If lines are flush with margin, they probably need to be indented if Indent = 1 then for i := 1 to Lines.Count - 1 do Lines[i] := DupeString(' ', IndentStart-1) + '''' + EscapeQuotes(TrimRight(Lines[i])) + EndOfLine else for i := 1 to Lines.Count - 1 do if Lines[i] = '' then Lines[i] := DupeString(' ', Indent-1) + '''' + EndOfLine else Lines[i] := Copy(Lines[i], 1, Indent-1) + '''' + EscapeQuotes(Copy(TrimRight(Lines[i]), Indent, MaxInt)) + EndOfLine; end; procedure UnquoteLines(Lines: TStrings; IndentStart: Integer); var i, p: Integer; begin for i := 0 to Lines.Count - 1 do Lines[i] := UnquoteLine(TrimRight(Lines[i])); // Remove excessive indenting if IndentStart > 1 then begin for i := 1 to Lines.Count - 1 do begin p := PosFirstNonSpace(Lines[i]); if (p > 0) and (IndentStart > p) then IndentStart := p; end; for i := 1 to Lines.Count - 1 do Lines[i] := Copy(Lines[i], IndentStart, MaxInt); end; end; end.
unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ImgList, Vcl.StdCtrls, Vcl.CategoryButtons; type TForm2 = class(TForm) CategoryPanelGroup1: TCategoryPanelGroup; CategoryPanel1: TCategoryPanel; CategoryPanel2: TCategoryPanel; CategoryPanel3: TCategoryPanel; Button1: TButton; Button2: TButton; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; GridPanel1: TGridPanel; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; ImageList1: TImageList; btnAddCategory: TButton; btnListPanels: TButton; ListBox1: TListBox; CategoryButtons1: TCategoryButtons; CategoryButtons2: TCategoryButtons; procedure btnAddCategoryClick(Sender: TObject); procedure btnListPanelsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} { TForm2 } procedure TForm2.btnAddCategoryClick(Sender: TObject); var newPanel: TCategoryPanel; begin newPanel := CategoryPanelGroup1.CreatePanel(self) as TCategoryPanel; NewPanel.Caption := 'Dynamic Panel'; with TButton.Create(self) do begin Caption := 'New button'; Parent := NewPanel; SetBounds (10, 10, Width, Height); end; end; procedure TForm2.btnListPanelsClick(Sender: TObject); var I: Integer; begin ListBox1.Clear; ListBox1.Items.Add('[Controls]'); for I := 0 to CategoryPanelGroup1.ControlCount - 1 do ListBox1.Items.Add ( (CategoryPanelGroup1.Controls[I] as TCategoryPanel).Caption); ListBox1.Items.Add('[Panels]'); for I := 0 to CategoryPanelGroup1.Panels.Count - 1 do ListBox1.Items.Add ( TCategoryPanel(CategoryPanelGroup1.Panels[I]).Caption); end; end.
unit ProxyInit; interface procedure InitProxy; implementation uses Registry, SocketComp, windows, winsock; resourcestring KeyProxy = 'Software\Oceanus\Star Peace\Client\Proxy'; const CKeyAuthentication: array[boolean] of TSocksAuthentication = (saNoAuthentication, saUsernamePassword); CKeyAuthenticationW: array[TSocksAuthentication] of boolean = (true, false); procedure InitProxy; var reg : TRegistry; Temp: string; begin reg := TRegistry.Create; with Reg do try RootKey := HKEY_CURRENT_USER; if KeyExists(KeyProxy) and OpenKey(KeyProxy, false) then with GeneralSockInfo do try fVersion := svNoSocks; fAuthentication := CKeyAuthentication[ReadBool('Authentication')]; Temp := ReadString('Addr'); try fAddr := TInAddr(inet_addr(pchar(Temp))); if integer(fAddr)=-1 then fAddr := TCustomWinSocket.LookupName(Temp); if integer(fAddr) <> 0 then begin fPort := ReadInteger('Port'); fVersion := TSocksVersion(ReadInteger('Version')); if fAuthentication = saUsernamePassword then begin fUserID := ReadString('User'); fPassword := ReadString('Password'); end; end; except end; except end; finally free; end; end; initialization InitProxy; end.
unit Script.Interfaces; interface type IscriptLog = interface procedure Log(const aString: String); end;//IscriptLog TscriptTokenType = (script_ttUnknown, script_ttToken, script_ttString, script_ttEOF); IscriptParser = interface function Get_TokenType: TscriptTokenType; function Get_TokenString: String; function Get_CurrentLineNumber: Integer; procedure NextToken; {* - Выбрать следующий токен из входного потока. } property TokenType: TscriptTokenType read Get_TokenType; property TokenString: String read Get_TokenString; property CurrentLineNumber: Integer read Get_CurrentLineNumber; end;//IscriptParser IscriptCompileLog = interface(IscriptLog) end;//IscriptCompileLog IscriptRunLog = interface(IscriptLog) end;//IscriptRunLog implementation end.
unit ValidationRule; interface uses ValidationRuleIntf; type TValidationRule = class(TInterfacedObject, IValidationRule) private FValidateFunction: TValidateFunction; function GetValidateFunction: TValidateFunction; procedure SetValidateFunction(const Value: TValidateFunction); public function Valid: Boolean; property ValidateFunction: TValidateFunction read GetValidateFunction write SetValidateFunction; end; implementation function TValidationRule.GetValidateFunction: TValidateFunction; begin Result := FValidateFunction; end; procedure TValidationRule.SetValidateFunction(const Value: TValidateFunction); begin FValidateFunction := Value; end; function TValidationRule.Valid: Boolean; begin Result := True; if Assigned(FValidateFunction) then Result := FValidateFunction; end; end.
unit UnitCustomMessage; interface uses ToolsApi, Vcl.Graphics, Winapi.Windows; type TCustomMessage = class(TInterfacedObject, IOTACustomMessage, INTACustomDrawMessage) private FMsg: String; FFontName: String; FForeColour: TColor; FStyle: TFontStyles; FBackColour: TColor; FMessagePntr: Pointer; protected Procedure SetForeColour(iColour: TColor); function CalcRect(Canvas: TCanvas; MaxWidth: Integer; Wrap: Boolean): TRect; procedure Draw(Canvas: TCanvas; const Rect: TRect; Wrap: Boolean); function GetColumnNumber: Integer; function GetFileName: string; function GetLineNumber: Integer; function GetLineText: string; procedure ShowHelp; public Constructor Create(strMsg: String; FontName: String; ForeColour: TColor = clBlack; Style: TFontStyles = []; BackColour: TColor = clWindow); Property ForeColour: TColor Write SetForeColour; Property MessagePntr: Pointer Read FMessagePntr Write FMessagePntr; end; implementation uses System.SysUtils; { TCustomMessage } function TCustomMessage.CalcRect(Canvas: TCanvas; MaxWidth: Integer; Wrap: Boolean): TRect; begin Canvas.Font.Name := FFontName; Canvas.Font.Style := FStyle; Result := Canvas.ClipRect; Result.Bottom := Result.Top + Canvas.TextHeight('Wp'); Result.Right := Result.Left + Canvas.TextWidth(FMsg); end; constructor TCustomMessage.Create(strMsg, FontName: String; ForeColour: TColor; Style: TFontStyles; BackColour: TColor); const strValidChars: set of AnsiChar = [#10, #13, #32 .. #128]; Var i: Integer; iLength: Integer; begin SetLength(FMsg, Length(strMsg)); iLength := 0; for i := 1 to Length(strMsg) do begin if CharInSet(strMsg[i], strValidChars) then begin FMsg[iLength + 1] := strMsg[i]; Inc(iLength); end; end; SetLength(FMsg, iLength); FFontName := FontName; FForeColour := ForeColour; FStyle := Style; FBackColour := BackColour; FMessagePntr := Nil; end; procedure TCustomMessage.Draw(Canvas: TCanvas; const Rect: TRect; Wrap: Boolean); begin If Canvas.Brush.Color = clWindow Then Begin Canvas.Font.Color := FForeColour; Canvas.Brush.Color := FBackColour; Canvas.FillRect(Rect); End; Canvas.Font.Name := FFontName; Canvas.Font.Style := FStyle; Canvas.TextOut(Rect.Left, Rect.Top, FMsg); end; function TCustomMessage.GetColumnNumber: Integer; begin Result := 0; end; function TCustomMessage.GetFileName: string; begin Result := ''; end; function TCustomMessage.GetLineNumber: Integer; begin Result := 0; end; function TCustomMessage.GetLineText: string; begin Result := FMsg; end; procedure TCustomMessage.SetForeColour(iColour: TColor); begin end; procedure TCustomMessage.ShowHelp; begin end; end.
unit MFichas.Model.Usuario.TipoDeUsuario.Gerente; interface uses MFichas.Model.Usuario.Interfaces, MFichas.Controller.Usuario.Operacoes.Interfaces, MFichas.Controller.Types; type TModelUsuarioTipoDeUsuarioGerente = class(TInterfacedObject, iModelUsuarioMetodos) private [weak] FParent : iModelUsuario; FNextResponsibility: iModelUsuarioMetodos; FOperacoes : iControllerUsuarioOperacoes; constructor Create(AParent: iModelUsuario); procedure PedirSenha; public destructor Destroy; override; class function New(AParent: iModelUsuario): iModelUsuarioMetodos; function SetOperacoes(AOperacoes: iControllerUsuarioOperacoes): iModelUsuarioMetodos; function NextReponsibility(AValue: iModelUsuarioMetodos): iModelUsuarioMetodos; function LogoENomeDaFesta : iModelUsuarioMetodos; function AbrirCaixa : iModelUsuarioMetodos; function FecharCaixa : iModelUsuarioMetodos; function Suprimento : iModelUsuarioMetodos; function Sangria : iModelUsuarioMetodos; function CadastrarProdutos : iModelUsuarioMetodos; function CadastrarGrupos : iModelUsuarioMetodos; function CadastrarUsuarios : iModelUsuarioMetodos; function AcessarRelatorios : iModelUsuarioMetodos; function AcessarConfiguracoes : iModelUsuarioMetodos; function ExcluirProdutosPosImpressao: iModelUsuarioMetodos; function &End : iModelUsuario; end; implementation { TModelUsuarioTipoDeUsuarioGerente } function TModelUsuarioTipoDeUsuarioGerente.&End: iModelUsuario; begin Result := FParent; end; function TModelUsuarioTipoDeUsuarioGerente.AbrirCaixa: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.AcessarConfiguracoes: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.AcessarRelatorios: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.CadastrarGrupos: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.CadastrarProdutos: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.CadastrarUsuarios: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; constructor TModelUsuarioTipoDeUsuarioGerente.Create(AParent: iModelUsuario); begin FParent := AParent; end; destructor TModelUsuarioTipoDeUsuarioGerente.Destroy; begin inherited; end; function TModelUsuarioTipoDeUsuarioGerente.ExcluirProdutosPosImpressao: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.FecharCaixa: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.LogoENomeDaFesta: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; class function TModelUsuarioTipoDeUsuarioGerente.New(AParent: iModelUsuario): iModelUsuarioMetodos; begin Result := Self.Create(AParent); end; function TModelUsuarioTipoDeUsuarioGerente.NextReponsibility( AValue: iModelUsuarioMetodos): iModelUsuarioMetodos; begin Result := Self; FNextResponsibility := AValue; end; procedure TModelUsuarioTipoDeUsuarioGerente.PedirSenha; begin FOperacoes .PedirSenha .SetTitle('Entre com a senha de PROPRIETÁRIO') .SetTextConfirm('Confirmar') .SetTextCancel('Cancelar') .SetChamada(tuGerente) .&End; end; function TModelUsuarioTipoDeUsuarioGerente.Sangria: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; function TModelUsuarioTipoDeUsuarioGerente.SetOperacoes( AOperacoes: iControllerUsuarioOperacoes): iModelUsuarioMetodos; begin Result := Self; FOperacoes := AOperacoes; end; function TModelUsuarioTipoDeUsuarioGerente.Suprimento: iModelUsuarioMetodos; begin Result := Self; PedirSenha; end; end.
unit ddTiffProcessor; { $Id: ddTiffProcessor.pas,v 1.2 2014/08/01 11:15:13 fireton Exp $ } interface uses Classes, l3Interfaces, l3BaseStream, l3ProtoObject, l3DataPtrList, l3Except; type TddTIFFHeader = packed record rOrder : Word; rID : Word; rFirstIFD : LongWord; end; PddTIFFTag = ^TddTIFFTag; TddTIFFTag = packed record rTag : Word; rType : Word; rCount : LongWord; rValue : LongWord; end; PddTagArray = ^TddTagArray; TddTagArray = array[0..MaxInt div 16] of TddTIFFTag; PddIFD = ^TddIFD; TddIFD = packed record rTagCount: Word; rTags : PddTagArray; rNextIFD : LongWord; end; type TddTiffProcessor = class(Tl3ProtoObject) private f_Header: TddTIFFHeader; f_IFDList: Tl3DataPtrList; f_IsLittleEndian: Boolean; f_Stream: Tl3Stream; f_StreamBase: Int64; procedure FreeIFD(aIFD: PddIFD); function CloneIFD(const aIFD: PddIFD): PddIFD; function FindTag(aIFD: PddIFD; aTagID: Word): PddTIFFTag; procedure ReadHeader; function N(const aWord: Word): Word; overload; function N(const aLongWord: LongWord): LongWord; overload; function pm_GetPageCount: Integer; procedure PutIFDDataToStream(aIFD: PddIFD; const aOutStream: TStream; aBasePos: Int64); procedure PutIFDToStream(aIFD: PddIFD; const aOutStream: TStream; aBasePos: Int64; var theNextIFDLinkPos: LongWord); procedure ReadFileDirectories; function ReadIFD: PddIFD; protected procedure Cleanup; override; public constructor Create(aStream: Tl3Stream); overload; constructor Create(aFileName: AnsiString); overload; procedure ExtractPages(const aOutStream: TStream; aPages: array of Integer); overload; procedure ExtractPages(const aOutFileName: AnsiString; aPages: array of Integer); overload; procedure ExtractPages(const aOutFileName: AnsiString; aRM: Il3RangeManager); overload; property PageCount: Integer read pm_GetPageCount; end; type EddTIFFError = class(El3Error); function EnumPagesInTIFF(aStream: TStream): Integer; overload; function EnumPagesInTIFF(aFileName: AnsiString): Integer; overload; implementation uses SysUtils, l3Types, l3Base, l3Stream; const cs_InvalidTIFF = 'Невалидный файл TIFF'; cs_CorruptedTIFF = 'Файл TIFF испорчен'; const // 1 2 3 4 5 6 7 8 9 10 11 12 cDataSize: array[1..12] of Integer = (1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8); // длины разных типов данных в тегах const ttStripOffsets = 273; ttStripByteCounts = 279; ttTileOffsets = 324; ttTileByteCounts = 325; const dtSHORT = 3; dtLONG = 4; type PLongWordArray = ^TLongWordArray; TLongWordArray = array[0..MaxInt div 16] of LongWord; function SwapWord(aWord: Word):Word; assembler; asm ror ax,8 end; function SwapDWord(aDWord:LongWord):LongWord; begin asm mov EAX, aDWord bswap EAX mov @result,EAX end; end; function _NW(const aWord: Word; aSwap: Boolean): Word; begin if aSwap then Result := SwapWord(aWord) else Result := aWord; end; function _NLW(const aLongWord: LongWord; aSwap: Boolean): LongWord; begin if aSwap then Result := SwapDWord(aLongWord) else Result := aLongWord; end; constructor TddTiffProcessor.Create(aStream: Tl3Stream); begin inherited Create; f_IFDList := Tl3DataPtrList.Make; f_Stream := aStream.Use; f_StreamBase := aStream.Position; ReadHeader; ReadFileDirectories; end; constructor TddTiffProcessor.Create(aFileName: AnsiString); var l_FS: Tl3FileStream; begin l_FS := Tl3FileStream.Create(aFileName, l3_fmRead); try Create(l_FS); finally FreeAndNil(l_FS); end; end; procedure TddTiffProcessor.Cleanup; var I: Integer; begin for I := 0 to Pred(f_IFDList.Count) do FreeIFD(f_IFDList[I]); FreeAndNil(f_IFDList); FreeAndNil(f_Stream); inherited; end; function TddTiffProcessor.CloneIFD(const aIFD: PddIFD): PddIFD; var l_Size: LongWord; begin l3System.GetLocalMem(Result, SizeOf(TddIFD)); l3FillChar(Result^, SizeOf(TddIFD)); Result^.rTagCount := aIFD^.rTagCount; l_Size := N(aIFD^.rTagCount) * SizeOf(TddTIFFTag); l3System.GetLocalMem(Result^.rTags, l_Size); l3Move(aIFD^.rTags^, Result^.rTags^, l_Size); Result^.rNextIFD := aIFD^.rNextIFD; end; procedure TddTiffProcessor.ExtractPages(const aOutStream: TStream; aPages: array of Integer); var I: Integer; l_NextIFDLinkPos: LongWord; l_OBase: Int64; l_WIFD: PddIFD; const cZero: LongWord = 0; begin l_OBase := aOutStream.Position; aOutStream.Write(f_Header, SizeOf(TddTIFFHeader)); l_NextIFDLinkPos := SizeOf(TddTIFFHeader) - 4; for I := 0 to High(aPages) do begin l_WIFD := CloneIFD(f_IFDList[aPages[I]]); try PutIFDDataToStream(l_WIFD, aOutStream, l_OBase); PutIFDToStream(l_WIFD, aOutStream, l_OBase, l_NextIFDLinkPos); finally FreeIFD(l_WIFD); end; end; // теперь надо записать 4 нуля - обязательных после последнего IFD aOutStream.Write(cZero, 4); end; procedure TddTiffProcessor.ExtractPages(const aOutFileName: AnsiString; aPages: array of Integer); var l_FS: Tl3FileStream; begin l_FS := Tl3FileStream.Create(aOutFileName, l3_fmWrite); try ExtractPages(l_FS, aPages); finally FreeAndNil(l_FS); end; end; procedure TddTiffProcessor.ExtractPages(const aOutFileName: AnsiString; aRM: Il3RangeManager); var l_Arr: array of Integer; I: Integer; begin SetLength(l_Arr, aRM.Count); for I := 1 to aRM.Count do l_Arr[I-1] := aRM.Pages[I] - 1; // в TIFF страницы нумеруются с 0 ExtractPages(aOutFileName, l_Arr); end; function TddTiffProcessor.FindTag(aIFD: PddIFD; aTagID: Word): PddTIFFTag; var I: Integer; l_MaxN: Integer; begin Result := nil; l_MaxN := N(aIFD^.rTagCount) - 1; for I := 0 to l_MaxN do if N(aIFD^.rTags^[I].rTag) = aTagID then begin Result := @(aIFD^.rTags^[I]); Break; end; end; procedure TddTiffProcessor.FreeIFD(aIFD: PddIFD); begin if aIFD^.rTags <> nil then l3System.FreeLocalMem(aIFD^.rTags); l3System.FreeLocalMem(aIFD); end; function TddTiffProcessor.N(const aWord: Word): Word; begin Result := _NW(aWord, not f_IsLittleEndian); end; function TddTiffProcessor.N(const aLongWord: LongWord): LongWord; begin Result := _NLW(aLongWord, not f_IsLittleEndian); end; function TddTiffProcessor.pm_GetPageCount: Integer; begin Result := f_IFDList.Count; end; procedure TddTiffProcessor.PutIFDDataToStream(aIFD: PddIFD; const aOutStream: TStream; aBasePos: Int64); var I: Integer; l_Count: Integer; l_DataPos: LongWord; l_DSize: LongWord; l_Type: Word; l_DLen: Word; l_Buf: Pointer; l_Chunk: LongWord; l_PicOffsets: Pointer; l_PicOffsetsLen: LongWord; l_IDataTag: Word; l_Tag: Word; const cBufSize = 1024 * 100; // 100 кб function ReadTagData(const aTag: PddTIFFTag; var theDataType: Word; var theLen: Longword): Pointer; begin theDataType := N(aTag^.rType); theLen := N(aTag^.rCount) * cDataSize[theDataType]; l3System.GetLocalMem(Result, theLen); if theLen > 4 then begin f_Stream.Seek(f_StreamBase + N(aTag^.rValue), soFromBeginning); f_Stream.Read(Result^, theLen); end else l3Move(aTag^.rValue, Result^, theLen); end; procedure CopyImageData; var I: Integer; l_DataLenTag: PddTIFFTag; l_DataTag: PddTIFFTag; l_DataType: Word; l_PicLens: Pointer; l_DataLenType: Word; l_TmpLW: LongWord; l_TmpW: LongWord; l_NumOfChunks: Integer; l_Pos: Longword; l_Len: LongWord; l_CLen: LongWord; begin // ищем в исходном файле данные изображения и копируем их в целевой файл, попутно готовя файлы для тега // данных изображения l_DataTag := FindTag(aIFD, ttStripOffsets); if l_DataTag = nil then l_DataTag := FindTag(aIFD, ttTileOffsets); if l_DataTag = nil then raise EddTIFFError.Create(cs_CorruptedTIFF); l_IDataTag := N(l_DataTag^.rTag); if l_IDataTag = ttStripOffsets then l_DataLenTag := FindTag(aIFD, ttStripByteCounts) else l_DataLenTag := FindTag(aIFD, ttTileByteCounts); if l_DataLenTag = nil then raise EddTIFFError.Create(cs_CorruptedTIFF); l_PicOffsets := ReadTagData(l_DataTag, l_DataType, l_PicOffsetsLen); l_PicLens := ReadTagData(l_DataLenTag, l_DataLenType, l_TmpLW); try l_NumOfChunks := l_PicOffsetsLen div cDataSize[l_DataType]; for I := 0 to l_NumOfChunks-1 do begin if l_DataType = dtSHORT then l_Pos := N(PWordArray(l_PicOffsets)^[I]) else l_Pos := N(PLongWordArray(l_PicOffsets)^[I]); if l_DataLenType = dtSHORT then l_Len := N(PWordArray(l_PicLens)^[I]) else l_Len := N(PLongWordArray(l_PicLens)^[I]); // запоминаем позицию в новом файле как позицию куска данных для тега if l_DataType = dtSHORT then begin l_TmpW := aOutStream.Position - aBasePos; PWordArray(l_PicOffsets)^[I] := N(l_TmpW) end else begin l_TmpLW := aOutStream.Position - aBasePos; PLongWordArray(l_PicOffsets)^[I] := N(l_TmpLW); end; f_Stream.Seek(f_StreamBase + l_Pos, soFromBeginning); while l_Len > 0 do begin if l_Len > cBufSize then l_CLen := cBufSize else l_CLen := l_Len; f_Stream.Read(l_Buf^, l_CLen); aOutStream.Write(l_Buf^, l_CLen); l_Len := l_Len - l_CLen; end; end; finally l3System.FreeLocalMem(l_PicLens); end; end; begin l_Count := N(aIFD^.rTagCount); l3System.GetLocalMem(l_Buf, cBufSize); try CopyImageData; try for I := 0 to Pred(l_Count) do begin l_Tag := N(aIFD^.rTags^[I].rTag); if l_Tag = l_IDataTag then // это тег со смещениями данных в файле, с ним надо обращаться особо begin if l_PicOffsetsLen > 4 then begin l_DataPos := aOutStream.Position - aBasePos; // запоминаем позицию данных в целевом файле, чтобы потом записать в тег aOutStream.Write(l_PicOffsets^, l_PicOffsetsLen); aIFD^.rTags^[I].rValue := N(l_DataPos); // записываем позицию данных в новом файле в тег end else l3Move(l_PicOffsets^, aIFD^.rTags^[I].rValue, l_PicOffsetsLen); end else begin l_Type := N(aIFD^.rTags^[I].rType); if (l_Type <= 12) and (l_Type > 0) then l_DLen := cDataSize[l_Type] else l_DLen := 1; // для неизвестных типов данных длина одного элемента - 1 байт l_DSize := N(aIFD^.rTags^[I].rCount) * l_DLen; // вычисляем общую длину данных if l_DSize <= 4 then // если общая длина данных укладывается в 4 байта - то данные содержатся в самом теге Continue; // значит, можно их не переносить в файл, вернее, они запишутся позже, вместе с IFD // данные в файле, начинаем перенос l_DataPos := aOutStream.Position - aBasePos; // запоминаем позицию данных в целевом файле, чтобы потом записать в тег f_Stream.Seek(f_StreamBase + N(aIFD^.rTags^[I].rValue), soFromBeginning); while l_DSize > 0 do begin if l_DSize > cBufSize then l_Chunk := cBufSize else l_Chunk := l_DSize; f_Stream.Read(l_Buf^, l_Chunk); aOutStream.Write(l_Buf^, l_Chunk); l_DSize := l_DSize - l_Chunk; end; aIFD^.rTags^[I].rValue := N(l_DataPos); // записываем позицию данных в новом файле в тег end; end; finally l3System.FreeLocalMem(l_PicOffsets); end; finally l3System.FreeLocalMem(l_Buf); end; end; procedure TddTiffProcessor.PutIFDToStream(aIFD: PddIFD; const aOutStream: TStream; aBasePos: Int64; var theNextIFDLinkPos: LongWord); const cZeroLongWord: LongWord = 0; var l_Count: Word; l_NewIFDPos: LongWord; l_Temp: LongWord; begin // выравниваем позицию в целевом файле по word boundary if (aOutStream.Position - aBasePos) and 1 = 1 then aOutStream.Write(cZeroLongWord, 1); l_NewIFDPos := aOutStream.Position - aBasePos; // позиция нового IFD, чтобы прилинковать к предыдущему aOutStream.Seek(aBasePos + theNextIFDLinkPos, soFromBeginning); // линкуем к предыдущему l_Temp := N(l_NewIFDPos); aOutStream.Write(l_Temp, 4); aOutStream.Seek(aBasePos + l_NewIFDPos, soFromBeginning); // возвращаемся назад и пишем IFD aOutStream.Write(aIFD^.rTagCount, SizeOf(Word)); aOutStream.Write(aIFD^.rTags^, SizeOf(TddTIFFTag) * N(aIFD^.rTagCount)); aOutStream.Write(cZeroLongWord, 4); // в линк на следующий пишем пока нули theNextIFDLinkPos := aOutStream.Position - aBasePos - 4; // вычисляем новую позицию для линка end; procedure TddTiffProcessor.ReadFileDirectories; var l_IFD: PddIFD; l_SPos: LongWord; begin l_SPos := N(f_Header.rFirstIFD); while l_SPos <> 0 do begin f_Stream.Seek(f_StreamBase + l_SPos, soFromBeginning); l_IFD := ReadIFD; if l_IFD = nil then raise EddTIFFError.Create(cs_CorruptedTIFF); f_IFDList.Add(l_IFD); l_SPos := N(l_IFD^.rNextIFD); end; end; procedure TddTiffProcessor.ReadHeader; begin f_Stream.Read(f_Header, SizeOf(TddTIFFHeader)); if (f_Header.rOrder <> $4949) and (f_Header.rOrder <> $4D4D) then raise EddTIFFError.Create(cs_InvalidTIFF); f_IsLittleEndian := f_Header.rOrder = $4949; if N(f_Header.rID) <> 42 then raise EddTIFFError.Create(cs_InvalidTIFF); end; function TddTiffProcessor.ReadIFD: PddIFD; var l_Count: Word; begin l3System.GetLocalMem(Result, SizeOf(TddIFD)); try l3FillChar(Result^, SizeOf(TddIFD)); f_Stream.Read(Result^.rTagCount, SizeOf(Word)); l_Count := N(Result^.rTagCount); l3System.GetLocalMem(Result^.rTags, SizeOf(TddTIFFTag) * l_Count); f_Stream.Read(Result^.rTags^, SizeOf(TddTIFFTag) * l_Count); f_Stream.Read(Result^.rNextIFD, SizeOf(LongWord)); except FreeIFD(Result); Result := nil; end; end; function EnumPagesInTIFF(aStream: TStream): Integer; var l_Header: TddTIFFHeader; l_IsBigEndian: Boolean; l_Pos: LongWord; l_StreamBase: Int64; l_TagCount: Word; begin Result := 0; l_StreamBase := aStream.Position; try aStream.Read(l_Header, SizeOf(TddTIFFHeader)); if (l_Header.rOrder <> $4949) and (l_Header.rOrder <> $4D4D) then Exit; l_IsBigEndian := l_Header.rOrder = $4D4D; if _NW(l_Header.rID, l_IsBigEndian) <> 42 then Exit; l_Pos := _NLW(l_Header.rFirstIFD, l_IsBigEndian); // получаем из заголовка смещение первого IFD while l_Pos <> 0 do begin Inc(Result); aStream.Seek(l_StreamBase + l_Pos, soFromBeginning); // переходим на позицию очередного IFD aStream.Read(l_TagCount, SizeOf(Word)); // пропускаем теги aStream.Seek(_NW(l_TagCount, l_IsBigEndian) * SizeOf(TddTIFFTag), soFromCurrent); aStream.Read(l_Pos, SizeOf(LongWord)); // читаем позицию следующего IFD l_Pos := _NLW(l_Pos, l_IsBigEndian); end; finally aStream.Seek(l_StreamBase, soFromBeginning); // возвращаем поток в исходное состояние end; end; function EnumPagesInTIFF(aFileName: AnsiString): Integer; var l_FS: Tl3FileStream; begin l_FS := Tl3FileStream.Create(aFileName, l3_fmRead); try Result := EnumPagesInTIFF(l_FS); finally FreeAndNil(l_FS); end; end; end.
unit Model.CadastroGeral; interface uses Common.ENum, FireDAC.Comp.Client, DAO.Conexao, Control.Sistema, FireDAC.Stan.Option, System.SysUtils; type TCadastroGeral= class private FAcao: TAcao; FNomePai: String; FDataRG: TDate; FNaturalidade: String; FRG: String; FNascimento: TDate; FEstadoCivil: String; FValidadeCNH: TDate; FUFNaturalidade: String; FUFRG: String; FCPF: String; FRegistroCNH: String; FID: Integer; FImagem: String; FUFCNH: String; FPrimeiraCNH: TDate; FDataCadastro: TDateTime; FNomeMae: String; FUsuario: Integer; FSexo: SmallInt; FNome: String; FCategoriaCNH: String; FNumeroCNH: String; FCodigoSegurancaCNH: String; FExpedidor: String; FDataEmissaoCNH: TDate; FConexao: TConexao; FCNAE: String; FPessoa: SmallInt; FSuframa: String; FAlias: String; FTipoCadastro: Integer; FCRT: Integer; FObs: String; FNacionalidade: String; FStatus: Integer; FIEST: String; FInscricaoMunicipal: String; FQuery: TFDQuery; FNomeTabela: String; function Inserir(): Boolean; function Alterar(): Boolean; function Excluir(): Boolean; public Constructor Create(); property ID: Integer read FID write FID; property TipoCadastro: Integer read FTipoCadastro write FTipoCadastro; property Pessoa: SmallInt read FPessoa write FPessoa; property Nome: String read FNome write FNome; property Alias: String read FAlias write FAlias; property CPF: String read FCPF write FCPF; property RG: String read FRG write FRG; property Expedidor: String read FExpedidor write FExpedidor; property DataRG: TDate read FDataRG write FDataRG; property UFRG: String read FUFRG write FUFRG; property Nascimento: TDate read FNascimento write FNascimento; property NomePai: String read FNomePai write FNomePai; property NomeMae: String read FNomeMae write FNomeMae; property Nacionalidade: String read FNacionalidade write FNacionalidade; property Naturalidade: String read FNaturalidade write FNaturalidade; property UFNaturalidade: String read FUFNaturalidade write FNaturalidade; property Suframa: String read FSuframa write FSuframa; property CNAE: String read FCNAE write FCNAE; property CRT: Integer read FCRT write FCRT; property CodigoSegurancaCNH: String read FCodigoSegurancaCNH write FCodigoSegurancaCNH; property NumeroCNH: String read FNumeroCNH write FNumeroCNH; property RegistroCNH: String read FRegistroCNH write FRegistroCNH; property ValidadeCNH: TDate read FValidadeCNH write FValidadeCNH; property CategoriaCNH: String read FCategoriaCNH write FCategoriaCNH; property DataEmissaoCNH: TDate read FDataEmissaoCNH write FDataEmissaoCNH; property PrimeiraCNH: TDate read FPrimeiraCNH write FPrimeiraCNH; property UFCNH: String read FUFCNH write FUFCNH; property Sexo: SmallInt read FSexo write FSexo; property EstadoCivil: String read FEstadoCivil write FEstadoCivil; property DataCadastro: TDateTime read FDataCadastro write FDataCadastro; property Usuario: Integer read FUsuario write FUsuario; property Imagem: String read FImagem write FImagem; property Status: Integer read FStatus write FStatus; property Obs: String read FObs write FObs; property InscricaoMunicipal: String read FInscricaoMunicipal write FInscricaoMunicipal; property IEST: String read FIEST write FIEST; property Query: TFDQuery read FQuery write FQuery; property NomeTabela: String read FNomeTabela write FNomeTabela; property Acao: TAcao read FAcao write FAcao; function GetID(): Integer; function Localizar(aParam: array of variant): Boolean; function Gravar(): Boolean; procedure SetupClass(FDquery: TFDQuery); procedure ClearClass; end; const TABLENAME = 'cadastro_geral'; SQLINSERT = 'insert into ' + TABLENAME + '(id_cadastro, cod_tipo_cadastro, cod_pessoa, nom_nome_razao, nom_fantasia, num_cpf_cnpj, num_rg_ie, ' + 'des_expedidor, dat_emissao_rg, uf_expedidor_rg, dat_nascimento, nom_pai, nom_mae, des_nacionalidade, ' + 'des_naturalidade, uf_naturalidade, num_suframa, num_cnae, num_crt, cod_seguranca_cnh, cod_cnh, ' + 'num_registro_cnh, dat_validade_cnh, des_categoria, dat_emissao_cnh, dat_primeira_cnh, uf_cnh, cod_sexo, ' + 'des_estado_civil, dat_cadastro, cod_usuario, des_imagem, id_status, des_obs, num_im, num_iest) ' + 'values ' + '(:id_cadastro, :cod_tipo_cadastro, :cod_pessoa, :nom_nome_razao, :nom_fantasia, :num_cpf_cnpj, :num_rg_ie, ' + ':des_expedidor, :dat_emissao_rg, :uf_expedidor_rg, :dat_nascimento, :nom_pai, :nom_mae, :des_nacionalidade, ' + ':des_naturalidade, :uf_naturalidade, :num_suframa, :num_cnae, :num_crt, :cod_seguranca_cnh, :cod_cnh, ' + ':num_registro_cnh, :dat_validade_cnh, :des_categoria, :dat_emissao_cnh, :dat_primeira_cnh, :uf_cnh, :cod_sexo, ' + ':des_estado_civil, :dat_cadastro, :cod_usuario, :des_imagem, :id_status, :des_obs, :num_im, :num_iest);'; SQLUPDATE = 'update ' + TABLENAME + ' set ' + 'cod_tipo_cadastro = :cod_tipo_cadastro, cod_pessoa = :cod_pessoa, nom_nome_razao = :nom_nome_razao, ' + 'nom_fantasia = :nom_fantasia, num_cpf_cnpj = :num_cpf_cnpj, num_rg_ie = :num_rg_ie, ' + 'des_expedidor = :des_expedidor, dat_emissao_rg = :dat_emissao_rg, uf_expedidor_rg = :uf_expedidor_rg, ' + 'dat_nascimento = :dat_nascimento, nom_pai = :nom_pai, nom_mae = :nom_mae, ' + 'des_nacionalidade = :des_nacionalidade, des_naturalidade = :des_naturalidade, ' + 'uf_naturalidade = :uf_naturalidade, num_suframa = :num_suframa, num_cnae = :num_cnae, num_crt = :num_crt, ' + 'cod_seguranca_cnh = :cod_seguranca_cnh, cod_cnh = :cod_cnh, num_registro_cnh = :num_registro_cnh, ' + 'dat_validade_cnh + :dat_validade_cnh, des_categoria = :des_categoria, dat_emissao_cnh = :dat_emissao_cnh, ' + 'dat_primeira_cnh = :dat_primeira_cnh, uf_cnh = :uf_cnh, cod_sexo = :cod_sexo, ' + 'des_estado_civil = :des_estado_civil, dat_cadastro = :dat_cadastro, cod_usuario = :cod_usuario, ' + 'des_imagem + :des_imagem, id_status = :id_status, des_obs = :des_obs ' + 'num_im = :num_im, num_iest = :num_iest ' + 'where ' + 'id_cadastro = :id_cadastro'; SQLQUERY = 'select ' + 'id_cadastro, cod_tipo_cadastro, cod_pessoa, nom_nome_razao, nom_fantasia, num_cpf_cnpj, num_rg_ie, ' + 'des_expedidor, dat_emissao_rg, uf_expedidor_rg, dat_nascimento, nom_pai, nom_mae, des_nacionalidade, ' + 'des_naturalidade, uf_naturalidade, num_suframa, num_cnae, num_crt, cod_seguranca_cnh, cod_cnh, ' + 'num_registro_cnh, dat_validade_cnh, des_categoria, dat_emissao_cnh, dat_primeira_cnh, uf_cnh, cod_sexo, ' + 'des_estado_civil, dat_cadastro, cod_usuario, des_imagem, id_status, des_obs, num_iest ' + 'from ' + TABLENAME + ';'; implementation { TCadastroGeral } function TCadastroGeral.Alterar: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLUPDATE, [Self.TipoCadastro, Self.Pessoa, Self.Nome, Self.Alias, Self.CPF, Self.RG, Self.Expedidor, Self.DataRG, Self.UFRG, Self.Nascimento, Self.NomePai, Self.NomeMae, Self.Nacionalidade, Self.Naturalidade, Self.UFNaturalidade, Self.Suframa, Self.CNAE, Self.CRT, Self.CodigoSegurancaCNH, Self.RegistroCNH, Self.ValidadeCNH, Self.CategoriaCNH, Self.DataEmissaoCNH, Self.PrimeiraCNH, Self.UFCNH, Self.Sexo, Self.EstadoCivil, Self.DataCadastro, Self.Usuario, Self.Imagem, Self.Status, Self.Obs, Self.InscricaoMunicipal, Self.IEST, Self.ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; procedure TCadastroGeral.ClearClass; begin FNomePai:= ''; FDataRG := StrToDate('31/12/1899'); FNaturalidade := ''; FRG := ''; FNascimento := StrToDate('31/12/1899'); FEstadoCivil := ''; FValidadeCNH := StrToDate('31/12/1899'); FUFNaturalidade := ''; FUFRG := ''; FCPF := ''; FRegistroCNH := ''; FID := 0; FImagem := ''; FUFCNH := ''; FPrimeiraCNH := StrToDate('31/12/1899'); FDataCadastro := StrToDate('31/12/1899'); FNomeMae := ''; FUsuario := 0; FSexo := 0; FNome := ''; FCategoriaCNH := ''; FNumeroCNH := ''; FCodigoSegurancaCNH := ''; FExpedidor := ''; FDataEmissaoCNH := StrToDate('31/12/1899'); FCNAE := ''; FPessoa := 0; FSuframa := ''; FAlias := ''; FTipoCadastro := 0; FCRT := 0; FObs := ''; FNacionalidade := ''; FStatus := 0; FIEST := ''; FInscricaoMunicipal := ''; end; constructor TCadastroGeral.Create; begin Fconexao := TConexao.Create; FNomeTabela := TABLENAME; end; function TCadastroGeral.Excluir: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_cadastro = :id_cadastro', [Self.ID]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TCadastroGeral.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_cadastro),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroGeral.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Self.Inserir(); tacAlterar: Result := Self.Alterar(); tacExcluir: Result := Self.Excluir(); end; end; function TCadastroGeral.Inserir: Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); Self.ID := GetId(); FDQuery.ExecSQL(SQLINSERT, [Self.ID, Self.TipoCadastro, Self.Pessoa, Self.Nome, Self.Alias, Self.CPF, Self.RG, Self.Expedidor, Self.DataRG, Self.UFRG, Self.Nascimento, Self.NomePai, Self.NomeMae, Self.Nacionalidade, Self.Naturalidade, Self.UFNaturalidade, Self.Suframa, Self.CNAE, Self.CRT, Self.CodigoSegurancaCNH, Self.RegistroCNH, Self.ValidadeCNH, Self.CategoriaCNH, Self.DataEmissaoCNH, Self.PrimeiraCNH, Self.UFCNH, Self.Sexo, Self.EstadoCivil, Self.DataCadastro, Self.Usuario, Self.Imagem, Self.Status, Self.Obs, Self.InscricaoMunicipal, Self.IEST]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroGeral.Localizar(aParam: array of variant): Boolean; var sfields: String; begin REsult := False; FQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FQuery.SQL.Clear; FQuery.SQL.Add(SQLQUERY); if aParam[0] = 'ID' then begin FQuery.SQL.Add('where id_cadastro = :id_cadastro'); FQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; end; if aParam[0] = 'RG' then begin FQuery.SQL.Add('where um_rg = :um_rg'); FQuery.ParamByName('um_rg').AsString := aParam[1]; end; if aParam[0] = 'CPFCNPJ' then begin FQuery.SQL.Add('where num_cpf = :num_cpf'); FQuery.ParamByName('num_cpf').AsString := aParam[1]; end; if aParam[0] = 'SEGCNH' then begin FQuery.SQL.Add('where cod_seguranca_cnh = :cod_seguranca_cnh'); FQuery.ParamByName('cod_seguranca_cnh').AsString := aParam[1]; end; if aParam[0] = 'REGISTROCNH' then begin FQuery.SQL.Add('where num_registro_cnh = :num_registro_cnh'); FQuery.ParamByName('num_registro_cnh').AsString := aParam[1]; end; if aParam[0] = 'NOME' then begin FQuery.SQL.Add('where nom_nome_razao LIKE :nom_nome_razao'); FQuery.ParamByName('nom_nome_razao').AsString := aParam[1]; end; if aParam[0] = 'ALIAS' then begin FQuery.SQL.Add('where nom_fantasia LIKE :nom_fantasia'); FQuery.ParamByName('nom_fantasia').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FQuery.SQL.Clear; FQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; if aParam[0] = 'MACRO' then begin if aParam[1] = '*' then begin sFields := 'id_cadastro, cod_tipo_cadastro, cod_pessoa, nom_nome_razao, nom_fantasia, num_cpf_cnpj, num_rg_ie, ' + 'des_expedidor, dat_emissao_rg, uf_expedidor_rg, dat_nascimento, nom_pai, nom_mae, des_nacionalidade, ' + 'des_naturalidade, uf_naturalidade, num_suframa, num_cnae, num_crt, cod_seguranca_cnh, cod_cnh, ' + 'num_registro_cnh, dat_validade_cnh, des_categoria, dat_emissao_cnh, dat_primeira_cnh, uf_cnh, cod_sexo, ' + 'des_estado_civil, dat_cadastro, cod_usuario, des_imagem, id_status, des_obs, num_iest'; end else begin sFields := aParam[1]; end; FQuery.SQL.Clear; FQuery.SQL.Add('select !colums from !table {if !where } where !where {fi}'); FQuery.MacroByName('colums').AsRaw := sFields; FQuery.MacroByName('table').AsRaw := TABLENAME; FQuery.MacroByName('where').AsRaw := aParam[2]; end; FQuery.Open(); if FQuery.IsEmpty then begin Exit; end; Result := True; end; procedure TCadastroGeral.SetupClass(FDquery: TFDQuery); begin FNomePai:= FDquery.FieldByName('nom_pai').AsString; FDataRG := FDquery.FieldByName('dat_emissao_rg').AsDateTime; FNaturalidade := FDquery.FieldByName('des_naturalidade').AsString; FRG := FDquery.FieldByName('num_rg_ie').AsString; FNascimento := FDquery.FieldByName('dat_nascimento').AsDateTime; FEstadoCivil := FDquery.FieldByName('des_estado_civil').AsString; FValidadeCNH := FDquery.FieldByName('dat_validade_cnh').AsDateTime; FUFNaturalidade := FDquery.FieldByName('uf_naturalidade').AsString; FUFRG := FDquery.FieldByName('uf_expedidor_rg').AsString; FCPF := FDquery.FieldByName('num_cpf_cnpj').AsString; FRegistroCNH := FDquery.FieldByName('num_registro_cnh').AsString; FID := FDquery.FieldByName('id_cadastro').AsInteger; FImagem := FDquery.FieldByName('des_imagem').AsString; FUFCNH := FDquery.FieldByName('uf_cnh').AsString; FPrimeiraCNH := FDquery.FieldByName('dat_primeira_cnh').AsDateTime; FDataCadastro := FDquery.FieldByName('dat_cadastro').AsDateTime; FNomeMae := FDquery.FieldByName('nom_mae').AsString; FUsuario := FDquery.FieldByName('cod_usuario').AsInteger; FSexo := FDquery.FieldByName('cod_sexo').AsInteger; FNome := FDquery.FieldByName('nom_nome_razao').AsString; FCategoriaCNH := FDquery.FieldByName('des_categoria').AsString; FNumeroCNH := FDquery.FieldByName('cod_cnh').AsString; FCodigoSegurancaCNH := FDquery.FieldByName('cod_seguranca_cnh').AsString; FExpedidor := FDquery.FieldByName('des_expedidor').AsString; FDataEmissaoCNH := FDquery.FieldByName('dat_emissao_cnh').AsDateTime; FCNAE := FDquery.FieldByName('num_cnae').AsString; FPessoa := FDquery.FieldByName('cod_pessoa').AsInteger; FSuframa := FDquery.FieldByName('num_suframa').AsString; FAlias := FDquery.FieldByName('nom_fantasia').AsString; FTipoCadastro := FDquery.FieldByName('cod_tipo_cadastro').AsInteger; FCRT := FDquery.FieldByName('num_crt').AsInteger; FObs := FDquery.FieldByName('des_obs').AsString; FNacionalidade := FDquery.FieldByName('des_nacionalidade').AsString; FStatus := FDquery.FieldByName('id_status').AsInteger; FIEST := FDquery.FieldByName('num_im').AsString; FInscricaoMunicipal := FDquery.FieldByName('num_iest').AsString; end; end.
unit BulkForwardGeocodeAddressesUnit; interface uses SysUtils, BaseExampleUnit, CommonTypesUnit, BulkGeocodingRequestUnit; type TBulkForwardGeocodeAddresses = class(TBaseExample) public procedure Execute(Addresses: TAddressInfoArray); end; implementation uses GeocodingUnit; procedure TBulkForwardGeocodeAddresses.Execute(Addresses: TAddressInfoArray); var ErrorString: String; Geocoding: TGeocodingList; i: integer; begin Geocoding := Route4MeManager.Geocoding.ForwardGeocodeAddresses( Addresses, ErrorString); try WriteLn(''); if (Geocoding.Count > 0) then begin WriteLn('BulkForwardGeocodeAddresses executed successfully'); for i := 0 to Geocoding.Count - 1 do if Geocoding[i].Destination.IsNotNull then WriteLn(Format('Destination: %s', [Geocoding[i].Destination.Value])); end else WriteLn(Format('BulkForwardGeocodeAddresses error: "%s"', [ErrorString])); finally FreeAndNil(Geocoding); end; end; end.
unit AttributeSelectKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы AttributeSelect } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\LiteSearch\Forms\AttributeSelectKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "AttributeSelectKeywordsPack" MUID: (4AAF4F89035C_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , AttributeSelect_Form , tfwPropertyLike , vtProportionalPanel , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , vtSizeablePanel , vtPanel , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4AAF4F89035C_Packimpl_uses* //#UC END# *4AAF4F89035C_Packimpl_uses* ; type TkwCfAttributeSelectBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfAttributeSelect.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; acfAttributeSelect: TcfAttributeSelect): TvtProportionalPanel; {* Реализация слова скрипта .TcfAttributeSelect.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfAttributeSelectBackgroundPanel TkwCfAttributeSelectSelectedZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfAttributeSelect.SelectedZone } private function SelectedZone(const aCtx: TtfwContext; acfAttributeSelect: TcfAttributeSelect): TvtSizeablePanel; {* Реализация слова скрипта .TcfAttributeSelect.SelectedZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfAttributeSelectSelectedZone TkwCfAttributeSelectValuesZone = {final} class(TtfwPropertyLike) {* Слово скрипта .TcfAttributeSelect.ValuesZone } private function ValuesZone(const aCtx: TtfwContext; acfAttributeSelect: TcfAttributeSelect): TvtPanel; {* Реализация слова скрипта .TcfAttributeSelect.ValuesZone } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwCfAttributeSelectValuesZone Tkw_Form_AttributeSelect = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы AttributeSelect ---- *Пример использования*: [code]форма::AttributeSelect TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_AttributeSelect Tkw_AttributeSelect_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AttributeSelect_Control_BackgroundPanel Tkw_AttributeSelect_Control_BackgroundPanel_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code]контрол::BackgroundPanel:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AttributeSelect_Control_BackgroundPanel_Push Tkw_AttributeSelect_Control_SelectedZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола SelectedZone ---- *Пример использования*: [code]контрол::SelectedZone TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AttributeSelect_Control_SelectedZone Tkw_AttributeSelect_Control_SelectedZone_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола SelectedZone ---- *Пример использования*: [code]контрол::SelectedZone:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AttributeSelect_Control_SelectedZone_Push Tkw_AttributeSelect_Control_ValuesZone = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ValuesZone ---- *Пример использования*: [code]контрол::ValuesZone TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AttributeSelect_Control_ValuesZone Tkw_AttributeSelect_Control_ValuesZone_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола ValuesZone ---- *Пример использования*: [code]контрол::ValuesZone:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_AttributeSelect_Control_ValuesZone_Push function TkwCfAttributeSelectBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; acfAttributeSelect: TcfAttributeSelect): TvtProportionalPanel; {* Реализация слова скрипта .TcfAttributeSelect.BackgroundPanel } begin Result := acfAttributeSelect.BackgroundPanel; end;//TkwCfAttributeSelectBackgroundPanel.BackgroundPanel class function TkwCfAttributeSelectBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TcfAttributeSelect.BackgroundPanel'; end;//TkwCfAttributeSelectBackgroundPanel.GetWordNameForRegister function TkwCfAttributeSelectBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtProportionalPanel); end;//TkwCfAttributeSelectBackgroundPanel.GetResultTypeInfo function TkwCfAttributeSelectBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfAttributeSelectBackgroundPanel.GetAllParamsCount function TkwCfAttributeSelectBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfAttributeSelect)]); end;//TkwCfAttributeSelectBackgroundPanel.ParamsTypes procedure TkwCfAttributeSelectBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwCfAttributeSelectBackgroundPanel.SetValuePrim procedure TkwCfAttributeSelectBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_acfAttributeSelect: TcfAttributeSelect; begin try l_acfAttributeSelect := TcfAttributeSelect(aCtx.rEngine.PopObjAs(TcfAttributeSelect)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfAttributeSelect: TcfAttributeSelect : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_acfAttributeSelect)); end;//TkwCfAttributeSelectBackgroundPanel.DoDoIt function TkwCfAttributeSelectSelectedZone.SelectedZone(const aCtx: TtfwContext; acfAttributeSelect: TcfAttributeSelect): TvtSizeablePanel; {* Реализация слова скрипта .TcfAttributeSelect.SelectedZone } begin Result := acfAttributeSelect.SelectedZone; end;//TkwCfAttributeSelectSelectedZone.SelectedZone class function TkwCfAttributeSelectSelectedZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfAttributeSelect.SelectedZone'; end;//TkwCfAttributeSelectSelectedZone.GetWordNameForRegister function TkwCfAttributeSelectSelectedZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtSizeablePanel); end;//TkwCfAttributeSelectSelectedZone.GetResultTypeInfo function TkwCfAttributeSelectSelectedZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfAttributeSelectSelectedZone.GetAllParamsCount function TkwCfAttributeSelectSelectedZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfAttributeSelect)]); end;//TkwCfAttributeSelectSelectedZone.ParamsTypes procedure TkwCfAttributeSelectSelectedZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству SelectedZone', aCtx); end;//TkwCfAttributeSelectSelectedZone.SetValuePrim procedure TkwCfAttributeSelectSelectedZone.DoDoIt(const aCtx: TtfwContext); var l_acfAttributeSelect: TcfAttributeSelect; begin try l_acfAttributeSelect := TcfAttributeSelect(aCtx.rEngine.PopObjAs(TcfAttributeSelect)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfAttributeSelect: TcfAttributeSelect : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(SelectedZone(aCtx, l_acfAttributeSelect)); end;//TkwCfAttributeSelectSelectedZone.DoDoIt function TkwCfAttributeSelectValuesZone.ValuesZone(const aCtx: TtfwContext; acfAttributeSelect: TcfAttributeSelect): TvtPanel; {* Реализация слова скрипта .TcfAttributeSelect.ValuesZone } begin Result := acfAttributeSelect.ValuesZone; end;//TkwCfAttributeSelectValuesZone.ValuesZone class function TkwCfAttributeSelectValuesZone.GetWordNameForRegister: AnsiString; begin Result := '.TcfAttributeSelect.ValuesZone'; end;//TkwCfAttributeSelectValuesZone.GetWordNameForRegister function TkwCfAttributeSelectValuesZone.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwCfAttributeSelectValuesZone.GetResultTypeInfo function TkwCfAttributeSelectValuesZone.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwCfAttributeSelectValuesZone.GetAllParamsCount function TkwCfAttributeSelectValuesZone.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TcfAttributeSelect)]); end;//TkwCfAttributeSelectValuesZone.ParamsTypes procedure TkwCfAttributeSelectValuesZone.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ValuesZone', aCtx); end;//TkwCfAttributeSelectValuesZone.SetValuePrim procedure TkwCfAttributeSelectValuesZone.DoDoIt(const aCtx: TtfwContext); var l_acfAttributeSelect: TcfAttributeSelect; begin try l_acfAttributeSelect := TcfAttributeSelect(aCtx.rEngine.PopObjAs(TcfAttributeSelect)); except on E: Exception do begin RunnerError('Ошибка при получении параметра acfAttributeSelect: TcfAttributeSelect : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ValuesZone(aCtx, l_acfAttributeSelect)); end;//TkwCfAttributeSelectValuesZone.DoDoIt function Tkw_Form_AttributeSelect.GetString: AnsiString; begin Result := 'cfAttributeSelect'; end;//Tkw_Form_AttributeSelect.GetString class procedure Tkw_Form_AttributeSelect.RegisterInEngine; begin inherited; TtfwClassRef.Register(TcfAttributeSelect); end;//Tkw_Form_AttributeSelect.RegisterInEngine class function Tkw_Form_AttributeSelect.GetWordNameForRegister: AnsiString; begin Result := 'форма::AttributeSelect'; end;//Tkw_Form_AttributeSelect.GetWordNameForRegister function Tkw_AttributeSelect_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_AttributeSelect_Control_BackgroundPanel.GetString class procedure Tkw_AttributeSelect_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtProportionalPanel); end;//Tkw_AttributeSelect_Control_BackgroundPanel.RegisterInEngine class function Tkw_AttributeSelect_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_AttributeSelect_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_AttributeSelect_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_AttributeSelect_Control_BackgroundPanel_Push.DoDoIt class function Tkw_AttributeSelect_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_AttributeSelect_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_AttributeSelect_Control_SelectedZone.GetString: AnsiString; begin Result := 'SelectedZone'; end;//Tkw_AttributeSelect_Control_SelectedZone.GetString class procedure Tkw_AttributeSelect_Control_SelectedZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtSizeablePanel); end;//Tkw_AttributeSelect_Control_SelectedZone.RegisterInEngine class function Tkw_AttributeSelect_Control_SelectedZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::SelectedZone'; end;//Tkw_AttributeSelect_Control_SelectedZone.GetWordNameForRegister procedure Tkw_AttributeSelect_Control_SelectedZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('SelectedZone'); inherited; end;//Tkw_AttributeSelect_Control_SelectedZone_Push.DoDoIt class function Tkw_AttributeSelect_Control_SelectedZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::SelectedZone:push'; end;//Tkw_AttributeSelect_Control_SelectedZone_Push.GetWordNameForRegister function Tkw_AttributeSelect_Control_ValuesZone.GetString: AnsiString; begin Result := 'ValuesZone'; end;//Tkw_AttributeSelect_Control_ValuesZone.GetString class procedure Tkw_AttributeSelect_Control_ValuesZone.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_AttributeSelect_Control_ValuesZone.RegisterInEngine class function Tkw_AttributeSelect_Control_ValuesZone.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ValuesZone'; end;//Tkw_AttributeSelect_Control_ValuesZone.GetWordNameForRegister procedure Tkw_AttributeSelect_Control_ValuesZone_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ValuesZone'); inherited; end;//Tkw_AttributeSelect_Control_ValuesZone_Push.DoDoIt class function Tkw_AttributeSelect_Control_ValuesZone_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ValuesZone:push'; end;//Tkw_AttributeSelect_Control_ValuesZone_Push.GetWordNameForRegister initialization TkwCfAttributeSelectBackgroundPanel.RegisterInEngine; {* Регистрация cfAttributeSelect_BackgroundPanel } TkwCfAttributeSelectSelectedZone.RegisterInEngine; {* Регистрация cfAttributeSelect_SelectedZone } TkwCfAttributeSelectValuesZone.RegisterInEngine; {* Регистрация cfAttributeSelect_ValuesZone } Tkw_Form_AttributeSelect.RegisterInEngine; {* Регистрация Tkw_Form_AttributeSelect } Tkw_AttributeSelect_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_AttributeSelect_Control_BackgroundPanel } Tkw_AttributeSelect_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_AttributeSelect_Control_BackgroundPanel_Push } Tkw_AttributeSelect_Control_SelectedZone.RegisterInEngine; {* Регистрация Tkw_AttributeSelect_Control_SelectedZone } Tkw_AttributeSelect_Control_SelectedZone_Push.RegisterInEngine; {* Регистрация Tkw_AttributeSelect_Control_SelectedZone_Push } Tkw_AttributeSelect_Control_ValuesZone.RegisterInEngine; {* Регистрация Tkw_AttributeSelect_Control_ValuesZone } Tkw_AttributeSelect_Control_ValuesZone_Push.RegisterInEngine; {* Регистрация Tkw_AttributeSelect_Control_ValuesZone_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TcfAttributeSelect)); {* Регистрация типа TcfAttributeSelect } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtProportionalPanel)); {* Регистрация типа TvtProportionalPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtSizeablePanel)); {* Регистрация типа TvtSizeablePanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } {$IfEnd} // NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit SaveStatusForms; interface uses Forms, IniFiles, SysUtils; type TSaveStatusForm = class (TForm) protected procedure DoCreate; override; procedure DoDestroy; override; end; implementation { TSaveStatusForm } procedure TSaveStatusForm.DoCreate; var Ini: TIniFile; begin inherited; Ini := TIniFile.Create (ExtractFileName (Application.ExeName)); Left := Ini.ReadInteger(Caption, 'Left', Left); Top := Ini.ReadInteger(Caption, 'Top', Top); Width := Ini.ReadInteger(Caption, 'Width', Width); Height := Ini.ReadInteger(Caption, 'Height', Height); Ini.Free; end; procedure TSaveStatusForm.DoDestroy; var Ini: TIniFile; begin Ini := TIniFile.Create (ExtractFileName (Application.ExeName)); Ini.WriteInteger(Caption, 'Left', Left); Ini.WriteInteger(Caption, 'Top', Top); Ini.WriteInteger(Caption, 'Width', Width); Ini.WriteInteger(Caption, 'Height', Height); Ini.Free; inherited; end; end.
unit xPlayer; interface uses SysUtils, Types, Classes, Controls, ShockwaveFlashObjects_TLB; type TxPlayer = class(TCustomControl) private FFlash: TShockwaveFlash; procedure RecalcFlashPos; procedure MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); protected function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; public procedure Resize; override; procedure Paint; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } end; implementation uses Graphics; { TxPlayer } const DefHeight = 300; DefWidth = 300; DefFlashWidth = 200; DefFlashHeight = 200; constructor TxPlayer.Create(AOwner: TComponent); begin inherited; Height := DefHeight; Width := DefWidth; // OnMouseWheel := MouseWheel; FFlash := TShockwaveFlash.Create(Self); with FFlash do begin Width := DefFlashWidth; Height := DefFlashHeight; BackgroundColor := 0; RecalcFlashPos; FFlash.Parent := Self; end; end; destructor TxPlayer.Destroy; begin try FFlash.Free; except end; inherited; end; function TxPlayer.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin FFlash.Width := FFlash.Width + Trunc(WheelDelta/Abs(WheelDelta)); FFlash.Height := FFlash.Height + Trunc(WheelDelta/Abs(WheelDelta)); RecalcFlashPos; Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos) end; procedure TxPlayer.MouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin end; procedure TxPlayer.Paint; begin with Canvas do begin Pen.Color := clBlack; Rectangle(Self.ClientRect); end; end; procedure TxPlayer.RecalcFlashPos; begin with FFlash do begin Left := (Self.Width - Width) div 2; Top := (Self.Height - Height) div 2; end; end; procedure TxPlayer.Resize; begin RecalcFlashPos; inherited; end; end.
unit UOrderedAccountList; interface uses Classes, UAccountKey, UAccount; type TOrderedAccountList = Class private FList : TList; public Constructor Create; Destructor Destroy; Override; Procedure Clear; Function Add(Const account : TAccount) : Integer; Function Count : Integer; Function Get(index : Integer) : TAccount; // Skybuck: moved to here to make it accessable to TPCSafeBoxTransaction Function Find(const account_number: Cardinal; var Index: Integer): Boolean; // Skybuck: property added to make FList accessable to TPCSafeBoxTransaction property List : TList read FList; End; implementation uses SysUtils; { TOrderedAccountList } Function TOrderedAccountList.Add(const account: TAccount) : Integer; Var P : PAccount; begin if Find(account.account,Result) then begin PAccount(FList[Result])^ := account; end else begin New(P); P^:=account; FList.Insert(Result,P); end; end; procedure TOrderedAccountList.Clear; Var i : Integer; P : PAccount; begin for I := 0 to FList.Count - 1 do begin P := FList[i]; Dispose(P); end; FList.Clear; end; function TOrderedAccountList.Count: Integer; begin Result := FList.Count; end; constructor TOrderedAccountList.Create; begin FList := TList.Create; end; destructor TOrderedAccountList.Destroy; begin Clear; FreeAndNil(FList); inherited; end; function TOrderedAccountList.Find(const account_number: Cardinal; var Index: Integer): Boolean; var L, H, I: Integer; C : Int64; begin Result := False; L := 0; H := FList.Count - 1; while L <= H do begin I := (L + H) shr 1; C := Int64(PAccount(FList[I]).account) - Int64(account_number); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; function TOrderedAccountList.Get(index: Integer): TAccount; begin Result := PAccount(FList.Items[index])^; end; end.
unit uClienteVO; interface uses System.SysUtils, uRevendaVO, uUsuarioVO; type TClienteVO = class private FBairro: string; FCEP: String; FCidade: string; FCNPJ: string; FCodigo: Integer; FContatoFinanceiro: string; FContatoCompraVenda: string; FEnquadramento: string; FNomeFantasia: string; FPendenciaFinanceira: string; FRazaoSocial: string; FRevenda: Integer; FRua: string; FSituacao: string; FTelefone: string; FUsuario: Integer; FVersao: string; FRevendaVO: TRevendaVO; FAtivo: Boolean; FRestricao: Boolean; FId: Integer; FUsuarioVO: TUsuarioVO; FEndereco: string; procedure SetAtivo(const Value: Boolean); procedure SetEndereco(const Value: string); procedure SetId(const Value: Integer); procedure SetRestricao(const Value: Boolean); procedure SetRevendaVO(const Value: TRevendaVO); procedure SetUsuarioVO(const Value: TUsuarioVO); procedure SetVersao(const Value: string); public property Id: Integer read FId write SetId; property Endereco: string read FEndereco write SetEndereco; property RevendaVO: TRevendaVO read FRevendaVO write SetRevendaVO; property Ativo: Boolean read FAtivo write SetAtivo; property Restricao: Boolean read FRestricao write SetRestricao; property UsuarioVO: TUsuarioVO read FUsuarioVO write SetUsuarioVO; property Versao: string read FVersao write SetVersao; property Bairro: string read FBairro write FBairro; property CEP: String read FCEP write FCEP; property Cidade: string read FCidade write FCidade; property CNPJ: string read FCNPJ write FCNPJ; property Codigo: Integer read FCodigo write FCodigo; property ContatoFinanceiro: string read FContatoFinanceiro write FContatoFinanceiro; property ContatoCompraVenda: string read FContatoCompraVenda write FContatoCompraVenda; property Enquadramento: string read FEnquadramento write FEnquadramento; property NomeFantasia: string read FNomeFantasia write FNomeFantasia; property PendenciaFinanceira: string read FPendenciaFinanceira write FPendenciaFinanceira; property RazaoSocial: string read FRazaoSocial write FRazaoSocial; property Revenda: Integer read FRevenda write FRevenda; property Rua: string read FRua write FRua; property Situacao: string read FSituacao write FSituacao; property Telefone: string read FTelefone write FTelefone; property Usuario: Integer read FUsuario write FUsuario; constructor create; destructor destroy; override; end; TEmailVO = class private FEmail: string; public property Email: string read FEmail write FEmail; end; TModuloVO = class private FCodigoModulo: Integer; FCodigoProduto: integer; FNomeModulo: string; FNomeProduto: string; public property CodigoModulo: Integer read FCodigoModulo write FCodigoModulo; property CodigoProduto: integer read FCodigoProduto write FCodigoProduto; property NomeModulo: string read FNomeModulo write FNomeModulo; property NomeProduto: string read FNomeProduto write FNomeProduto; end; implementation { TClienteVO } constructor TClienteVO.create; begin FRevendaVO := TRevendaVO.Create; FUsuarioVO := TUsuarioVO.Create; end; destructor TClienteVO.destroy; begin FreeAndNil(FRevendaVO); FreeAndNil(FUsuarioVO); inherited; end; procedure TClienteVO.SetAtivo(const Value: Boolean); begin FAtivo := Value; end; procedure TClienteVO.SetEndereco(const Value: string); begin FEndereco := Value; end; procedure TClienteVO.SetId(const Value: Integer); begin FId := Value; end; procedure TClienteVO.SetRestricao(const Value: Boolean); begin FRestricao := Value; end; procedure TClienteVO.SetRevendaVO(const Value: TRevendaVO); begin FRevendaVO := Value; end; procedure TClienteVO.SetUsuarioVO(const Value: TUsuarioVO); begin FUsuarioVO := Value; end; procedure TClienteVO.SetVersao(const Value: string); begin FVersao := Value; end; end.
unit evdDOM; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "EVD" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/EVD/evdDOM.pas" // Начат: 01.06.2009 17:06 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> Shared Delphi::EVD::DOM // // Объектная модель документа EVD // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\EVD\evdDefine.inc} interface uses l3Types, evdTypes ; type TevdPaperSize = ( {* Размер бумаги } evd_psCustom , evd_psA0 // 84 x 118.8 , evd_psA1 // 59.4 x 84 , evd_psA2 // 42 x 59.4 , evd_psA3 // 29.7 x 42 , evd_psA4 // 21 x 29.7 , evd_psA5 // 14.8 x 21 );//TevdPaperSize IevdSection = interface(IUnknown) {* Свойства раздела документа } ['{200906F8-7E80-4FA3-B51F-628A5D751D6E}'] function pm_GetPaperSize: TevdPaperSize; procedure pm_SetPaperSize(aValue: TevdPaperSize); function pm_GetOrientation: TevPageOrientation; procedure pm_SetOrientation(aValue: TevPageOrientation); property PaperSize: TevdPaperSize read pm_GetPaperSize write pm_SetPaperSize; {* Размер бумаги } property Orientation: TevPageOrientation read pm_GetOrientation write pm_SetOrientation; {* Ориентация страницы } end;//IevdSection TevdLanguage = ( {* Язык } evd_lgRussian // Русский , evd_lgEnglish // Английский , evd_lgGerman // Немецкий , evd_lgFrench // Французский , evd_lgItalian // Итальянский , evd_lgSpanish // Испанский );//TevdLanguage IevdDictEntry = interface(IUnknown) {* Вхождение толкового словаря } ['{70F7FC17-4C78-4917-A9D5-593B8889B4A5}'] function pm_GetShortName(aLang: TevdLanguage): Tl3PCharLen; procedure pm_SetShortName(aLang: TevdLanguage; const aValue: Tl3PCharLen); property ShortName[aLang: TevdLanguage]: Tl3PCharLen read pm_GetShortName write pm_SetShortName; {* Короткие имена } end;//IevdDictEntry implementation end.
unit VoiceExt; {$I CSXGuard.inc} interface uses HLSDK; procedure VX_Init; procedure VX_Debug; procedure SVC_VoiceInit; cdecl; procedure SVC_VoiceData; cdecl; const VOICE_BYTE_RATE = 16000; type PVoiceBanEntry = ^TVoiceBanEntry; TVoiceBanEntry = record UserID: LongWord; Banned: Boolean; end; var Voice_RecordToFile: cvar_s = nil; Voice_InputFromFile: cvar_s = nil; Voice_RecordStart: HLSDK.Voice_RecordStart = nil; Voice_IsRecording: HLSDK.Voice_IsRecording = nil; Voice_RecordStop: HLSDK.Voice_RecordStop = nil; CL_SendVoicePacket: HLSDK.CL_SendVoicePacket = nil; Voice_GetCompressedData_Orig: HLSDK.Voice_GetCompressedData = nil; Voice_GetCompressedData_Gate: HLSDK.Voice_GetCompressedData = nil; Cmd_VoiceRecord_Start: cmd_s = nil; Cmd_VoiceRecord_Stop: cmd_s = nil; CurrentMicInputByte: PLongWord = nil; TotalMicInputBytes: PLongWord = nil; MicInputFileData: PPointer = nil; VoiceRecording: PBoolean = nil; // custom Voice_InputFile: cvar_s = nil; Voice_MicData: cvar_s = nil; Voice_Decompressed: cvar_s = nil; Voice_LoopInput: cvar_s = nil; Voice_StopInput: cvar_s = nil; Voice_ConnectionState: Byte = 5; Voice_DefaultPacketSize: Word = 2048; Voice_EnableBanManager: Boolean = True; Voice_BannedPlayers: array[1..MAX_PLAYERS] of TVoiceBanEntry; implementation uses Windows, CvarDef, MsgAPI, MemSearch, SysUtils, Detours, Common; procedure VX_Record_Start; cdecl; var UncompressedFile, DecompressedFile, MicInputFile: PChar; begin if Byte(CState^) >= Voice_ConnectionState then begin if Voice_RecordToFile.Value >= 1 then if (Voice_MicData.Data <> '') and (Voice_Decompressed.Data <> '') then begin UncompressedFile := Voice_MicData.Data; DecompressedFile := Voice_Decompressed.Data; if CheckRelativePath(UncompressedFile) or CheckRelativePath(DecompressedFile) then begin Print('Relative pathnames are not allowed.'); Exit; end; end else begin UncompressedFile := 'voice_micdata.wav'; DecompressedFile := 'voice_decompressed.wav'; end else begin UncompressedFile := nil; DecompressedFile := nil; end; if Voice_InputFromFile.Value >= 1 then if Voice_InputFile.Data <> '' then MicInputFile := Voice_InputFile.Data else MicInputFile := 'voice_input.wav' else MicInputFile := nil; if CheckRelativePath(MicInputFile) then begin Print('Relative pathnames are not allowed.'); Exit; end; Voice_RecordStart(UncompressedFile, DecompressedFile, MicInputFile); end else Print('Recording cannot be started now.'); end; procedure VX_Record_Stop; cdecl; begin if Byte(CState^) >= Voice_ConnectionState then if Voice_IsRecording then begin CL_SendVoicePacket(1); Voice_RecordStop; end else if not KeyStateActive then Print('Currently not recording.') else else if not KeyStateActive then Print('Recording cannot be stopped now.'); end; procedure SVC_VoiceInit; cdecl; var I, Count: LongWord; begin if CState^ <> ca_uninitialized then if LogDeveloper then Print('Tried to send SVC_VoiceInit at CState = ', IntToStr(Byte(CState^)), '; update ignored.') else else begin Count := 0; for I := 1 to MAX_PLAYERS do begin if Voice_BannedPlayers[I].Banned then Inc(Count); Voice_BannedPlayers[I].Banned := False; Voice_BannedPlayers[I].UserID := 0; end; if LogDeveloper and (Count > 0) then Print('Unbanned ', IntToStr(Count), ' players'); end; SVC_VoiceInit_Orig; end; procedure SVC_VoiceData; cdecl; var Index: Byte; Size: Word; begin if not Enabled or not Voice_EnableBanManager then begin SVC_VoiceData_Orig; Exit; end; MSG_SaveReadCount; Index := MSG_ReadByte + 1; if Voice_BannedPlayers[Index].Banned and (Voice_BannedPlayers[Index].UserID = Cardinal(Studio.PlayerInfo(Index - 1).UserID)) then begin Size := MSG_ReadShort; Inc(MSG_ReadCount^, Size); if LogDeveloper then Print('VoiceData from banned player; Size = ', IntToStr(Size), '.'); Exit; end; MSG_RestoreReadCount; SVC_VoiceData_Orig; end; procedure VX_AddBan(Index: Byte; UserID: LongWord); begin if Engine.EventAPI.EV_IsLocal(Index - 1) = 1 then Print('Couldn''t ban local player.') else begin Voice_BannedPlayers[Index].Banned := True; Voice_BannedPlayers[Index].UserID := UserID; Print('Done.'); end; end; procedure VX_RemoveBan(Index: Byte); begin Voice_BannedPlayers[Index].Banned := False; Voice_BannedPlayers[Index].UserID := 0; Print('Done.'); end; procedure VX_BanList; var I, Count: Byte; begin if not Voice_EnableBanManager then begin Print('Voice ban manager is disabled.'); Exit; end; Count := 0; for I := 1 to MAX_PLAYERS do if Voice_BannedPlayers[I].Banned then begin Print('#', IntToStr(I), ': ', IntToStr(Voice_BannedPlayers[I].UserID)); Inc(Count); end; Print(IntToStr(Count), ' total players'); end; procedure VX_ClearBanList; var I: Byte; begin if not Voice_EnableBanManager then begin Print('Voice ban manager is disabled.'); Exit; end; for I := 1 to MAX_PLAYERS do begin Voice_BannedPlayers[I].Banned := False; Voice_BannedPlayers[I].UserID := 0; end; Print('Done.'); end; procedure VX_Ban; var Str: PChar; PInfo: player_info_s; Index: Longint; I: Byte; begin if not Voice_EnableBanManager then begin Print('Voice ban manager is disabled.'); Exit; end; if Engine.Cmd_Argc < 2 then Print('Syntax: ', LowerCase(Engine.Cmd_Argv(0)), ' <name/#index>') else begin Str := Engine.Cmd_Argv(1); if (Str = nil) or (Str = '') then Print('Invalid parameter.') else if PByte(Str)^ = Ord('#') then // Index if not TryStrToInt(PChar(Cardinal(Str) + 1), Index) or not (Byte(Index) in [1..MAX_PLAYERS]) then Print('Invalid player index.') else begin PInfo := Studio.PlayerInfo(Index - 1); if PInfo = nil then Print('Invalid player index.') else if PInfo.UserID = 0 then Print('Invalid player index.') else VX_AddBan(Byte(Index), PInfo.UserID); end else // Name begin for I := 0 to MAX_PLAYERS - 1 do begin PInfo := Studio.PlayerInfo(I); if (PInfo <> nil) and (StrIComp(Str, @PInfo.Name) = 0) then begin VX_AddBan(I + 1, Studio.PlayerInfo(I).UserID); Exit; end; end; Print('Couldn''t find specified player.'); end; end; end; procedure VX_Unban; var Str: PChar; Index: Longint; I: Byte; PInfo: player_info_s; begin if not Voice_EnableBanManager then begin Print('Voice ban manager is disabled.'); Exit; end; if Engine.Cmd_Argc < 2 then Print('Syntax: ', LowerCase(Engine.Cmd_Argv(0)), ' <name/#index>') else begin Str := Engine.Cmd_Argv(1); if (Str = nil) or (Str = '') then Print('Invalid parameter.') else if PByte(Str)^ = Ord('#') then // Index if not TryStrToInt(PChar(Cardinal(Str) + 1), Index) or not (Byte(Index) in [1..MAX_PLAYERS]) then Print('Invalid player index.') else VX_RemoveBan(Byte(Index)) else // Name begin for I := 0 to MAX_PLAYERS - 1 do begin PInfo := Studio.PlayerInfo(I); if (PInfo <> nil) and (StrIComp(Str, @PInfo.Name) = 0) then begin VX_RemoveBan(I + 1); Exit; end; end; Print('Couldn''t find specified player.'); end; end; end; procedure VX_Debug; begin PrintAddress('Voice_RecordStart', @Voice_RecordStart); PrintAddress('Voice_RecordStop', @Voice_RecordStop); PrintAddress('Voice_IsRecording', @Voice_IsRecording); PrintAddress('CL_SendVoicePacket', @CL_SendVoicePacket); PrintAddress('Voice_GetCompressedData', @Voice_GetCompressedData_Orig); PrintAddress('CurrentMicInputByte', CurrentMicInputByte); PrintAddress('TotalMicInputBytes', TotalMicInputBytes); PrintAddress('SVC_VoiceInit', @CvarDef.SVC_VoiceInit_Orig); PrintAddress('SVC_VoiceData', @CvarDef.SVC_VoiceData_Orig); end; procedure VX_Find_Voice_RecordStart; begin Cmd_VoiceRecord_Start := CommandByName('+voicerecord'); CheckCallback(Cmd_VoiceRecord_Start); VoiceExt.Voice_RecordStart := Pointer(Absolute(Cardinal(@Cmd_VoiceRecord_Start.Callback) + 67)); if Bounds(@VoiceExt.Voice_RecordStart, HLBase, HLBase_End, True) then Error('Couldn''t find Voice_RecordStart pointer.'); VoiceExt.TotalMicInputBytes := PPointer(Cardinal(@VoiceExt.Voice_RecordStart) + 62 - Cardinal(SW))^; if Bounds(VoiceExt.TotalMicInputBytes, HLBase, HLBase_End) then Error('Couldn''t find TotalMicInputBytes pointer.'); VoiceExt.CurrentMicInputByte := PPointer(Cardinal(@VoiceExt.Voice_RecordStart) + 82 - Cardinal(SW))^; if Bounds(VoiceExt.CurrentMicInputByte, HLBase, HLBase_End) then Error('Couldn''t find CurrentMicInputByte pointer.'); end; procedure VX_Find_Voice_RecordStop; begin Cmd_VoiceRecord_Stop := CommandByName('-voicerecord'); CheckCallback(Cmd_VoiceRecord_Stop); VoiceExt.Voice_IsRecording := Pointer(Absolute(Cardinal(@Cmd_VoiceRecord_Stop.Callback) + 10)); if Bounds(@VoiceExt.Voice_IsRecording, HLBase, HLBase_End, True) then Error('Couldn''t find Voice_IsRecording pointer.'); VoiceExt.CL_SendVoicePacket := Pointer(Absolute(Cardinal(@Cmd_VoiceRecord_Stop.Callback) + 21)); if Bounds(@VoiceExt.CL_SendVoicePacket, HLBase, HLBase_End, True) then Error('Couldn''t find CL_SendVoicePacket pointer.'); VoiceExt.Voice_RecordStop := Pointer(Absolute(Cardinal(@Cmd_VoiceRecord_Stop.Callback) + 29)); if Bounds(@VoiceExt.Voice_RecordStop, HLBase, HLBase_End, True) then Error('Couldn''t find Voice_RecordStop pointer.'); end; procedure VX_Find_Voice_GetCompressedData; begin VoiceExt.Voice_GetCompressedData_Orig := Pointer(Absolute(Cardinal(@VoiceExt.CL_SendVoicePacket) + 45 + Cardinal(SW))); if Bounds(@VoiceExt.Voice_GetCompressedData_Orig, HLBase, HLBase_End, True) then Error('Couldn''t find Voice_GetCompressedData pointer.'); end; procedure VX_Find_MicInputFileData; begin VoiceExt.MicInputFileData := PPointer(Cardinal(@VoiceExt.Voice_RecordStop) + 1)^; if Bounds(VoiceExt.MicInputFileData, HLBase, HLBase_End) then Error('Couldn''t find MicInputFileData pointer.'); end; procedure VX_Find_VoiceRecording; begin VoiceExt.VoiceRecording := PPointer(Cardinal(@VoiceExt.Voice_IsRecording) + 1)^; if Bounds(VoiceExt.VoiceRecording, HLBase, HLBase_End) then Error('Couldn''t find VoiceRecording pointer.'); end; procedure Patch_CL_SendVoicePacket; var Protect: LongWord; Addr: Pointer; begin // 1: tweak the buffer size on the stack (Voice_DefaultPacketSize) Addr := Pointer(Cardinal(@CL_SendVoicePacket) + 7 - Cardinal(SW) * 2); if PWord(Cardinal(Addr) - 2)^ <> $EC81 then Error('Couldn''t find CL_SendVoicePacket patch pattern 1.'); VirtualProtect(Addr, 4, PAGE_EXECUTE_READWRITE, Protect); PCardinal(Addr)^ := Cardinal(Voice_DefaultPacketSize); VirtualProtect(Addr, 4, Protect, Protect); // 2: replace the default connection state (Voice_ConnectionState) Addr := Pointer(Cardinal(@CL_SendVoicePacket) + 13 + Cardinal(SW) * 4); if PWord(Cardinal(Addr) - 2)^ <> $F883 then Error('Couldn''t find CL_SendVoicePacket patch pattern 2.'); VirtualProtect(Addr, 1, PAGE_EXECUTE_READWRITE, Protect); PByte(Addr)^ := Voice_ConnectionState; VirtualProtect(Addr, 1, Protect, Protect); // 3: tweak the offset that is required to reach the saved buffer (Voice_DefaultPacketSize) Addr := Pointer(Cardinal(@CL_SendVoicePacket) + 29 + Cardinal(SW) * 5); if ((not SW) and ((PWord(Cardinal(Addr) - 2)^ <> $2484) or (PByte(Cardinal(Addr) - 3)^ <> $8B))) or (SW and (PWord(Cardinal(Addr) - 2)^ <> $8D8D)) then Error('Couldn''t find CL_SendVoicePacket patch pattern 3.'); VirtualProtect(Addr, 4, PAGE_EXECUTE_READWRITE, Protect); if not SW then PCardinal(Addr)^ := Cardinal(Voice_DefaultPacketSize) + 8 else PCardinal(Addr)^ := -Cardinal(Voice_DefaultPacketSize); VirtualProtect(Addr, 4, Protect, Protect); // 4: tweak the actial buffer size (passed to Voice_GetCompressedData) (Voice_DefaultPacketSize) Addr := Pointer(Cardinal(@CL_SendVoicePacket) + 39 + Cardinal(SW)); if PWord(Cardinal(Addr) - 2)^ <> $6850 then Error('Couldn''t find CL_SendVoicePacket patch pattern 4.'); VirtualProtect(Addr, 4, PAGE_EXECUTE_READWRITE, Protect); PCardinal(Addr)^ := Cardinal(Voice_DefaultPacketSize); VirtualProtect(Addr, 4, Protect, Protect); // 5: tweak the buffer size on the stack (Voice_DefaultPacketSize) Addr := Pointer(Cardinal(@CL_SendVoicePacket) + 126 - Cardinal(SW) * 19); if ((not SW) and (PWord(Cardinal(Addr) - 2)^ <> $C481)) or (SW and (PWord(Cardinal(Addr) - 2)^ <> $958D)) then Error('Couldn''t find CL_SendVoicePacket patch pattern 5.'); VirtualProtect(Addr, 4, PAGE_EXECUTE_READWRITE, Protect); if not SW then PCardinal(Addr)^ := Cardinal(Voice_DefaultPacketSize) else PCardinal(Addr)^ := -Cardinal(Voice_DefaultPacketSize); VirtualProtect(Addr, 4, Protect, Protect); // 6: change the jump type (Voice_ConnectionState) Addr := Pointer(Cardinal(@CL_SendVoicePacket) + 15 + Cardinal(SW) * 3); if ((not SW) and (PWord(Cardinal(Addr) - 1)^ <> $7556)) or (SW and (PByte(Addr)^ <> $75)) then Error('Couldn''t find CL_SendVoicePacket patch pattern 6.'); VirtualProtect(Addr, 1, PAGE_EXECUTE_READWRITE, Protect); PByte(Addr)^ := $7C; VirtualProtect(Addr, 1, Protect, Protect); // we're done here end; function Voice_GetCompressedData(const Buffer: Pointer; Size: LongWord; Final: LongWord): LongWord; cdecl; var CurrentMicInputByte, TotalMicInputBytes: LongWord; begin CurrentMicInputByte := VoiceExt.CurrentMicInputByte^; TotalMicInputBytes := VoiceExt.TotalMicInputBytes^; if (MicInputFileData <> nil) and (TotalMicInputBytes > 0) and (CurrentMicInputByte >= TotalMicInputBytes) then if Voice_LoopInput.Value >= 1 then VoiceExt.CurrentMicInputByte^ := 0 else if Voice_StopInput.Value >= 1 then Voice_RecordStop; Result := Voice_GetCompressedData_Gate(Buffer, Size, Final); end; function GetInputTime(Pos: LongWord): String; var I, J: LongWord; begin Pos := Pos div VOICE_BYTE_RATE; I := Pos div 60; J := Pos mod 60; if I >= 10 then Result := IntToStr(I) else Result := '0' + IntToStr(I); if J >= 10 then Result := Result + ':' + IntToStr(J) else Result := Result + ':0' + IntToStr(J); end; function GetInputPos(Time: String): LongWord; var I, J, L: LongWord; begin for I := 1 to Length(Time) do if Time[I] = ' ' then Delete(Time, I, 1); I := Pos(':', Time); if (I = 0) or (Time = '') then begin Result := StrToIntDef(Time, 0) * VOICE_BYTE_RATE; Exit; end else if I = 1 then begin Result := StrToIntDef(Copy(Time, 2, MaxInt), 0) * VOICE_BYTE_RATE; Exit; end else begin L := Length(Time); J := StrToIntDef(Copy(Time, I + 1, L - I), 0); I := StrToIntDef(Copy(Time, 1, I - 1), 0); Result := (I * 60 + J) * VOICE_BYTE_RATE; end; end; procedure VX_InputInfo; begin if not VoiceRecording^ then Print('Currently not recording.') else if MicInputFileData^ = nil then Print('The input file data is empty.') else Print('CurrentMicInputByte = ' + IntToStr(CurrentMicInputByte^) + '; TotalMicInputBytes = ' + IntToStr(TotalMicInputBytes^) + '; CurrentInputTime = ' + GetInputTime(CurrentMicInputByte^) + '; TotalInputTime = ' + GetInputTime(TotalMicInputBytes^)); end; procedure VX_SeekInput; var I: LongWord; begin if Engine.Cmd_Argc < 2 then Print('Syntax: ', LowerCase(Engine.Cmd_Argv(0)), ' <time>') else if not VoiceRecording^ then Print('Currently not recording.') else if (MicInputFileData^ = nil) or (TotalMicInputBytes^ = 0) then Print('The input file data is empty.') else begin I := GetInputPos(Engine.Cmd_Argv(1)); if I <= TotalMicInputBytes^ then CurrentMicInputByte^ := I else Print('Requested position exceeds avaliable byte count.') end; end; procedure VX_Init; begin VX_Find_Voice_RecordStart; VX_Find_Voice_RecordStop; VX_Find_Voice_GetCompressedData; VX_Find_MicInputFileData; VX_Find_VoiceRecording; Voice_GetCompressedData_Gate := Detour(@Voice_GetCompressedData_Orig, @Voice_GetCompressedData, 5 + Cardinal(SW) * 3); Patch_CL_SendVoicePacket; Engine.AddCommand('voice_debug', @VX_Debug); Voice_InputFile := Engine.RegisterVariable('voice_inputfile', 'voice_input.wav', 0); Voice_MicData := Engine.RegisterVariable('voice_micdata', 'voice_micdata.wav', 0); Voice_Decompressed := Engine.RegisterVariable('voice_decompressed', 'voice_decompressed.wav', 0); Voice_LoopInput := Engine.RegisterVariable('voice_loopinput', '0', 0); Voice_StopInput := Engine.RegisterVariable('voice_stopinput', '0', 0); Voice_RecordToFile := Engine.GetCVarPointer('voice_recordtofile'); if Bounds(Voice_RecordToFile, HLBase, HLBase_End) then Error('Couldn''t find "voice_recordtofile" CVar pointer.'); Voice_InputFromFile := Engine.GetCVarPointer('voice_inputfromfile'); if Bounds(Voice_InputFromFile, HLBase, HLBase_End) then Error('Couldn''t find "voice_inputfromfile" CVar pointer.'); Cmd_VoiceRecord_Start.Callback := @VX_Record_Start; Cmd_VoiceRecord_Stop.Callback := @VX_Record_Stop; Engine.AddCommand('voice_banlist', @VX_BanList); Engine.AddCommand('voice_clearbanlist', @VX_ClearBanList); Engine.AddCommand('voice_ban', @VX_Ban); Engine.AddCommand('voice_unban', @VX_Unban); Engine.AddCommand('voice_inputinfo', @VX_InputInfo); Engine.AddCommand('voice_seekinput', @VX_SeekInput); if LogDeveloper then Print('Voice initialized.'); end; end.
unit uLibVLC; // 參考 https://wiki.videolan.org/Using_libvlc_with_Delphi/ interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TFormVLC = class(TForm) Panel1: TPanel; Panel2: TPanel; btnPlay: TButton; btnStop: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnPlayClick(Sender: TObject); procedure btnStopClick(Sender: TObject); private { Private declarations } public { Public declarations } end; plibvlc_instance_t = type Pointer; plibvlc_media_player_t = type Pointer; plibvlc_media_t = type Pointer; var FormVLC: TFormVLC; implementation {$R *.dfm} var libvlc_media_new_path: function(p_instance: plibvlc_instance_t; path: PAnsiChar): plibvlc_media_t; cdecl; libvlc_media_new_location: function(p_instance: plibvlc_instance_t; psz_mrl: PAnsiChar): plibvlc_media_t; cdecl; libvlc_media_player_new_from_media: function(p_media: plibvlc_media_t) : plibvlc_media_player_t; cdecl; libvlc_media_player_set_hwnd : procedure(p_media_player: plibvlc_media_player_t; drawable: Pointer); cdecl; libvlc_media_player_play: procedure(p_media_player : plibvlc_media_player_t); cdecl; libvlc_media_player_stop: procedure(p_media_player : plibvlc_media_player_t); cdecl; libvlc_media_player_release : procedure(p_media_player: plibvlc_media_player_t); cdecl; libvlc_media_player_is_playing : function(p_media_player: plibvlc_media_player_t): Integer; cdecl; libvlc_media_release: procedure(p_media: plibvlc_media_t); cdecl; libvlc_new: function(argc: Integer; argv: PAnsiChar) : plibvlc_instance_t; cdecl; libvlc_release: procedure(p_instance: plibvlc_instance_t); cdecl; libvlc_media_add_option: procedure(p_media: plibvlc_media_t; ppsz_options: PAnsiChar); cdecl; vlcLib: Integer; vlcInstance: plibvlc_instance_t; vlcMedia: plibvlc_media_t; vlcMediaPlayer: plibvlc_media_player_t; {$R *.dfm} // ----------------------------------------------------------------------------- // Read registry to get VLC installation path // ----------------------------------------------------------------------------- function GetVLCLibPath: String; var Handle: HKEY; RegType: Integer; DataSize: Cardinal; Key: PWideChar; begin Result := ''; Key := 'Software\VideoLAN\VLC'; if RegOpenKeyEx(HKEY_LOCAL_MACHINE, Key, 0, KEY_READ, Handle) = ERROR_SUCCESS then begin if RegQueryValueEx(Handle, 'InstallDir', nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then begin SetLength(Result, DataSize); RegQueryValueEx(Handle, 'InstallDir', nil, @RegType, PByte(@Result[1]), @DataSize); Result[DataSize] := '\'; end else Showmessage('Error on reading registry'); RegCloseKey(Handle); Result := String(PChar(Result)); end; end; // ----------------------------------------------------------------------------- // Load libvlc library into memory // ----------------------------------------------------------------------------- function LoadVLCLibrary(APath: string): Integer; begin Result := LoadLibrary(PWideChar(APath + '\libvlccore.dll')); Result := LoadLibrary(PWideChar(APath + '\libvlc.dll')); end; // ----------------------------------------------------------------------------- function GetAProcAddress(Handle: Integer; var addr: Pointer; procName: string; failedList: TStringList): Integer; begin addr := GetProcAddress(Handle, PWideChar(procName)); if Assigned(addr) then Result := 0 else begin if Assigned(failedList) then failedList.Add(procName); Result := -1; end; end; // ----------------------------------------------------------------------------- // Get address of libvlc functions // ----------------------------------------------------------------------------- function LoadVLCFunctions(vlcHandle: Integer; failedList: TStringList): Boolean; begin GetAProcAddress(vlcHandle, @libvlc_new, 'libvlc_new', failedList); GetAProcAddress(vlcHandle, @libvlc_media_new_location, 'libvlc_media_new_location', failedList); GetAProcAddress(vlcHandle, @libvlc_media_player_new_from_media, 'libvlc_media_player_new_from_media', failedList); GetAProcAddress(vlcHandle, @libvlc_media_release, 'libvlc_media_release', failedList); GetAProcAddress(vlcHandle, @libvlc_media_player_set_hwnd, 'libvlc_media_player_set_hwnd', failedList); GetAProcAddress(vlcHandle, @libvlc_media_player_play, 'libvlc_media_player_play', failedList); GetAProcAddress(vlcHandle, @libvlc_media_player_stop, 'libvlc_media_player_stop', failedList); GetAProcAddress(vlcHandle, @libvlc_media_player_release, 'libvlc_media_player_release', failedList); GetAProcAddress(vlcHandle, @libvlc_release, 'libvlc_release', failedList); GetAProcAddress(vlcHandle, @libvlc_media_player_is_playing, 'libvlc_media_player_is_playing', failedList); GetAProcAddress(vlcHandle, @libvlc_media_new_path, 'libvlc_media_new_path', failedList); GetAProcAddress(vlcHandle, @libvlc_media_add_option, 'libvlc_media_add_option', failedList); // if all functions loaded, result is an empty list, otherwise result is a list of functions failed Result := failedList.Count = 0; end; procedure TFormVLC.FormCreate(Sender: TObject); var sL: TStringList; begin // load vlc library vlcLib := LoadVLCLibrary(GetVLCLibPath()); if vlcLib = 0 then begin Showmessage('Load vlc library failed'); Exit; end; // sL will contains list of functions fail to load sL := TStringList.Create; if not LoadVLCFunctions(vlcLib, sL) then begin Showmessage('Some functions failed to load : ' + #13#10 + sL.Text); FreeLibrary(vlcLib); sL.Free; Exit; end; sL.Free; end; procedure TFormVLC.btnStopClick(Sender: TObject); begin if not Assigned(vlcMediaPlayer) then begin Showmessage('Not playing'); Exit; end; // stop vlc media player libvlc_media_player_stop(vlcMediaPlayer); // and wait until it completely stops while libvlc_media_player_is_playing(vlcMediaPlayer) = 1 do begin Sleep(100); end; // release vlc media player libvlc_media_player_release(vlcMediaPlayer); vlcMediaPlayer := nil; // release vlc instance libvlc_release(vlcInstance); end; procedure TFormVLC.FormClose(Sender: TObject; var Action: TCloseAction); begin // unload vlc library FreeLibrary(vlcLib); end; procedure TFormVLC.btnPlayClick(Sender: TObject); var str: AnsiString; begin // create new vlc instance vlcInstance := libvlc_new(0, nil); // create new vlc media from file // vlcMedia := libvlc_media_new_path(vlcInstance, 'd:\demo.mp4'); // if you want to play from network, use libvlc_media_new_location instead // vlcMedia := libvlc_media_new_location(vlcInstance, 'udp://@225.2.1.27:5127'); vlcMedia := libvlc_media_new_location(vlcInstance, 'rtsp://169.254.0.123:8557/h264'); // network-caching=200 // 預設為 1000 str := ':network-caching=200'; // :前面不能有空格 libvlc_media_add_option(vlcMedia, PAnsiChar(str)); // dxva2 硬體加速,若是 Win64 位元,則需要安裝 VLC 64 位元的版本 str := ':avcodec-hw=dxva2'; // :前面不能有空格 libvlc_media_add_option(vlcMedia, PAnsiChar(str)); // create new vlc media player vlcMediaPlayer := libvlc_media_player_new_from_media(vlcMedia); // now no need the vlc media, free it libvlc_media_release(vlcMedia); // play video in a TPanel, if not call this routine, vlc media will open a new window libvlc_media_player_set_hwnd(vlcMediaPlayer, Pointer(Panel1.Handle)); // play media libvlc_media_player_play(vlcMediaPlayer); end; end.
unit furqWinMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, JvSplit, JvMemo, JvExStdCtrls, JvExExtCtrls, JvExtComponent, ExtCtrls, XPMan, Menus, StdActns, ActnList, furqBase, furqContext, Buttons, JclStringLists, MMSystem; type TMainForm = class(TForm) pnlInput: TPanel; edtInput: TEdit; Panel2: TPanel; JvxSplitter1: TJvxSplitter; memTextOut: TJvMemo; JvxSplitter2: TJvxSplitter; lbButtons: TListBox; XPManifest1: TXPManifest; dlgOpenQuest: TOpenDialog; ActionList1: TActionList; actOpenQuest: TAction; actFileExit: TFileExit; MainMenu: TMainMenu; Afq1: TMenuItem; N1: TMenuItem; N2: TMenuItem; pnlInventory: TPanel; lbInventory: TListBox; Panel1: TPanel; btnAction: TSpeedButton; SaveDlg: TSaveDialog; N3: TMenuItem; actLoadSaved: TAction; N4: TMenuItem; LoadDlg: TOpenDialog; btnEnter: TButton; PauseTimer: TTimer; G1: TMenuItem; miAbout: TMenuItem; actStartOver: TAction; N5: TMenuItem; procedure FormDestroy(Sender: TObject); procedure actOpenQuestExecute(Sender: TObject); procedure lbButtonsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure memTextOutMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); procedure lbButtonsClick(Sender: TObject); procedure lbInventoryClick(Sender: TObject); procedure btnActionClick(Sender: TObject); procedure btnActionMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure lbButtonsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure actLoadSavedExecute(Sender: TObject); procedure actStartOverExecute(Sender: TObject); procedure btnEnterClick(Sender: TObject); procedure memTextOutKeyPress(Sender: TObject; var Key: Char); procedure miAboutClick(Sender: TObject); procedure PauseTimerTimer(Sender: TObject); private f_Code: TFURQCode; f_Interpreter: TFURQInterpreter; f_Context : TFURQWinContext; f_CurFilename: string; f_InvItem: Integer; f_InvMenus: IJclStringList; f_MusicIsPlaying: Boolean; procedure ActionsHandler(aSender: TObject); procedure ClearMenus; procedure ClearScreen; procedure ContinuePlayingMusic; procedure DoCls; procedure DoMusic; procedure DoPause; procedure DoSound; procedure FlushText; function GetMenuOnItem(const aItem: string): TPopupMenu; procedure HandleInput; procedure HandleInputKey; procedure InputkeyMode; procedure InputMode; procedure LoadButtonsAndActions; procedure NextTurn; procedure NormalMode; procedure OpenQuest(aFilename: string); procedure PlayMusic(aFilename: string); procedure SaveGame; procedure StartOver; procedure StartTimer(aInterval: Integer); procedure StopMusic; procedure StopTimer; protected procedure MMMCINOTIFY_Message(var Message: TMessage); message MM_MCINOTIFY; public { Public declarations } end; var MainForm: TMainForm; implementation uses furqTypes, furqAbout, furqLoader; {$R *.dfm} procedure TMainForm.ActionsHandler(aSender: TObject); var l_MI: TMenuItem; begin l_MI := TMenuItem(aSender); f_Context.StateResult := Format('m:%d,%d',[f_InvItem+1, l_MI.Tag]); f_Context.OutText(cCaretReturn); NextTurn; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(f_Context); FreeAndNil(f_Code); FreeAndNil(f_Interpreter); ClearMenus; StopMusic; end; procedure TMainForm.actOpenQuestExecute(Sender: TObject); begin if dlgOpenQuest.Execute then OpenQuest(dlgOpenQuest.Filename); end; procedure TMainForm.ClearMenus; var I: Integer; begin for I := 0 to f_InvMenus.LastIndex do f_InvMenus.Objects[I].Free; f_InvMenus.Clear; end; procedure TMainForm.FlushText; begin if f_Context.TextBuffer <> '' then begin memTextOut.Lines.Text := memTextOut.Lines.Text + f_Context.TextBuffer; SendMessage(memTextOut.Handle, EM_LINESCROLL, SB_LINEDOWN, MaxInt); f_Context.ClearTextBuffer; end; end; procedure TMainForm.lbButtonsMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var l_ItemIdx: Integer; l_LB: TListBox; begin l_LB := TListBox(Sender); l_ItemIdx := l_LB.ItemAtPos(Point(X, Y), True); if l_ItemIdx <> -1 then l_LB.ItemIndex := l_ItemIdx; if l_LB = lbInventory then lbButtons.ClearSelection else lbInventory.ClearSelection; end; procedure TMainForm.memTextOutMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin lbButtons.ClearSelection; lbInventory.ClearSelection; end; procedure TMainForm.FormCreate(Sender: TObject); var l_Bitmap: TBitmap; begin f_Interpreter := TFURQInterpreter.Create; f_InvMenus := JclStringList; f_InvMenus.CaseSensitive := False; l_Bitmap := TBitmap.Create; try l_Bitmap.Width := 1; l_Bitmap.Height := 1; l_Bitmap.PixelFormat := pf4bit; l_Bitmap.Canvas.Pixels[0,0] := clBlack;//memTextOut.Color; memTextOut.Caret.Bitmap := l_Bitmap; finally l_Bitmap.Free; end; Randomize; if ParamCount > 0 then OpenQuest(ParamStr(1)); end; function TMainForm.GetMenuOnItem(const aItem: string): TPopupMenu; var l_AIdx: Integer; l_MIdx: Integer; l_AList: IJclStringList; I: Integer; l_MI: TMenuItem; begin Result := nil; l_AIdx := f_Context.Code.ActionList.IndexOf(aItem); if l_AIdx < 0 then Exit; l_MIdx := f_InvMenus.IndexOf(aItem); if l_MIdx < 0 then begin Result := TPopupMenu.Create(Self); l_AList := f_Context.Code.ActionList.Lists[l_AIdx]; for I := 0 to l_AList.LastIndex do begin l_MI := TMenuItem.Create(Result); l_MI.Caption := l_AList.Strings[I]; l_MI.Tag := I+1; l_MI.OnClick := ActionsHandler; Result.Items.Add(l_MI); end; f_InvMenus.AddObject(aItem, Result); end else Result := TPopupMenu(f_InvMenus.Objects[l_MIdx]); end; procedure TMainForm.LoadButtonsAndActions; var l_Idx: Integer; l_GTitle: string; begin NormalMode; lbButtons.Items.Clear; lbButtons.Items.AddStrings(f_Context.Buttons); l_GTitle := EnsureString(f_Context.Variables['gametitle']); if l_GTitle <> '' then Caption := l_GTitle + ' - fireURQ' else Caption := 'fireURQ'; btnAction.Caption := f_Context.Variables['invname']; l_Idx := f_Context.Code.ActionList.IndexOf('inv'); btnAction.Enabled := l_Idx <> -1; lbInventory.Items.Clear; for l_Idx := 0 to f_Context.Inventory.LastIndex do lbInventory.Items.Add(f_Context.GetInventoryString(l_Idx)); end; procedure TMainForm.NextTurn; begin StopTimer; NormalMode; f_Interpreter.Execute(f_Context); FlushText; LoadButtonsAndActions; case f_Context.State of // csEnd : LoadButtonsAndActions; csSave : SaveGame; csInput : HandleInput; csInputKey: HandleInputKey; csPause : DoPause; csCls : DoCls; csMIDI : DoMusic; csSound : DoSound; end; end; procedure TMainForm.StartOver; begin FreeAndNil(f_Context); f_Context := TFURQWinContext.Create(f_Code, f_CurFilename); actLoadSaved.Enabled := True; actStartOver.Enabled := True; lbButtons.Items.Clear; StopMusic; NormalMode; memTextOut.Clear; lbButtons.Clear; lbInventory.Clear; NextTurn; end; procedure TMainForm.lbButtonsClick(Sender: TObject); var l_ItemIdx: Integer; begin l_ItemIdx := lbButtons.ItemAtPos(lbButtons.ScreenToClient(Mouse.CursorPos), True); if l_ItemIdx <> -1 then begin // на фантомные кнопки не реагируем вообще if TFURQButtonData(f_Context.Buttons.Objects[l_ItemIdx]).LabelIdx < 0 then Exit; f_Context.StateResult := 'b:' + IntToStr(l_ItemIdx); ClearScreen; NextTurn; end; end; procedure TMainForm.lbInventoryClick(Sender: TObject); var l_Menu: TPopupMenu; l_Rect: TRect; l_Point: TPoint; begin f_InvItem := lbInventory.ItemAtPos(lbInventory.ScreenToClient(Mouse.CursorPos), True); if f_InvItem <> -1 then begin l_Menu := GetMenuOnItem(f_Context.Inventory[f_InvItem]); if l_Menu <> nil then begin l_Rect := lbInventory.ItemRect(f_InvItem); l_Point.X := l_Rect.Left; l_Point.Y := l_Rect.Bottom; l_Point := lbInventory.ClientToScreen(l_Point); l_Menu.Popup(l_Point.X, l_Point.Y); end; end; end; procedure TMainForm.btnActionClick(Sender: TObject); var l_Menu: TPopupMenu; l_Point: TPoint; begin l_Menu := GetMenuOnItem('inv'); l_Point.X := 0; l_Point.Y := btnAction.Height; l_Point := btnAction.ClientToScreen(l_Point); f_InvItem := -1; l_Menu.Popup(l_Point.X, l_Point.Y); end; procedure TMainForm.btnActionMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin lbInventory.ClearSelection; end; procedure TMainForm.lbButtonsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin with lbButtons.Canvas do begin FillRect(Rect); if odDisabled in State then Font.Color := clGrayText else if TFURQButtonData(f_Context.Buttons.Objects[Index]).LabelIdx = -1 then Font.Color := clRed; if Index >= 0 then TextOut(Rect.Left + 2, Rect.Top+2, lbButtons.Items[Index]); end; end; procedure TMainForm.SaveGame; begin if SaveDlg.Execute then f_Context.StateResult := SaveDlg.FileName; NextTurn; end; procedure TMainForm.actLoadSavedExecute(Sender: TObject); begin if LoadDlg.Execute then begin f_Context.LoadFromFile(LoadDlg.Filename); ClearScreen; lbButtons.Clear; lbInventory.Clear; NextTurn; end; end; procedure TMainForm.actStartOverExecute(Sender: TObject); begin if MessageDlg('Вы уверены, что хотите начать игру сначала?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then StartOver; end; procedure TMainForm.ClearScreen; begin memTextOut.Clear; end; procedure TMainForm.HandleInput; begin InputMode; end; procedure TMainForm.InputMode; begin lbButtons.Items.Clear; lbButtons.Enabled := False; lbInventory.Enabled := False; pnlInput.Visible := True; edtInput.Text := ''; edtInput.SetFocus; end; procedure TMainForm.NormalMode; begin lbButtons.Enabled := True; lbInventory.Enabled := True; pnlInput.Visible := False; end; procedure TMainForm.btnEnterClick(Sender: TObject); begin f_Context.StateResult := edtInput.Text; NormalMode; NextTurn; end; procedure TMainForm.ContinuePlayingMusic; begin f_MusicIsPlaying := mciSendString('play urqmusic from 0 notify', nil, 0, Handle) = 0; end; procedure TMainForm.DoCls; procedure _ClearButtons; begin f_Context.ClearButtons; lbButtons.Clear; end; procedure _ClearScreen; begin memTextOut.Clear; end; begin with f_Context do begin if StateParam = 'B' then _ClearButtons else if StateParam = 'T' then _ClearScreen else begin _ClearButtons; _ClearScreen; end; end; Application.ProcessMessages; NextTurn; end; procedure TMainForm.DoMusic; begin if f_Context.StateParam = '' then StopMusic else PlayMusic(f_Context.StateParam); NextTurn; end; procedure TMainForm.DoPause; var l_Interval: Integer; begin l_Interval := Round(StrToFloatDef(f_Context.StateParam, 1000)); LoadButtonsAndActions; StartTimer(l_Interval); end; procedure TMainForm.DoSound; begin PlaySound(PChar(f_Context.StateParam), 0, SND_FILENAME or SND_ASYNC or SND_NODEFAULT); NextTurn; end; procedure TMainForm.HandleInputKey; begin InputKeyMode; end; procedure TMainForm.InputkeyMode; begin lbButtons.Enabled := False; lbInventory.Enabled := False; memTextOut.SetFocus; end; procedure TMainForm.memTextOutKeyPress(Sender: TObject; var Key: Char); begin if (f_Context <> nil) and (f_Context.State = csInputKey) then begin f_Context.StateResult := Key; NextTurn; end; end; procedure TMainForm.miAboutClick(Sender: TObject); begin with TAboutBox.Create(nil) do begin ShowModal; Free; end; end; procedure TMainForm.MMMCINOTIFY_Message(var Message: TMessage); begin inherited; if Message.wParam = MCI_NOTIFY_SUCCESSFUL then ContinuePlayingMusic; end; procedure TMainForm.OpenQuest(aFilename: string); var l_Ext : string; l_Source : string; l_FS : TFileStream; begin if FileExists(aFilename) then begin if f_Code <> nil then FreeAndNil(f_Code); f_Code := TFURQCode.Create; l_Ext := AnsiLowerCase(ExtractFileExt(aFilename)); l_FS := TFileStream.Create(aFilename, fmOpenRead); try if l_Ext = '.qs2' then l_Source := FURQLoadQS2(l_FS) else if l_Ext = '.qs1' then l_Source := FURQLoadQS1(l_FS) else l_Source := FURQLoadQST(l_FS); finally FreeAndNil(l_FS); end; f_Code.Load(l_Source); aFilename := ExpandFileName(aFileName); SetCurrentDir(ExtractFilePath(aFileName)); f_CurFilename := ExtractFileName(aFileName); ClearMenus; StartOver; end; end; procedure TMainForm.StartTimer(aInterval: Integer); begin PauseTimer.Interval := aInterval; PauseTimer.Enabled := True; end; procedure TMainForm.PauseTimerTimer(Sender: TObject); begin PauseTimer.Enabled := False; NextTurn; end; procedure TMainForm.PlayMusic(aFilename: string); var l_Str: string; begin if f_MusicIsPlaying then StopMusic; l_Str := Format('open sequencer!%s alias urqmusic', [aFileName]); if mciSendString(PChar(l_Str), nil, 0, 0) = 0 then ContinuePlayingMusic; end; procedure TMainForm.StopMusic; begin if f_MusicIsPlaying then mciSendString('close urqmusic', nil, 0, 0); end; procedure TMainForm.StopTimer; begin PauseTimer.Enabled := False; end; end.
unit l3PipeStream; {* Поток-труба. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3PipeStream - } { Начат: 11.05.2000 11:12 } { $Id: l3PipeStream.pas,v 1.22 2011/05/18 12:09:16 lulin Exp $ } // $Log: l3PipeStream.pas,v $ // Revision 1.22 2011/05/18 12:09:16 lulin // {RequestLink:266409354}. // // Revision 1.21 2010/03/18 14:15:46 lulin // {RequestLink:197951943}. // // Revision 1.20 2008/02/28 15:12:11 lulin // - переносим nevTools на модель. // // Revision 1.19 2007/08/14 14:30:13 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.18 2007/02/12 18:06:19 lulin // - переводим на строки с кодировкой. // // Revision 1.17 2007/02/12 16:40:36 lulin // - переводим на строки с кодировкой. // // Revision 1.16 2007/01/22 15:20:13 oman // - new: Локализация библиотек - l3 (cq24078) // // Revision 1.15 2005/04/19 15:41:51 lulin // - переходим на "правильный" ProcessMessages. // // Revision 1.14 2004/08/05 16:58:19 law // - new behavior: для Немезиса в оглавлении вместо имени документа выводим "Оглавление" (CQ OIT5-8572). // - избавился от ряда Warning'ов и Hint'ов. // // Revision 1.13 2002/05/23 13:00:18 law // - new beahvior: не перемещаем указатель, если стоим там где надо. // // Revision 1.12 2002/05/20 14:11:39 narry // - bug fix: подавление ошибки при завершении нити. // // Revision 1.11 2002/04/16 12:05:26 law // - new method: NotDone. // // Revision 1.10 2001/08/29 07:01:10 law // - split unit: l3Intf -> l3BaseStream, l3BaseDraw, l3InterfacedComponent. // // Revision 1.9 2001/07/27 15:46:04 law // - comments: xHelpGen. // // Revision 1.8 2000/12/15 15:19:01 law // - вставлены директивы Log. // {$Include l3Define.inc } interface uses Windows, Classes, SyncObjs, l3Types, l3Base, l3BaseStream, l3Memory, l3Interfaces, l3ProtoObject ; type Tl3PipeStream = class; Tl3Writer = class; Tl3WriterThread = class(Tl3Thread) {* Нить для работы писателя в трубу. } private {property fields} f_Stream : Tl3PipeStream; f_Writer : Tl3Writer; f_GapPool : Tl3MemoryPool; f_Percent : Long; protected {internal methods} procedure Release; override; {-} procedure UpdatePercent; {-} procedure ClearReferences; {-} public {public methods} constructor Create(CreateSuspended : Bool; aStream : Tl3PipeStream; aWriter : Tl3Writer); reintroduce; {* - создать нить. } procedure Execute; override; {-} function WriterCallBack(aWrittenSize: Long; aPercent: Long): Bool; {* - нотификация от писателя. } protected {protected properties} property Writer: Tl3Writer read f_Writer; {* - писатель. } public {public properties} property Stream: Tl3PipeStream read f_Stream; {* - поток. } end;{Tl3WriterThread} Tl3Writer = class(Tl3ProtoObject) {* Писатель в трубу. } private {property fields} f_WriterThread : Tl3WriterThread; f_HasData : Bool; protected {internal methods} function DoWriteProcess: Bool; virtual; abstract; {* - собственно процесс записи, для перекрытия в потомках. } procedure BeforeWriteProcess; virtual; {* - перед процессом записи, для перекрытия в потомках. } procedure AfterWriteProcess; virtual; {* - после процесса записи, для перекрытия в потомках. } procedure WriteProcessFinished(Sender: TObject); {-} procedure NotDone; virtual; {-} public {public methods} constructor Create{(anOwner: TObject = nil)}; //override; {-} procedure WriteProcess(aStream: Tl3PipeStream); {* - начать процесс записи. } procedure EndWriteProcess; {* - закончить процесс записи. } function InWriteProcess: Bool; {* - в процессе записи? } public {public properties} property HasData: Bool read f_HasData write f_HasData; {* - есть данные? } property WriterThread: Tl3WriterThread read f_WriterThread; {* - нить в контексте которой работает писатель. } end;{Tl3Writer} Tl3PipeStream = class(Tl3Stream) {* Поток-труба. } private {property fields} f_BufferCS : TCriticalSection; f_Buffer : Tl3MemoryPool; f_WrittenSize : Long; f_Offset : Long; f_Writer : Tl3Writer; f_Position : Long; f_Progress : Il3Progress; f_OriginalSize : Long; protected {internal methods} procedure Release; override; {-} public {public methods} constructor Create(aWriter : Tl3Writer; aBufferSize : Long; aOriginalSize : Long; const aProgress : Il3Progress = nil); reintroduce; {* - создать поток. } procedure LockBuffer; {* - начать операцию с буфером. } procedure UnlockBuffer; {* - закончить операцию с буфером. } function Read(var Buffer; Count: LongInt): LongInt; override; {-} function Seek(anOffset: LongInt; anOrigin: Word): LongInt; override; {-} public {public properties} property Buffer: Tl3MemoryPool read f_Buffer; {* - буфер потока. } property Offset: Long read f_Offset write f_Offset; {* - смещение в буфере. } property WrittenSize: Long read f_WrittenSize write f_WrittenSize; {* - сколько записано в поток? } end;{Tl3PipeStream} {* Поток-труба. Для использования в тех случаях когда процессом записи управляет один внешний объект, а процессом чтения - другой. То есть оба выполняют какие-то свои циклы и их надо синхронизировать.} implementation uses {$IfDef l3ConsoleApp} Messages, {$EndIf l3ConsoleApp} SysUtils, {$IfNDef l3ConsoleApp} Forms, {$EndIf l3ConsoleApp} l3MinMax, l3Math, l3IntegerValueMapManager, l3String, l3PipeStreamRes, afwFacade ; { start class Tl3PipeStream } constructor Tl3PipeStream.Create(aWriter : Tl3Writer; aBufferSize : Long; aOriginalSize : Long; const aProgress : Il3Progress = nil); {reintroduce;} {-} begin inherited Create; l3Set(f_Writer, aWriter); f_BufferCS := TCriticalSection.Create; f_Buffer := Tl3MemoryPool.Create; f_Buffer.Size := aBufferSize; f_Progress := aProgress; f_OriginalSize := aOriginalSize; if (f_Progress <> nil) then f_Progress.Start(100, str_l3mmReadFile.AsCStr); end; procedure Tl3PipeStream.Release; {override;} {-} begin if (f_Progress <> nil) then f_Progress.Finish; f_Progress := nil; l3Free(f_Writer); l3Free(f_Buffer); l3Free(f_BufferCS); inherited; end; procedure Tl3PipeStream.LockBuffer; {-} begin f_BufferCS.Enter; end; procedure Tl3PipeStream.UnlockBuffer; {-} begin f_BufferCS.Leave; end; function Tl3PipeStream.Read(var Buffer; Count: LongInt): LongInt; {override;} {-} {$IfDef l3ConsoleApp} procedure ProcessMessages; {-as there is no Tapplication available here} var Msg: TMsg; begin if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin if (Msg.Message <> WM_QUIT) then begin TranslateMessage(Msg); DispatchMessage(Msg); end;{Msg.Message <> WM_QUIT} end;{PeekMessage} end; {$EndIf l3ConsoleApp} var l_GapSize : Long; begin Result := 0; repeat LockBuffer; try l_GapSize := WrittenSize - Offset; if (l_GapSize >= Count) then begin l3Move(f_Buffer.AsPointer^, Buffer, Count); Result := Count; Inc(f_Offset, Result); Inc(f_Position, Result); break; {l_GapSize >= Count} end else if not f_Writer.HasData OR ((l_GapSize > 0) AND (Count > f_Buffer.Size)) then begin l3Move(f_Buffer.AsPointer^, Buffer, l_GapSize); Result := l_GapSize; Inc(f_Offset, Result); Inc(f_Position, Result); break; {not Writer.HasData} end; finally UnlockBuffer; end;{try..finally} with f_Writer do if not InWriteProcess then WriteProcess(Self); {$IfDef l3ConsoleApp} ProcessMessages; {$Else l3ConsoleApp} afw.ProcessMessages; {$EndIf l3ConsoleApp} Sleep(0); until false; end; function Tl3PipeStream.Seek(anOffset: LongInt; anOrigin: Word): LongInt; {override;} {-} var C : Char; begin Result := f_Position; LockBuffer; try Case anOrigin of soFromBeginning: begin if (anOffset >= 0) then begin if (f_Position <> anOffset) then begin f_Position := 0; Offset := 0; WrittenSize := 0; UnlockBuffer; try with f_Writer do begin EndWriteProcess; HasData := true; end;{with f_Writer} while (anOffset > 0) AND (Read(C, 1) = 1) do Dec(anOffset); finally LockBuffer; end;{try..finally} end;//f_Position <> anOffset Result := f_Position; end else raise Exception.CreateFmt('Неверное смещение в Tl3PipeStream %d', [anOffset]); end;{soFromBeginning} soFromCurrent: begin if (anOffset = 0) then Result := f_Position else if (anOffset > 0) then begin Inc(f_Offset, anOffset); Inc(f_Position, anOffset); Result := f_Position; if (Offset = WrittenSize) then begin WrittenSize := 0; Offset := 0; end else if (Offset > WrittenSize) then begin anOffset := Offset - WrittenSize; WrittenSize := 0; Offset := 0; UnlockBuffer; try while (anOffset > 0) AND (Read(C, 1) = 1) do Dec(anOffset); finally LockBuffer; end;{try..finally} end; end else begin if (Offset + anOffset >= 0) then begin Inc(f_Offset, anOffset); Inc(f_Position, anOffset); Result := f_Position; end else Result := Seek(f_Position + anOffset, soFromBeginning); end; end;{soFromCurrent} soFromEnd: if (anOffset <= 0) then Result := Seek(WrittenSize - anOffset, soFromCurrent) else raise Exception.CreateFmt('Неверное смещение в Tl3PipeStream %d', [anOffset]); else raise Exception.CreateFmt('Неверный код смещения в Tl3PipeStream %d', [anOrigin]); end;{Case anOrigin} finally UnlockBuffer; end;{try..finally} end; { start class Tl3Writer } constructor Tl3Writer.Create{(anOwner: TObject = nil)}; {override;} {-} begin inherited; HasData := true; end; procedure Tl3Writer.WriteProcess(aStream: Tl3PipeStream); {-} begin if not InWriteProcess then begin f_WriterThread := Tl3WriterThread.Create(true, aStream, Self); try with f_WriterThread do begin OnTerminate := WriteProcessFinished; FreeOnTerminate := true; BeforeWriteProcess; Resume; end; except l3Free(f_WriterThread); raise; end;{try..except} end;{not InWriteProcess} end; procedure Tl3Writer.EndWriteProcess; {-} begin if InWriteProcess then with f_WriterThread do begin Terminate; try WaitFor; except on EOSError do begin // - ловим ошибки ожидания завершения нити end;//EOSError end;//try..except end;{with f_WriterThread} end; procedure Tl3Writer.BeforeWriteProcess; //virtual; {-} begin end; procedure Tl3Writer.AfterWriteProcess; //virtual; {-} begin end; procedure Tl3Writer.WriteProcessFinished(Sender: TObject); {-} begin f_WriterThread := nil; HasData := false; AfterWriteProcess; end; procedure Tl3Writer.NotDone; //virtual; {-} begin end; function Tl3Writer.InWriteProcess: Bool; {-} begin Result := f_WriterThread <> nil; end; { start class Tl3WriterThread } constructor Tl3WriterThread.Create(CreateSuspended : Bool; aStream : Tl3PipeStream; aWriter : Tl3Writer); {reintroduce;} {-} begin l3Set(f_Stream, aStream); l3Set(f_Writer, aWriter); inherited Create(CreateSuspended); end; procedure Tl3WriterThread.ClearReferences; {-} begin l3Free(f_Stream); l3Free(f_Writer); l3Free(f_GapPool); end; procedure Tl3WriterThread.Release; {override;} {-} begin Synchronize(ClearReferences); inherited; end; procedure Tl3WriterThread.Execute; {override;} {-} var l_Done : Bool; begin Stream.LockBuffer; try with Writer do begin l_Done := DoWriteProcess; HasData := false; end;{with Writer} finally Stream.UnlockBuffer; end;{try..finally} if not l_Done then Writer.NotDone; end; procedure Tl3WriterThread.UpdatePercent; {-} begin Stream.f_Progress.Progress(f_Percent); end; function Tl3WriterThread.WriterCallBack(aWrittenSize: Long; aPercent: Long): Bool; {-} var l_GapSize : Long; begin Result := not Terminated; if Result then begin with Stream do begin if (f_GapPool = nil) then begin Offset := 0; WrittenSize := aWrittenSize end else begin l_GapSize := WrittenSize - Offset; with Buffer do begin Size := Max(aWrittenSize + l_GapSize, Size); if (l_GapSize > 0) then begin l3Move(AsPointer^, AsPointer[l_GapSize], aWrittenSize); l3Move(f_GapPool.AsPointer^, AsPointer^, l_GapSize); end;{l_GapSize > 0} WrittenSize := aWrittenSize + l_GapSize; Offset := 0; end;{with Buffer} end;{f_GapPool = nil} if (WrittenSize = 0) then Exit; UnlockBuffer; try f_Percent := aPercent; if (f_Percent = 0) then while (f_OriginalSize > 0) do begin f_Percent := l3MulDiv(f_Position, 100, f_OriginalSize); if (f_Percent <= 100) then break; Inc(f_OriginalSize, f_OriginalSize div 4); end;{while (f_OriginalSize > 0)} if (f_Progress <> nil) then Synchronize(UpdatePercent); {- здесь Reader может считать буфер} repeat Sleep(0); until (Offset > 0) OR Terminated; {- ждем пока хоть что-то считают} finally LockBuffer; end;{try..finally} if Terminated then Result := false else begin l_GapSize := WrittenSize - Offset; if (l_GapSize > 0) then begin {-кое-что осталось в буфере} if (f_GapPool = nil) then begin f_GapPool := Tl3MemoryPool.Create; f_GapPool.Size := l_GapSize; {f_GapPool = nil} end else f_GapPool.Size := Max(f_GapPool.Size, l_GapSize); l3Move(Buffer.AsPointer[Offset], f_GapPool.AsPointer^, l_GapSize); {Offset < WrittenSize} end else {-ничего не осталось - временный буфер не нужен} l3Free(f_GapPool); end;{Terminated} end;{with Stream} end;{Result} end; end.
unit main; interface {$I ..\Common\Defines.inc} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SyncObjs, ExtCtrls, clTcpServer, clFtpServer, clUserMgr, clFtpFileHandler, clUtils, clTcpCommandServer, clServerGuard, clTcpServerTls, DemoBaseFormUnit; type TMainForm = class(TclDemoBaseForm) btnStart: TButton; btnStop: TButton; memLog: TMemo; edtPort: TEdit; Label1: TLabel; Label2: TLabel; clFtpServer1: TclFtpServer; Label3: TLabel; edtRootDir: TEdit; clFtpFileHandler1: TclFtpFileHandler; Label4: TLabel; Label5: TLabel; GroupBox1: TGroupBox; clServerGuard1: TclServerGuard; Label6: TLabel; edtAllowedConnections: TEdit; Label7: TLabel; Label8: TLabel; memBlackList: TMemo; memWhiteList: TMemo; cbWhiteListOnly: TCheckBox; procedure clFtpServer1Stop(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure clFtpServer1AcceptConnection(Sender: TObject; AConnection: TclUserConnection; var Handled: Boolean); procedure clFtpServer1Authenticate(Sender: TObject; AConnection: TclFtpCommandConnection; var Account: TclFtpUserAccountItem; const AUserName, APassword: string; var IsAuthorized, Handled: Boolean); procedure clFtpServer1CloseConnection(Sender: TObject; AConnection: TclUserConnection); procedure clFtpServer1ReceiveCommand(Sender: TObject; AConnection: TclCommandConnection; ACommandParams: TclTcpCommandParams); procedure clFtpServer1SendResponse(Sender: TObject; AConnection: TclCommandConnection; const ACommand, AResponse: string); procedure clFtpServer1Start(Sender: TObject); procedure FormShow(Sender: TObject); private FSynchronizer: TCriticalSection; FIsStop: Boolean; procedure PutLogMessage(const ALogMessage: string); end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.clFtpServer1SendResponse(Sender: TObject; AConnection: TclCommandConnection; const ACommand, AResponse: string); begin PutLogMessage('Reply: ' + AResponse); end; procedure TMainForm.clFtpServer1Start(Sender: TObject); begin PutLogMessage('=================='#13#10'Start Server'); end; procedure TMainForm.clFtpServer1Stop(Sender: TObject); begin PutLogMessage('Stop Server'); end; procedure TMainForm.FormCreate(Sender: TObject); begin FSynchronizer := TCriticalSection.Create(); end; procedure TMainForm.FormDestroy(Sender: TObject); begin FSynchronizer.Free(); end; procedure TMainForm.PutLogMessage(const ALogMessage: string); begin if not (csDestroying in ComponentState) then begin FSynchronizer.Enter(); try memLog.Lines.Add(ALogMessage); finally FSynchronizer.Leave(); end; end; end; procedure TMainForm.btnStartClick(Sender: TObject); begin clServerGuard1.ConnectionLimit.Max := StrToInt(edtAllowedConnections.Text); clServerGuard1.ConnectionLimit.Period := 60000; //1 minute clServerGuard1.BlackIPList.Assign(memBlackList.Lines); clServerGuard1.WhiteIPList.Assign(memWhiteList.Lines); clServerGuard1.AllowWhiteListOnly := cbWhiteListOnly.Checked; clServerGuard1.Reset(); clFtpServer1.Port := StrToInt(edtPort.Text); clFtpServer1.RootDir := edtRootDir.Text; ForceFileDirectories(AddTrailingBackSlash(clFtpServer1.RootDir)); clFtpServer1.Start(); end; procedure TMainForm.btnStopClick(Sender: TObject); begin FIsStop := True; try clFtpServer1.Stop(); finally FIsStop := False; end; end; procedure TMainForm.clFtpServer1AcceptConnection(Sender: TObject; AConnection: TclUserConnection; var Handled: Boolean); begin PutLogMessage('Accept Connection. Host: ' + AConnection.PeerIP); end; procedure TMainForm.clFtpServer1Authenticate(Sender: TObject; AConnection: TclFtpCommandConnection; var Account: TclFtpUserAccountItem; const AUserName, APassword: string; var IsAuthorized, Handled: Boolean); begin if Account <> nil then begin PutLogMessage('Authenticate user: ' + Account.UserName); end; end; procedure TMainForm.clFtpServer1CloseConnection(Sender: TObject; AConnection: TclUserConnection); begin if not FIsStop then begin PutLogMessage('Close Connection. Host: ' + AConnection.PeerIP); end; end; procedure TMainForm.clFtpServer1ReceiveCommand(Sender: TObject; AConnection: TclCommandConnection; ACommandParams: TclTcpCommandParams); begin PutLogMessage('Command: ' + ACommandParams.Command + ' ' + ACommandParams.Parameters); end; procedure TMainForm.FormShow(Sender: TObject); begin {$IFDEF DELPHIX101} Height := 513; {$ENDIF} end; end.
unit HCInterfacesUnit; {* Интерфейсы для взаимодействия с отделом Пащака } // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\HCAdapterLib\HCInterfacesUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "HCInterfaces" MUID: (442BEF93030D) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses , IOUnit ; const {* Константы для адаптера консультаций. } STATISTIC_PACKET_SIZE_PARAMETER: PAnsiChar = -StatisticPacketSize; {* Параметр командной строки, задающий максимальное количество консультаций, которые могут быть спрошены за раз у СК (не накладывает ограничений на количество консультаций, передаваемых в метод GetStatusStatistic) } STATISTIC_PACKET_SIZE: size = 500; {* Значение по-умолчанию для максимального количества консультаций, которые могут быть спрошены за раз у СК (не накладывает ограничений на количество консультаций, передаваемых в метод GetStatusStatistic) } STATISTIC_SLEEP_TIME_PARAMETER: PAnsiChar = -StatisticSleepTime; {* Параметр командной строки, задающий время ожидания между посылкой запросов на статистику при большом числе консультаций. } STATISTIC_SLEEP_TIME: unsigned integer = 1; {* Время ожидания в секундах между посылкой запросов на статистику при большом числе консультаций. } {* текстовые значения ошибок в xml при удалении запросов из базы. } EES_INVALID_STATUS: PAnsiChar = INVALID_STATUS; {* консультация с текущим статусом не может быть удалена (чтобы её удалить необходимо указать атрибут force="yes") } EES_NOT_FOUND: PAnsiChar = NOT_FOUND; {* консультация с заданным идентификатором не найдена (например переехала из базы 6-ки в базу 7-ки) } EES_UNKNOWN: PAnsiChar = UNKNOWN; {* внутренняя ошибка СК } {* ключи мульти фабрик для интерфейса консультации } QUERY70: PAnsiChar = QUERY70; MARK70: PAnsiChar = MARK70; type IConsultingData = interface {* Интерфейс для получения и подтверждения факта получения запроса. } ['{E92828ED-9B9A-4302-8D42-37E413C6F434}'] procedure GetData(out aRet {* IStream }); stdcall; {* Получение данных запроса. Возвращается запрос (оценка) в XML формате (описание см в реквизите). } procedure DataReceived; stdcall; {* Подтверждение получения данных текущего запроса. При вызове этого метода запрос помечается как переданный на обработку (при получении оценки, как полностью обработанный). } end;//IConsultingData TResultValue = ( {* Возможные значения возвращаемых значений функций } RV_SUCCESS = 0 {* функция отработала успешно } , RV_DUPLICATED = 1 {* запрос в базе уже помечен, как отвеченный. } , RV_EMPTY = 2 {* на данный момент нет запросов данного типа } , RV_ERROR = -1 {* серверу не удалось прочесть ответ, или положить его в базу, или произошел еще какой-то внутренний сбой. В этом случае необходимо повторить попытку отдачи ответа. } , RV_BAD_XML = -2 {* формат ответа не соответствует "ожиданиям" сервера. } , RV_COMPLECT_REMOVED_ERROR = -3 {* комплект был удалён из АРМ-а (http://mdp.garant.ru/pages/viewpage.action?pageId=118982402) } , RV_INVALID_QUERY_ID = -4 {* данного идентификатора нет в базе } );//TResultValue TQueryID = PAnsiChar; CantFindXerces = class {* Не смогли загрузить библиотеку для работы с XML } end;//CantFindXerces IOnlineData = interface(IConsultingData) {* Консультации, проходящие через СК. Имеют уникальный идентификатор. } ['{43387100-5C41-4CCB-83EB-4EE5BB99C443}'] class function Make(var xml_stream: IStream; const consultation_id); stdcall; {* фабрика для получения интерфейса } end;//IOnlineData IBusinessLogicLifeCycle = interface {* Интерфейс для управления жизненным циклом бизнес-объектов адаптера } ['{AC92D75F-442C-4FFE-897D-23499B1BBC34}'] procedure Start; stdcall; {* метод должен быть вызван первым после загрузки dll библиотеки } procedure Stop; stdcall; {* метод должен быть вызван перед завершением работы библиотеки } procedure GetConsultationManager70; stdcall; {* получить интерфейс к СК версии 7 } end;//IBusinessLogicLifeCycle IConsultingRequests = interface {* Интерфейс для получения запросов от пользователей и их оценок. } ['{EB5AE11E-74DA-4DFE-950B-CE68586C28F1}'] function GetQueryById(query_id: TQueryID; out data: IConsultingData): TResultValue; stdcall; {* получить следующий запрос для обработки } function GetNextMark(out data: IConsultingData): TResultValue; stdcall; {* Получение очередной оценки на запрос. При вызове этой операции происходит передача объекта "Оценка" для получения данных. До тех пор пока не будет проведен вызов DataRecieved, эта операция будет возвращать этот запрос. Если нет ни одного нового запроса, получившего оценку пользователя, возвращается нулевой объект. } function SetAnswer(var answer: IStream): TResultValue; stdcall; {* Ответ на запрос или предварительное уведомление о сроках обработки запроса. Ответ оформлен в XML формате (описание cм. в реквизите). Варианты возвращаемых значений: [0] - если ответ успешно помещен в базу. [1] - если запрос в базе уже помечен, как отвеченный. [-1] - если серверу не удалось прочесть ответ, или положить его в базу, или произошел еще какой-то внутренний сбой. В этом случае необходимо повторить попытку отдачи ответа. [-2] - если формат ответа не соответствует "ожиданиям" сервера. } function GetStatusStatistic(var query: IStream; out result: IStream): TResultValue; stdcall; {* функция выдаёт статусы консультаций и даты их последней модификации по их идентификаторам. } function EraseQueriesById(var query: IStream; out result: IStream): TResultValue; stdcall; {* удалить запросы из базы СК } function SignQuery(var query: IStream; out signed_query: IStream): TResultValue; stdcall; {* добавить в xml контрольную сумму } function GetListOfNewQueries(out result: IStream): TResultValue; stdcall; {* получить список идентификаторов консультаций, которые нужно забрать на обработку в ППО } end;//IConsultingRequests implementation uses l3ImplUses ; end.
unit GameTypes; interface uses Windows, Classes, Warnings, SpriteImages, SpeedBmp; type index = 0..0; const // Focus kinds (0..9 ~ Reserved) fkSelection = 0; type TGameImage = TFrameImage; TCanvasImage = TSpeedBitmap; type TZoomLevel = integer; TRotation = (drNorth, drEast, drSouth, drWest); type IGameUpdater = interface function Lock : integer; function Unlock : integer; function LockCount : integer; procedure QueryUpdate(Defer : boolean); end; type IGameView = interface; IGameFocus = interface(IGameUpdater) procedure MouseMove(x, y : integer); procedure MouseClick; procedure KeyPressed(which : word; const Shift : TShiftState); procedure Refresh; function GetText(kind : integer) : string; function GetObject : TObject; procedure Dispatch(var msg); function GetRect : TRect; procedure SetRect(const R : TRect); end; IGameDocument = interface; TOnRegionsUpdateNotification = procedure (const view : IGameView; const Regions : array of TRect) of object; TOnRegionsUpdateDoneNotification = procedure (const view : IGameView) of object; IGameView = interface(IGameUpdater) // private function GetOrigin : TPoint; procedure SetOrigin(const which : TPoint); function GetDocument : IGameDocument; procedure SetDocument(const which : IGameDocument); function GetZoomLevel : TZoomLevel; procedure SetZoomLevel(which : TZoomLevel); function GetRotation : TRotation; procedure SetRotation(which : TRotation); procedure SetOnRegionsUpdate(OnRegionsUpdate : TOnRegionsUpdateNotification); procedure SetOnRegionsUpdateDone(OnRegionsUpdateDone : TOnRegionsUpdateDoneNotification); // public procedure UpdateRegions(const which : array of TRect); function GetFocus : IGameFocus; function GetSize : TPoint; property Origin : TPoint read GetOrigin write SetOrigin; property Size : TPoint read GetSize; property Document : IGameDocument read GetDocument write SetDocument; property ZoomLevel : TZoomLevel read GetZoomLevel write SetZoomLevel; property Rotation : TRotation read GetRotation write SetRotation; property OnRegionsUpdate : TOnRegionsUpdateNotification write SetOnRegionsUpdate; property OnRegionsUpdateDone : TOnRegionsUpdateDoneNotification write SetOnRegionsUpdateDone; end; IGameDocument = interface procedure RenderSnapshot(const view : IGameView; const ClipRect : TRect; target : TCanvasImage); function ClipMovement(const view : IGameView; var dx, dy : integer) : boolean; function CreateFocus(const view : IGameView) : IGameFocus; procedure ViewChanged(const view : IGameView); end; implementation end.
unit UCloudConvertDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomConvert, FMX.TMSCloudConvert, FMX.Objects, FMX.ListBox, FMX.Layouts, FMX.Memo; type TForm11 = class(TForm) TMSFMXCloudConvert1: TTMSFMXCloudConvert; GroupBox1: TGroupBox; Label2: TLabel; lbInputFile: TLabel; GroupBox2: TGroupBox; GroupBox3: TGroupBox; lbProgress: TLabel; ProgressBar1: TProgressBar; GroupBox4: TGroupBox; Label1: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; lbStartTime: TLabel; lbEndTime: TLabel; lbInputFileSize: TLabel; lbOutputFileSize: TLabel; lbOutputFileName: TLabel; lbOutputDownload: TLabel; Label4: TLabel; cbOutput: TComboBox; btConvert: TButton; Image1: TImage; Memo1: TMemo; procedure btConvertClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TMSFMXCloudConvert1DownloadProgress(Sender: TObject; FileName: string; Position, Total: Int64); procedure TMSFMXCloudConvert1UploadProgress(Sender: TObject; FileName: string; Position, Total: Int64); private { Private declarations } public { Public declarations } procedure InitLabels; end; var Form11: TForm11; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // CloudConvertAppkey = 'xxxxxxxxx'; {$I APPIDS.INC} procedure TForm11.btConvertClick(Sender: TObject); var sv: TSaveDialog; InputFile, OutputFile, OutputFormat: string; txtFile: TStringList; begin ProgressBar1.Value := 0; InitLabels; btConvert.Enabled := false; InputFile := lbInputFile.Text; OutputFormat := cbOutput.Items[cbOutput.ItemIndex]; OutputFile := 'OrderTMScomponents.' + OutputFormat; sv := TSaveDialog.Create(Self); sv.FileName := OutputFile; if sv.Execute then begin if TMSFMXCloudConvert1.ConvertAndDownload(InputFile, sv.FileName) then begin lbStartTime.Text := DateTimeToStr(TMSFMXCloudConvert1.ConvertResult.StartTime); lbEndTime.Text := DateTimeToStr(TMSFMXCloudConvert1.ConvertResult.EndTime); lbOutputDownload.Text := DateTimeToStr(TMSFMXCloudConvert1.ConvertResult.ExpiryTime); lbInputFileSize.Text := IntToStr( TMSFMXCloudConvert1.ConvertResult.InputFile.FileSize); lbOutputFileSize.Text := IntToStr( TMSFMXCloudConvert1.ConvertResult.OutputFile.FileSize); lbOutputFileName.Text := TMSFMXCloudConvert1.ConvertResult.OutputFile.FileName; if FileExists(sv.FileName) then begin if OutputFormat <> 'TXT' then begin Image1.Visible := true; Memo1.Visible := false; Image1.Bitmap.LoadFromFile(sv.FileName); end else begin Image1.Visible := false; Memo1.Visible := true; txtFile := TStringList.Create; txtFile.LoadFromFile(sv.FileName); Memo1.Text := txtFile.Text; txtFile.Free; end; end; end else begin lbStartTime.Text := 'Conversion failed, please try again.'; end; end; btConvert.Enabled := true; end; procedure TForm11.FormCreate(Sender: TObject); begin InitLabels; cbOutput.ItemIndex := 0; TMSFMXCloudConvert1.App.Key := CloudConvertAppKey; end; procedure TForm11.InitLabels; begin lbStartTime.Text := ''; lbEndTime.Text := ''; lbOutputDownload.Text := ''; lbInputFileSize.Text := ''; lbOutputFileSize.Text := ''; lbOutputFileName.Text := ''; end; procedure TForm11.TMSFMXCloudConvert1DownloadProgress(Sender: TObject; FileName: string; Position, Total: Int64); begin ProgressBar1.Value := Position; ProgressBar1.Max := Total; lbProgress.Text := InttoStr(Position) +' of ' + InttoStr(Total) +' downloaded'; end; procedure TForm11.TMSFMXCloudConvert1UploadProgress(Sender: TObject; FileName: string; Position, Total: Int64); begin ProgressBar1.Value := Position; ProgressBar1.Max := Total; lbProgress.Text := InttoStr(Position) +' of ' + InttoStr(Total) +' uploaded'; end; end.
unit StdFluids; interface const tidFluid_ConstructionForce = 'Construction'; tidFluid_Machinery = 'Machinery'; tidFluid_FreshFood = 'FreshFood'; tidFluid_OrganicMat = 'OrganicMat'; tidFluid_Chemicals = 'Chemicals'; tidFluid_LegalServ = 'LegalServ'; tidFluid_CompServ = 'CompServ'; tidFluid_Ore = 'Ore'; tidFluid_OreChems = 'OreChems'; tidFluid_OreSilicon = 'OreSilicon'; tidFluid_OreStone = 'OreStone'; tidFluid_OreCoal = 'OreCoal'; tidFluid_ElabFood = 'ElabFood'; tidFluid_Metals = 'Metals'; tidFluid_Plastics = 'Plastics'; tidFluid_Drugs = 'Drugs'; tidFluid_ElectComp = 'ElectComp'; tidFluid_BusinessMachines = 'BusinessMachines'; tidFluid_Cars = 'Cars'; tidFluid_FabThreads = 'FabricThreads'; tidFluid_Clothes = 'Clothes'; tidFluid_HouseHoldingAppliances = 'HouseHoldingAppliances'; tidFluid_Toys = 'Toys'; tidFluid_Oil = 'Oil'; tidFluid_Gasoline = 'Gasoline'; tidFluid_Liquors = 'Liquors'; tidFluid_Advertisement = 'Advertisement'; tidFluid_Films = 'Films'; tidFluid_Timber = 'Timber'; tidFluid_Furniture = 'Furniture'; tidFluid_Books = 'Books'; tidFluid_Paper = 'Paper'; tidFluid_CDs = 'CDs'; tidFluid_PrintedMaterial = 'PrintedMaterial'; const unid_None = 0; unid_Advertisement = 1; unid_CompServ = 2; unid_LegalServ = 3; const tidGate_ConstructionForce = tidFluid_ConstructionForce; tidGate_Machinery = tidFluid_Machinery; tidGate_FreshFood = tidFluid_FreshFood; tidGate_OrganicMat = tidFluid_OrganicMat; tidGate_Chemicals = tidFluid_Chemicals; tidGate_LegalServ = tidFluid_LegalServ; tidGate_CompServ = tidFluid_CompServ; tidGate_Ore = tidFluid_Ore; tidGate_ElabFood = tidFluid_ElabFood; tidGate_Metals = tidFluid_Metals; tidGate_Plastics = tidFluid_Plastics; tidGate_Gasoline = tidFluid_Gasoline; tidGate_Oil = tidFluid_Oil; tidGate_OreChems = tidFluid_OreChems; tidGate_OreSilicon = tidFluid_OreSilicon; tidGate_OreStone = tidFluid_OreStone; tidGate_OreCoal = tidFluid_OreCoal; tidGate_Drugs = tidFluid_Drugs; tidGate_ElectComp = tidFluid_ElectComp; tidGate_BusinessMachines = tidFluid_BusinessMachines; tidGate_Cars = tidFluid_Cars; tidGate_FabThreads = tidFluid_FabThreads; tidGate_Clothes = tidFluid_Clothes; tidGate_HouseHoldingAppliances = tidFluid_HouseHoldingAppliances; tidGate_Toys = tidFluid_Toys; tidGate_Liquors = tidFluid_Liquors; tidGate_Advertisement = tidFluid_Advertisement; tidGate_Films = tidFluid_Films; tidGate_Timber = tidFluid_Timber; tidGate_Furniture = tidFluid_Furniture; tidGate_Books = tidFluid_Books; tidGate_Paper = tidFluid_Paper; tidGate_CDs = tidFluid_CDs; tidGate_PrintedMaterial = tidFluid_PrintedMaterial; procedure RegisterMetaFluids; implementation uses Kernel, MediaGates; // RegisterMetaFluids procedure RegisterMetaFluids; begin with TMetaFluid.Create( tidFluid_ConstructionForce, 'Construction Force', 'Construction Force', 'tons', 'tons/day', 24, 0.001, 1000, 100 ) do begin Options := Options + [mfTradeable, mfImportable, mfConstruction]; StorageVol := 500000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Machinery, 'Machinery', 'Machinery', 'machines', 'machines/day', 24, 0.0005, 400, 8000 ) do begin Options := Options + [mfTradeable, mfImportable, mfConstruction]; StorageVol := 5000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_FreshFood, 'Fresh Food', 'Fresh food is produced mainly by farms. It englobes vegetables, grains and meat.', 'kg', 'kg/day', 24, 0.0008, 1, 4 ) do begin Options := Options + [mfStorable, mfTradeable]; StorageVol := 5000000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_OrganicMat, 'Organic Materials', 'Vegetal fibers and other subproducts of farms.', 'kg', 'kg/day', 24, 0.0002, 1, 10 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 1000000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Chemicals, 'Chemicals', 'All kind of chemical products.', 'kg', 'kg/day', 24, 0.0005, 1, 20 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 100000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_LegalServ, 'Legal Services', 'Legal counceling services. This will make a facility more competitive.', 'hours', 'hours/week', 7*24, 0.0001, 80, 250 ) do begin Options := Options + [mfTradeable, mfCompanyFluid, mfImportable]; UNId := unid_LegalServ; CnxLimit := 500; StorageVol := 0; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_CompServ, 'Computer Services', 'Information management, process automatization.', 'hours', 'hours/week', 7*24, 0.0001, 80, 200 ) do begin Options := Options + [mfTradeable, mfCompanyFluid, mfImportable]; UNId := unid_CompServ; CnxLimit := 500; StorageVol := 0; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Ore, 'Ore', 'All kind of mineral products not ready yet for industrials applications.', 'kg', 'kg/day', 24, 0.0005, 1, 1 ) do begin Options := Options + [mfImportable, mfTradeable]; StorageVol := 100000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_OreChems, 'Raw Chemicals', 'Raw chemicals. Have to be processed to obtain usable chemical products.', 'kg', 'kg/day', 24, 0.0005, 1, 1 ) do begin Options := Options + [mfImportable, mfTradeable]; StorageVol := 100000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_OreSilicon, 'Silicon', 'Silicon used at electronic component factories.', 'kg', 'kg/day', 24, 0.0005, 1, 1 ) do begin Options := Options + [mfImportable, mfTradeable]; StorageVol := 200000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_OreStone, 'Stone', 'Stone is used to produce construction materials.', 'kg', 'kg/day', 24, 0.0005, 1, 1 ) do begin Options := Options + [mfImportable, mfTradeable]; StorageVol := 200000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_OreCoal, 'Coal', 'Coal is required by metal plants.', 'kg', 'kg/day', 24, 0.0005, 1, 1 ) do begin Options := Options + [mfImportable, mfTradeable]; StorageVol := 200000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_ElabFood, 'Processed Food', 'All kind of elaborated food ready for consuming.', 'items', 'items/day', 24, 0.0001, 1, 15 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 2500000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Metals, 'Metals', 'All kind of metals ready for industrial applications.', 'kg', 'kg/day', 24, 0.0005, 1, 8 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 25000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Plastics, 'Plastics', 'All kind of Plastics ready for industrial applications.', 'kg', 'kg/day', 24, 0.0001, 1, 5 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 20000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Drugs, 'Pharmaceutics', 'Pharmaceutics.', 'kg', 'kg/day', 24, 0.0004, 1, 40 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_ElectComp, 'Electronic Components', 'All kind of metals ready for industrial applications.', 'items', 'items/day', 24, 0.0002, 1, 50 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_BusinessMachines, 'Business Machines', 'Business machines such as computers, printers, photocopiers, ect.', 'items', 'items/day', 24, 0.001, 4, 800 ) do begin Options := Options + [mfTradeable, mfStorable, mfImportable, mfConstruction]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_HouseHoldingAppliances, 'Household appliances', 'Any domestic device, refrigerators, washing machines, air conditioners, etc.', 'items', 'items/day', 24, 0.0005, 10, 110 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Oil, 'Crude Oil', 'Oil.', 'lt', 'lt/day', 24, 0.0002, 10, 0.2 ) do begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 100000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Gasoline, 'Gasoline', 'Gasoline.', 'lt', 'lt/day', 24, 0.0002, 10, 0.7 ) do begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 100000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Toys, 'Toys', 'Toys.', 'items', 'items/day', 24, 0.0005, 10, 32 ) do begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Cars, 'Cars', 'Cars.', 'cars', 'cars/week', 24*7, 0.001, // ?????? 800, 7000 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 200; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_FabThreads, 'Fabrics and Threads', 'Fabric and thread ready for looming.', 'meters', 'meters/day', 24, 0.0002, 2, 6 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Clothes, 'Clothes', 'Stuff to wear on.', 'items', 'items/day', 24, 0.0001, 1, 25 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 10000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Liquors, 'Liquors', 'Any kind of booze', 'items', 'items/day', 24, 0.0002, 1, 5 ) do begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 2500000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Advertisement, 'Advertisement', 'Advertisement', 'hits', 'hits/day', 24, 0, 0, 0.5 ) do begin Options := Options + [mfTradeable, mfImportable, mfCompanyFluid]; UNId := unid_Advertisement; CnxLimit := 500; StorageVol := 0; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Films, 'Films', 'Movies', 'Films', 'Films/day', 1, // 24 0.00002, 1, 50) do begin Options := Options + [mfTradeable, mfStorable, mfImportable]; CnxLimit := 500; StorageVol := 0; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Timber, 'Timber', 'Any kind of timber', 'kg', 'kg/day', 24, 0.0005, 700, 2 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 500000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Furniture, 'Furniture', 'Furniture for home', 'items', 'items/day', 24, 0.0005, 700, 100 ) do begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 15000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Books, 'Books', 'Books in general', 'books', 'books/day', 24, 0.0001, 700, 15 ) do begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 20000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_Paper, // id of the fluid 'Paper', // name 'Paper in general', // desc 'kg', // unit nme 'kg/day', // fluid name/time 24, // number of hours the above means 0.0005, // transp cost 700, // ?? 15 ) do // unit cost begin Options := Options + [mfTradeable, mfImportable, mfStorable]; StorageVol := 250000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_CDs, // id of the fluid 'Compact Discs', // name 'Music Compact Discs', // desc 'CD', // unit nme 'CD/day', // fluid name/time 24, // number of hours the above means 0.0001, // transp cost 700, // ?? 15 ) do // unit cost begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 25000; Register( 'Fluids' ); end; with TMetaFluid.Create( tidFluid_PrintedMaterial, // id of the fluid 'Printed Material', // name 'Brochures, Flyers, etc.', // desc 'kg', // unit nme 'kg/day', // fluid name/time 24, // number of hours the above means 0.0005, // transp cost 700, // ?? 25 ) do // unit cost begin Options := Options + [mfTradeable, mfStorable, mfImportable]; StorageVol := 25000; Register( 'Fluids' ); end; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } { ElInterfaceClasses unit: } { Copyright (c) 2001 Akzhan Abdulin } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElInterfaceClasses; interface uses Classes; type { IElObjectIdentity enables identity tests } IElObjectIdentity = interface ['{0C5A6289-FFE6-4DE3-B9D2-4E0B22D1A9E4}'] function SameIdentity(ARef: IUnknown): Boolean; end; { IElObjectIdentity2 internally serves to test identity and meets ITC, IPC } IElObjectIdentity2 = interface ['{1847D467-CF11-4370-B5FF-762951CA0FA5}'] function GetIdentity: Pointer; end; TElCustomIdentifiedObject = class(TInterfacedObject, IElObjectIdentity, IElObjectIdentity2) private FIdentity: Pointer; protected { IElObjectIdentity } function SameIdentity(ARef: IUnknown): Boolean; { IElObjectIdentity2 } function GetIdentity: Pointer; public procedure AfterConstruction; override; end; IElComparableObject = interface(IElObjectIdentity) ['{9D9174AC-5243-433C-A54C-6349E5D5778F}'] function Compare(ARef: IUnknown): Integer; end; { IElInterfaceList provides additional FastGet method } IElInterfaceList = interface(IInterfaceList) ['{BB275413-8170-4DDF-8843-B0288F5DDD3F}'] function FastGet(Index: Integer): IUnknown; function Get(Index: Integer): IUnknown; function GetCapacity: Integer; function GetCount: Integer; procedure Put(Index: Integer; Item: IUnknown); procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); procedure Clear; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); function First: IUnknown; function IndexOf(Item: IUnknown): Integer; function Add(Item: IUnknown): Integer; procedure Insert(Index: Integer; Item: IUnknown); function Last: IUnknown; function Remove(Item: IUnknown): Integer; procedure Lock; procedure Unlock; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: IUnknown read Get write Put; default; end; { TElInterfaceList accepts duplicates } TElInterfaceList = class(TInterfacedObject, IElInterfaceList, IInterfaceList) private FList: TThreadList; protected { IElInterfaceList } function FastGet(Index: Integer): IUnknown; function Get(Index: Integer): IUnknown; function GetCapacity: Integer; function GetCount: Integer; procedure Put(Index: Integer; Item: IUnknown); procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); public constructor Create; destructor Destroy; override; procedure Clear; procedure Delete(Index: Integer); procedure Exchange(Index1, Index2: Integer); function Expand: TElInterfaceList; function First: IUnknown; function IndexOf(Item: IUnknown): Integer; function Add(Item: IUnknown): Integer; procedure Insert(Index: Integer; Item: IUnknown); function Last: IUnknown; function Remove(Item: IUnknown): Integer; procedure Lock; procedure Unlock; property Capacity: Integer read GetCapacity write SetCapacity; property Count: Integer read GetCount write SetCount; property Items[Index: Integer]: IUnknown read Get write Put; default; end; IElInterfaceStack = interface ['{26DF724D-0250-4B7F-9E26-13C664F20D20}'] procedure Push(Value: IUnknown); function GetFront: IUnknown; function Pop: IUnknown; procedure Clear; function Empty: Boolean; end; TElInterfaceStack = class(TInterfacedObject, IElInterfaceStack) private FList: IInterfaceList; protected { IElInterfaceStack } procedure Push(Value: IUnknown); function GetFront: IUnknown; function Pop: IUnknown; procedure Clear; function Empty: Boolean; public procedure AfterConstruction; override; end; IElAttributeList = interface ['{47F41D19-EE3C-4E0A-9F06-3CEF29F64000}'] function GetText: String; procedure SetText(const Text: String); function GetName(const Index: Integer): String; function GetValue(const Index: Integer): String; procedure SetValue(const Index: Integer; const AValue: String); function GetCount: Integer; function GetAttribute(const AName: String): String; procedure SetAttribute(const AName: String; const AValue: String; Additive: Boolean); procedure _SetAttribute(const AName: String; const AValue: String); procedure RemoveAttribute(const AName: String); procedure Clear; property Text: String read GetText write SetText; property Names[const Index: Integer]: String read GetName; property Values[const Index: Integer]: String read GetValue write SetValue; property Count: Integer read GetCount; property Attributes[const Name: String]: String read GetAttribute write _SetAttribute; end; TElAttributeList = class(TInterfacedObject, IElAttributeList) private FNames: TStrings; FValues: TStrings; protected { IElAttributeList } function GetText: String; procedure SetText(const Text: String); function GetName(const Index: Integer): String; function GetValue(const Index: Integer): String; procedure SetValue(const Index: Integer; const AValue: String); function GetCount: Integer; function GetAttribute(const AName: String): String; procedure SetAttribute(const AName: String; const AValue: String; Additive: Boolean); procedure _SetAttribute(const AName: String; const AValue: String); procedure RemoveAttribute(const AName: String); procedure Clear; public procedure AfterConstruction; override; destructor Destroy; override; end; implementation uses SysUtils, Consts; { TElCustomIdentifiedObject } procedure TElCustomIdentifiedObject.AfterConstruction; begin inherited; FIdentity := Self; end; function TElCustomIdentifiedObject.GetIdentity: Pointer; begin Result := FIdentity; end; function TElCustomIdentifiedObject.SameIdentity( ARef: IUnknown): Boolean; var Id: IElObjectIdentity2; begin Result := Supports(ARef, IElObjectIdentity2, Id) and (FIdentity = Id.GetIdentity); end; { TElInterfaceList } constructor TElInterfaceList.Create; begin inherited Create; FList := TThreadList.Create; FList.Duplicates := dupAccept; end; destructor TElInterfaceList.Destroy; begin Clear; FList.Free; inherited Destroy; end; procedure TElInterfaceList.Clear; var I: Integer; begin if FList <> nil then begin with FList.LockList do try for I := 0 to Count - 1 do IUnknown(List[I]) := nil; Clear; finally Self.FList.UnlockList; end; end; end; procedure TElInterfaceList.Delete(Index: Integer); begin with FList.LockList do try Self.Put(Index, nil); Delete(Index); finally Self.FList.UnlockList; end; end; function TElInterfaceList.Expand: TElInterfaceList; begin with FList.LockList do try Expand; Result := Self; finally Self.FList.Unlocklist; end; end; function TElInterfaceList.First: IUnknown; begin Result := Get(0); end; function TElInterfaceList.Get(Index: Integer): IUnknown; begin with FList.LockList do try if (Index < 0) or (Index >= Count) then Error(@SListIndexError, Index); Result := IUnknown(List[Index]); finally Self.FList.UnlockList; end; end; function TElInterfaceList.GetCapacity: Integer; begin with FList.LockList do try Result := Capacity; finally Self.FList.UnlockList; end; end; function TElInterfaceList.GetCount: Integer; begin with FList.LockList do try Result := Count; finally Self.FList.UnlockList; end; end; function TElInterfaceList.IndexOf(Item: IUnknown): Integer; begin with FList.LockList do try Result := IndexOf(Pointer(Item)); finally Self.FList.UnlockList; end; end; function TElInterfaceList.Add(Item: IUnknown): Integer; begin with FList.LockList do try Result := Add(nil); IUnknown(List[Result]) := Item; finally Self.FList.UnlockList; end; end; procedure TElInterfaceList.Insert(Index: Integer; Item: IUnknown); begin with FList.LockList do try Insert(Index, nil); IUnknown(List[Index]) := Item; finally Self.FList.UnlockList; end; end; function TElInterfaceList.Last: IUnknown; begin with FList.LockList do try Result := Self.Get(Count - 1); finally Self.FList.UnlockList; end; end; procedure TElInterfaceList.Put(Index: Integer; Item: IUnknown); begin with FList.LockList do try if (Index < 0) or (Index >= Count) then Error(@SListIndexError, Index); IUnknown(List[Index]) := Item; finally Self.FList.UnlockList; end; end; function TElInterfaceList.Remove(Item: IUnknown): Integer; begin with FList.LockList do try Result := IndexOf(Pointer(Item)); if Result > -1 then begin IUnknown(List[Result]) := nil; Delete(Result); end; finally Self.FList.UnlockList; end; end; procedure TElInterfaceList.SetCapacity(NewCapacity: Integer); begin with FList.LockList do try Capacity := NewCapacity; finally Self.FList.UnlockList; end; end; procedure TElInterfaceList.SetCount(NewCount: Integer); begin with FList.LockList do try Count := NewCount; finally Self.FList.UnlockList; end; end; procedure TElInterfaceList.Exchange(Index1, Index2: Integer); begin with FList.LockList do try Exchange(Index1, Index2); finally Self.FList.UnlockList; end; end; procedure TElInterfaceList.Lock; begin FList.LockList; end; procedure TElInterfaceList.Unlock; begin FList.UnlockList; end; function TElInterfaceList.FastGet(Index: Integer): IUnknown; begin Result := IUnknown(FList.LockList.List[Index]); FList.UnlockList; end; { TElInterfaceStack } procedure TElInterfaceStack.AfterConstruction; begin inherited; FList := TElInterfaceList.Create; end; procedure TElInterfaceStack.Clear; begin FList.Clear; end; function TElInterfaceStack.Empty: Boolean; begin Result := (FList.Count = 0); end; function TElInterfaceStack.GetFront: IUnknown; begin Result := FList.Last; end; function TElInterfaceStack.Pop: IUnknown; var Index: Integer; begin with FList do begin Lock; try Index := Pred(Count); Result := Items[Index]; Delete(Index); finally Unlock; end; end; end; procedure TElInterfaceStack.Push(Value: IUnknown); begin FList.Add(Value); end; { TElAttributeList } procedure TElAttributeList._SetAttribute(const AName, AValue: String); begin SetAttribute(AName, AValue, False); end; procedure TElAttributeList.AfterConstruction; begin inherited; FNames := TStringList.Create; FValues := TStringList.Create; end; procedure TElAttributeList.Clear; begin FNames.Clear; FValues.Clear; end; destructor TElAttributeList.Destroy; begin FNames.Free; FValues.Free; inherited; end; function TElAttributeList.GetAttribute(const AName: String): String; var Index: Integer; begin Index := FNames.IndexOf(AName); if Index >= 0 then begin Result := FValues[Index]; end else begin Result := ''; end; end; function TElAttributeList.GetCount: Integer; begin Result := FNames.Count; end; function TElAttributeList.GetName(const Index: Integer): String; begin Result := FNames[Index]; end; function TElAttributeList.GetText: String; var I: Integer; Name: String; Value: String; begin Result := ''; for I := 0 to Pred(FNames.Count) do begin Name := FNames[I]; Value := FValues[I]; if (Pos(' ', Name) > 0) or (Pos(#9, Name) > 0) then begin Name := '"' + Name + '"'; end; Result := Result + ' ' + Name + '="' + Value + '"'; end; Result := Trim(Result); end; function TElAttributeList.GetValue(const Index: Integer): String; begin Result := FValues[Index]; end; procedure TElAttributeList.RemoveAttribute(const AName: String); var Index: Integer; begin Index := FNames.IndexOf(AName); if Index >= 0 then begin FNames.Delete(Index); FValues.Delete(Index); end; end; procedure TElAttributeList.SetAttribute(const AName, AValue: String; Additive: Boolean); var Index: Integer; O: String; V: String; begin Index := FNames.IndexOf(AName); if Index >= 0 then begin V := AValue; if Additive then begin if V = '' then Exit; O := FValues[Index]; if O <> '' then begin V := AValue + '; ' + O; end; end; FValues[Index] := V; end else begin FNames.Add(AName); FValues.Add(AValue); end; end; procedure TElAttributeList.SetText(const Text: String); const QuoteChars = ['''', '"']; var I: Integer; C: Char; InQuote: Boolean; QuoteChar: Char; Phrase: String; Name: String; NameParsed: Boolean; ValueParsed: Boolean; begin Clear; Phrase := ''; NameParsed := False; ValueParsed := False; InQuote := False; QuoteChar := #0; for I := 1 to Length(Text) do begin C := Text[I]; if InQuote then begin if C = QuoteChar then begin InQuote := False; Continue; end; end else begin if C in QuoteChars then begin QuoteChar := C; InQuote := True; Continue; end; end; if not InQuote then begin if (C = '=') and not NameParsed then begin Name := Trim(Phrase); Phrase := ''; NameParsed := True; ValueParsed := False; Continue; end; if (C in [' ', #9]) and ValueParsed then begin if Name <> '' then begin SetAttribute(Name, Trim(Phrase), True); end; Phrase := ''; NameParsed := False; ValueParsed := False; Continue; end; if NameParsed and not (C in [' ', #9]) then begin ValueParsed := True; end; end; Phrase := Phrase + C; end; if (not NameParsed) and (Phrase <> '') then begin Name := Trim(Phrase); NameParsed := True; Phrase := ''; end; if NameParsed then begin if Name <> '' then begin SetAttribute(Name, Trim(Phrase), True); end; end; end; procedure TElAttributeList.SetValue(const Index: Integer; const AValue: String); begin FValues[Index] := AValue; end; end.
unit Dm; interface uses SysUtils, Classes, DB, ADODB, Forms; type TData = class(TDataModule) Ado: TADOConnection; Costo: TADODataSet; DetCosto: TADODataSet; TDatos: TADOTable; TDatosIVA: TFloatField; TDatosRNI: TFloatField; TDatosDENOMINA: TWideStringField; TDatosDIRECCION: TWideStringField; TDatosCUIT: TWideStringField; TDatosCONDICIVA: TWideStringField; TDatosLOCALIDAD: TWideStringField; TDatosPROVINCIA: TWideStringField; TDatosIBRUTOS: TWideStringField; TDatosCONCILIA: TIntegerField; TDatosFECHA: TDateTimeField; TDetCosto: TADOTable; TDetCostoCLAVE: TIntegerField; TDetCostoITEM: TSmallintField; TDetCostoCODIGO: TWideStringField; TDetCostoCANTIDAD: TFloatField; TDetCostoIMPORTE: TFloatField; TDetCostoUSD: TBooleanField; Ultinum: TADOTable; UltinumULTIMO: TIntegerField; DetCostoCANTIDAD: TFloatField; DetCostoCLAVE: TIntegerField; DetCostoIMPORTE: TFloatField; DetCostoITEM: TSmallintField; DetCostoUSD: TBooleanField; DetCostoCAMBIOUSD: TFloatField; DetCostoCOS_MPRIMANOMBRE: TWideStringField; DetCostoCOS_CATEGORIANOMBRE: TWideStringField; ConsCos: TADODataSet; DetCostoSUBTOTAL: TCurrencyField; DetCostoMONEDA: TStringField; DetCostoCOS_DETCOSTOCODIGO: TWideStringField; DetCostoCOS_CATEGORIACODIGO: TWideStringField; TCosto: TADODataSet; DetCos: TADODataSet; DConsCos: TDataSource; DetCosCLAVE: TIntegerField; DetCosCANTIDAD: TFloatField; DetCosCODIGO: TWideStringField; DetCosIMPORTE: TFloatField; DetCosITEM: TSmallintField; DetCosUSD: TBooleanField; DetCosNOMBRE: TWideStringField; SelCosto: TADODataSet; ConsCostoActivo: TADODataSet; UpdActivo: TADOCommand; Categorias: TADODataSet; CategoriasCODIGO: TWideStringField; CategoriasNOMBRE: TWideStringField; MPrima: TADODataSet; Articulo: TADODataSet; ArticuloCODIGO: TWideStringField; ArticuloDENOMINA: TWideStringField; ArticuloCOSTO: TFloatField; ArticuloVENTA: TFloatField; ArticuloUNITARIO: TWideStringField; MPrimaNom: TADODataSet; WideStringField1: TWideStringField; WideStringField2: TWideStringField; WideStringField4: TWideStringField; WideStringField5: TWideStringField; FloatField1: TFloatField; UltinumIVA: TFloatField; IngMPrima: TADODataSet; IngMPrimaCATEGORIA: TWideStringField; IngMPrimaCODIGO: TWideStringField; IngMPrimaNOMBRE: TWideStringField; IngMPrimaPESDOL: TWideStringField; IngMPrimaPRECIO: TFloatField; CostoCLAVE: TIntegerField; CostoCODIGO: TWideStringField; CostoNOMBRE: TWideStringField; CostoFECHA: TDateTimeField; CostoCOSTO: TFloatField; CostoVENTA: TFloatField; CostoANTERIOR: TFloatField; CostoPESO: TFloatField; CostoLARGO: TFloatField; CostoRENTAOPTIMA: TFloatField; CostoOBSERVA: TMemoField; ConsCosANTERIOR: TFloatField; ConsCosCLAVE: TIntegerField; ConsCosCODIGO: TWideStringField; ConsCosCOSTO: TFloatField; ConsCosFECHA: TDateTimeField; ConsCosLARGO: TFloatField; ConsCosNOMBRE: TWideStringField; ConsCosOBSERVA: TMemoField; ConsCosPESO: TFloatField; ConsCosVENTA: TFloatField; ConsCosRENTAOPTIMA: TFloatField; TCostoCLAVE: TIntegerField; TCostoCODIGO: TWideStringField; TCostoNOMBRE: TWideStringField; TCostoFECHA: TDateTimeField; TCostoCOSTO: TFloatField; TCostoVENTA: TFloatField; TCostoANTERIOR: TFloatField; TCostoPESO: TFloatField; TCostoLARGO: TFloatField; TCostoRENTAOPTIMA: TFloatField; TCostoOBSERVA: TMemoField; CostoVENTA50: TFloatField; CostoVENTA25: TFloatField; SelCostoCLAVE: TIntegerField; SelCostoCODIGO: TWideStringField; SelCostoNOMBRE: TWideStringField; SelCostoFECHA: TDateTimeField; SelCostoCOSTO: TFloatField; SelCostoVENTA: TFloatField; SelCostoVENTA50: TFloatField; SelCostoVENTA25: TFloatField; SelCostoANTERIOR: TFloatField; SelCostoPESO: TFloatField; SelCostoLARGO: TFloatField; SelCostoRENTAOPTIMA: TFloatField; SelCostoOBSERVA: TMemoField; TCostoVENTA50: TFloatField; TCostoVENTA25: TFloatField; DetCosSUBTOTAL: TCurrencyField; CostoCAMBIOUSD: TFloatField; CostoACTIVO: TBooleanField; ConsCostoActivoANTERIOR: TFloatField; ConsCostoActivoCLAVE: TIntegerField; ConsCostoActivoCODIGO: TWideStringField; ConsCostoActivoCOSTO: TFloatField; ConsCostoActivoCAMBIOUSD: TFloatField; ConsCostoActivoFECHA: TDateTimeField; ConsCostoActivoNOMBRE: TWideStringField; ConsCostoActivoOBSERVA: TMemoField; ConsCostoActivoPESO: TFloatField; ConsCostoActivoVENTA: TFloatField; ConsCostoActivoVENTA25: TFloatField; ConsCostoActivoVENTA50: TFloatField; ConsCostoActivoRENTAOPTIMA: TFloatField; ConsCosCAMBIOUSD: TFloatField; ConsCosACTIVO: TBooleanField; SelCostoCAMBIOUSD: TFloatField; SelCostoACTIVO: TBooleanField; TCostoCAMBIOUSD: TFloatField; TCostoACTIVO: TBooleanField; ConsCosVENTA25: TFloatField; ConsCosVENTA50: TFloatField; CostoIVA: TFloatField; SelCostoIVA: TFloatField; TCostoIVA: TFloatField; ConsCosIVA: TFloatField; ConsCostoActivoIVA: TFloatField; ArticuloPESO: TFloatField; ArticuloACTIVO: TBooleanField; MPrimaCATEGORIA: TWideStringField; MPrimaCODIGO: TWideStringField; MPrimaNOMBRE: TWideStringField; MPrimaPESDOL: TWideStringField; MPrimaPRECIO: TFloatField; DetFormula: TADODataSet; DetForm: TADODataSet; DetFormulaCLAVE: TIntegerField; DetFormulaCODIGO: TWideStringField; DetFormulaIMPORTE: TFloatField; DetFormulaITEM: TSmallintField; DetFormCLAVE: TIntegerField; DetFormCODIGO: TWideStringField; DetFormIMPORTE: TFloatField; DetFormITEM: TSmallintField; DetFormNOMBRE: TWideStringField; DetFormFORMULA: TWideStringField; Formulas: TADODataSet; FormulasCODIGO: TWideStringField; FormulasFORMULA: TWideStringField; FormulasNOMBRE: TWideStringField; Formula: TADODataSet; FormulaCLAVE: TIntegerField; FormulaITEM: TSmallintField; FormulaCODIGO: TWideStringField; FormulaIMPORTE: TFloatField; TCostoTRAPO: TFloatField; TCostoDESPERDICIO: TFloatField; TCostoCOMISION: TFloatField; SelCostoTRAPO: TFloatField; SelCostoDESPERDICIO: TFloatField; SelCostoCOMISION: TFloatField; ConsCostoActivoTRAPO: TFloatField; ConsCostoActivoDESPERDICIO: TFloatField; ConsCostoActivoCOMISION: TFloatField; ConsCosTRAPO: TFloatField; ConsCosDESPERDICIO: TFloatField; ConsCosCOMISION: TFloatField; CostoTRAPO: TFloatField; CostoDESPERDICIO: TFloatField; CostoCOMISION: TFloatField; procedure DataModuleCreate(Sender: TObject); procedure DetCosCalcFields(DataSet: TDataSet); procedure MPrimaNewRecord(DataSet: TDataSet); procedure DetCostoCalcFields(DataSet: TDataSet); procedure IngMPrimaNewRecord(DataSet: TDataSet); private { Private declarations } Ruta: string; public { Public declarations } procedure AbrirArchivo( DataSet: TDataSet ); procedure CerrarArchivo( DataSet: TDataSet ); end; var Data: TData; implementation {$R *.dfm} procedure TData.DataModuleCreate(Sender: TObject); begin Ruta := ExtractFilePath( Application.ExeName ) + 'Conf\Costos.udl'; Ado.ConnectionString := 'FILE NAME=' + Ruta; Ado.Connected := true; end; procedure TData.DetCosCalcFields(DataSet: TDataSet); begin DetCosSUBTOTAL.Value := DetCosCANTIDAD.Value * DetCosIMPORTE.value; end; procedure TData.AbrirArchivo(DataSet: TDataSet); begin DataSet.Tag := DataSet.Tag + 1; DataSet.Open; end; procedure TData.CerrarArchivo(DataSet: TDataSet); begin DataSet.Tag := DataSet.Tag - 1; if DataSet.Tag <= 0 then DataSet.Close; end; procedure TData.MPrimaNewRecord(DataSet: TDataSet); begin MPrimaPESDOL.value := '0'; end; procedure TData.DetCostoCalcFields(DataSet: TDataSet); begin if ( DetCostoUSD.value = true ) then DetCostoSUBTOTAL.value := DetCostoIMPORTE.value * DetCostoCAMBIOUSD.value * DetCostoCANTIDAD.value else DetCostoSUBTOTAL.value := DetCostoIMPORTE.value * DetCostoCANTIDAD.value; if DetCostoUSD.value then DetCostoMONEDA.value := 'USD' else DetCostoMONEDA.value := ' $ '; end; procedure TData.IngMPrimaNewRecord(DataSet: TDataSet); begin IngMPrimaPESDOL.value := '0'; IngMPrimaPRECIO.value := 0; end; end.
unit Complex1D; interface type TComplexRec = record Re,Im: Real; end; ComplexTernary1D=class private // Re_data,Im_data: array of Real; fdata: array of TComplexRec; fq,fqmin1: Integer; //число тритов fT,fN: Integer; //полное число элементов и мин/макс значение (-N, N) base: Integer; //смещение нулевого отсчета increments: array of Integer; //для алгоритма Лены - посчитаем заранее function Re_value(i: Integer): Real; function Im_value(i: Integer): Real; procedure set_Re(i: Integer; value: Real); procedure set_Im(i: Integer; value: Real); public procedure Set_BitCount(aQ: Integer); procedure Set_Length(aT: Integer); procedure inversion; procedure inversion_by_Elena; procedure inversion_combined; property Re[i: integer]: Real read Re_value write set_Re; property Im[i: integer]: Real read Im_value write set_Im; property N: Integer read fN; property T: Integer read fT; // procedure generalFFT(inverse: boolean); procedure FFT; procedure inverseFFT; constructor Create; end; function VarReal(X: Real): Variant; implementation uses math,streaming_class_lib; (* General *) function VarReal(X: Real): Variant; begin Result:=X; end; //очень тупая функция, но без нее громоздко выходит (* ComplexTernary1D *) constructor ComplexTernary1D.Create; begin inherited Create; Set_Length(0); end; procedure ComplexTernary1D.Set_BitCount(aQ: Integer); var i,plus,minus: Integer; begin if aQ<0 then begin fQ:=-1; fqmin1:=-2; fT:=0; fN:=-1; SetLength(fdata,0); end else begin fq:=aQ; fqmin1:=fq-1; fT:=Round(power(3,fq)); fN:=(fT-1) div 2; SetLength(fdata,fT); base:=fN; SetLength(increments,fq); if fq>0 then begin increments[0]:=fT div 3; plus:=fT div 9; minus:=fT; for i:=1 to fq-1 do begin increments[i]:=increments[i-1]+plus-minus; plus:=plus div 3; minus:=minus div 3; end; end; end; end; procedure ComplexTernary1D.Set_Length(aT: Integer); begin assert(aT>-1,'Set_Length: negative argument'); if aT<1 then Set_BitCount(-1) else begin fq:=math.Ceil(ln(aT)/ln(3)); Set_BitCount(fq); end; end; function ComplexTernary1D.Re_value(i: Integer): Real; begin assert((i<=fN) and (i>=-fN),'Re_value index out of range'); Result:=fdata[base+i].Re; end; function ComplexTernary1D.Im_value(i: Integer): Real; begin assert((i<=fN) and (i>=-fN),'Im_value index out of range'); Result:=fdata[base+i].Im; end; procedure ComplexTernary1D.set_Re(i: Integer; value: Real); begin assert((i<=fN) and (i>=-fN),'set_Re index out of range'); fdata[base+i].Re:=value; end; procedure ComplexTernary1D.set_Im(i: Integer; value: Real); begin assert((i<=fN) and (i>=-fN),'set_Im index out of range'); fdata[base+i].Im:=value; end; procedure ComplexTernary1D.inversion; var i,k,j,ma,ik,lim: Integer; begin i:=0; ma:=fN-2; ik:=fT div 3; for j:=1 to ma do begin k:=ik; i:=i+k; lim:=fN; while i>lim do begin i:=i-3*k; lim:=lim-2*k; k:=k div 3; i:=i+k; end; if (j<i) then begin SwapFloats(fdata[base+i].re,fdata[base+j].re); SwapFloats(fdata[base+i].im,fdata[base+j].im); SwapFloats(fdata[base-i].re,fdata[base-j].re); SwapFloats(fdata[base-i].im,fdata[base-j].im); end else if (i<0) then begin SwapFloats(fdata[base+i].re,fdata[base+j].re); SwapFloats(fdata[base+i].im,fdata[base+j].im); end; end; end; procedure ComplexTernary1D.inversion_by_Elena; var i,j,a,b,k: Integer; begin //_q, _qmin1 уже определены a:=fT div 3; b:=1; i:=2; j:=-N; //начали от печки k:=-N; while i<=fT do begin while a>0 do begin if (i-1) mod a = 0 then begin j:=j+b; if a<>1 then j:=j-9*b; end; a:=a div 3; b:=b*3; end; inc(i); inc(k); a:=fT div 3; b:=1; if k<j then begin SwapFloats(fdata[base+k].Re,fdata[base+j].Re); SwapFloats(fdata[base+k].Im,fdata[base+j].Im); end; end; end; procedure ComplexTernary1D.inversion_combined; var i,j,ik,a,b,ma,Tmin1: Integer; // t: TComplexRec; t: Real; begin ma:=2*fN-2; ik:=fT div 3; i:=fN+ik; j:=fN+1; Tmin1:=fT-1; while j<=ma do begin //знаем, что здесь i>0 if (j<i) then begin t:=fdata[i].Re; fdata[i].Re:=fdata[j].Re; fdata[j].Re:=t; t:=fdata[i].Im; fdata[i].Im:=fdata[j].Im; fdata[j].Im:=t; t:=fdata[Tmin1-i].Re; fdata[Tmin1-i].Re:=fdata[Tmin1-j].Re; fdata[Tmin1-j].Re:=t; t:=fdata[Tmin1-i].Im; fdata[Tmin1-i].Im:=fdata[Tmin1-j].Im; fdata[Tmin1-j].Im:=t; end; //здесь наступает перенос, нужно узнать, на сколько разрядов inc(j); a:=9; b:=1; while j mod a=0 do begin inc(b); a:=a*3; end; inc(i,increments[b]); //i заведомо отрицательное, т.е. меньше fN t:=fdata[i].Re; fdata[i].Re:=fdata[j].Re; fdata[j].Re:=t; t:=fdata[i].Im; fdata[i].Im:=fdata[j].Im; fdata[j].Im:=t; //наконец, с -1 до 0 без переноса //можем прийти к отрицательному ответу! inc(i,ik); inc(j); if (j<i) then begin t:=fdata[i].Re; fdata[i].Re:=fdata[j].Re; fdata[j].Re:=t; t:=fdata[i].Im; fdata[i].Im:=fdata[j].Im; fdata[j].Im:=t; t:=fdata[Tmin1-i].Re; fdata[Tmin1-i].Re:=fdata[Tmin1-j].Re; fdata[Tmin1-j].Re:=t; t:=fdata[Tmin1-i].Im; fdata[Tmin1-i].Im:=fdata[Tmin1-j].Im; fdata[Tmin1-j].Im:=t; end else if i<fN then begin t:=fdata[i].Re; fdata[i].Re:=fdata[j].Re; fdata[j].Re:=t; t:=fdata[i].Im; fdata[i].Im:=fdata[j].Im; fdata[j].Im:=t; end; //готовимся к следующей итерации - с 0 до 1 без переноса inc(i,ik); inc(j); end; end; procedure ComplexTernary1D.FFT; var N1,M1,T1,k,j,incr,big_incr,i: Integer; sqrt3,Wr,Wi,Ph,incWr,incWi,TwoPi,tmpWr: Real; //W - фазовый множитель, r,i - действ. и мнимое знач. xsum,ysum,xdif,ydif,ax,ay,xp1,xm1,yp1,ym1,x0,y0: Real; //sum - суммы //dif - разности //p1,0,m1 - +1,0,-1 соотв begin sqrt3:=-sqrt(3)/2; TwoPi:=2*pi; inversion; T1:=fT; N1:=fN; incr:=1; while N1>0 do begin T1:=T1 div 3; N1:=(T1-1) div 2; big_incr:=incr*3; //для внутреннего цикла M1:=(incr-1) div 2; //для внешнего //отдельно обработаем i=0, там фазовый множ. не нужен for k:=-N1 to N1 do begin j:=base+big_incr*k; //отдельно обраб. нулевое значение - там не нужно фаз. множителей x0:=fdata[j].Re; y0:=fdata[j].Im; j:=j+incr; xp1:=fdata[j].re; yp1:=fdata[j].Im; j:=j-2*incr; xm1:=fdata[j].re; ym1:=fdata[j].im; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент fdata[j].Re:=Ax-xdif; fdata[j].Im:=Ay-ydif; j:=j+2*incr; //+1-й элемент fdata[j].re:=Ax+xdif; fdata[j].Im:=Ay+ydif; j:=j-incr; //0-й элемент fdata[j].Re:=x0+xsum; fdata[j].Im:=y0+ysum; //итого, 12 сложений и 4 умножения end; //шаг фазового множителя: 2pi/incr; //на первой итерации просто 2pi, но там цикл и не запустится //на второй итер: Ph:=TwoPi/big_incr; incWr:=cos(Ph); incWi:=-sin(Ph); Wr:=1; Wi:=0; for i:=1 to M1 do begin //пересчитываем фазовый множитель, потом делаем циклы для i и -i tmpWr:=Wr; Wr:=tmpWr*incWr-Wi*incWi; Wi:=Wi*incWr+tmpWr*incWi; for k:=-N1 to N1 do begin //итерация для +i j:=base+i+big_incr*k; //x0,y0 - без изменений x0:=fdata[j].re; y0:=fdata[j].im; j:=j+incr; //а здесь надо умножить на фаз. множ. //элем. +1 - на W tmpWr:=fdata[j].re; yp1:=fdata[j].im; xp1:=tmpWr*Wr-yp1*Wi; yp1:=yp1*Wr+tmpWr*Wi; j:=j-2*incr; //элем. -1 умножаем на W* (сопряж) tmpWr:=fdata[j].Re; ym1:=fdata[j].Im; xm1:=tmpWr*Wr+ym1*Wi; ym1:=ym1*Wr-tmpWr*Wi; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент fdata[j].Re:=Ax-xdif; fdata[j].Im:=Ay-ydif; j:=j+2*incr; //+1-й элемент fdata[j].re:=Ax+xdif; fdata[j].Im:=Ay+ydif; j:=j-incr; //0-й элемент fdata[j].Re:=x0+xsum; fdata[j].Im:=y0+ysum; //Теперь, то же самое для элемента -i j:=base-i+big_incr*k; //x0,y0 - без изменений x0:=fdata[j].Re; y0:=fdata[j].Im; j:=j+incr; //а здесь надо умножить на фаз. множ. //элем. +1 - на W* (т.к -i) tmpWr:=fdata[j].re; yp1:=fdata[j].Im; xp1:=tmpWr*Wr+yp1*Wi; yp1:=yp1*Wr-tmpWr*Wi; j:=j-2*incr; //элем. -1 умножаем на W tmpWr:=fdata[j].Re; ym1:=fdata[j].Im; xm1:=tmpWr*Wr-ym1*Wi; ym1:=ym1*Wr+tmpWr*Wi; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент fdata[j].Re:=Ax-xdif; fdata[j].im:=Ay-ydif; j:=j+2*incr; //+1-й элемент fdata[j].Re:=Ax+xdif; fdata[j].Im:=Ay+ydif; j:=j-incr; //0-й элемент fdata[j].Re:=x0+xsum; fdata[j].Im:=y0+ysum; end; end; //конец одного слоя incr:=big_incr; end; end; procedure ComplexTernary1D.inverseFFT; var N1,M1,T1,k,j,incr,big_incr,i: Integer; sqrt3,Wr,Wi,Ph,incWr,incWi,TwoPi,tmpWr: Real; //W - фазовый множитель, r,i - действ. и мнимое знач. xsum,ysum,xdif,ydif,ax,ay,xp1,xm1,yp1,ym1,x0,y0: Real; //sum - суммы //dif - разности //p1,0,m1 - +1,0,-1 соотв begin sqrt3:=sqrt(3)/2; TwoPi:=2*pi; inversion; T1:=fT; N1:=fN; incr:=1; while N1>0 do begin T1:=T1 div 3; N1:=(T1-1) div 2; big_incr:=incr*3; //для внутреннего цикла M1:=(incr-1) div 2; //для внешнего //отдельно обработаем i=0, там фазовый множ. не нужен for k:=-N1 to N1 do begin j:=base+big_incr*k; //отдельно обраб. нулевое значение - там не нужно фаз. множителей x0:=fdata[j].Re; y0:=fdata[j].Im; j:=j+incr; xp1:=fdata[j].Re; yp1:=fdata[j].Im; j:=j-2*incr; xm1:=fdata[j].Re; ym1:=fdata[j].Im; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент fdata[j].Re:=Ax-xdif; fdata[j].Im:=Ay-ydif; j:=j+2*incr; //+1-й элемент fdata[j].Re:=Ax+xdif; fdata[j].Im:=Ay+ydif; j:=j-incr; //0-й элемент fdata[j].Re:=x0+xsum; fdata[j].Im:=y0+ysum; //итого, 12 сложений и 4 умножения end; //шаг фазового множителя: 2pi/incr; //на первой итерации просто 2pi, но там цикл и не запустится //на второй итер: Ph:=TwoPi/big_incr; incWr:=cos(Ph); incWi:=sin(Ph); Wr:=1; Wi:=0; for i:=1 to M1 do begin //пересчитываем фазовый множитель, потом делаем циклы для i и -i tmpWr:=Wr; Wr:=tmpWr*incWr-Wi*incWi; Wi:=Wi*incWr+tmpWr*incWi; for k:=-N1 to N1 do begin //итерация для +i j:=base+i+big_incr*k; //x0,y0 - без изменений x0:=fdata[j].Re; y0:=fdata[j].Im; j:=j+incr; //а здесь надо умножить на фаз. множ. //элем. +1 - на W tmpWr:=fdata[j].Re; yp1:=fdata[j].Im; xp1:=tmpWr*Wr-yp1*Wi; yp1:=yp1*Wr+tmpWr*Wi; j:=j-2*incr; //элем. -1 умножаем на W* (сопряж) tmpWr:=fdata[j].Re; ym1:=fdata[j].Im; xm1:=tmpWr*Wr+ym1*Wi; ym1:=ym1*Wr-tmpWr*Wi; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент fdata[j].re:=Ax-xdif; fdata[j].Im:=Ay-ydif; j:=j+2*incr; //+1-й элемент fdata[j].Re:=Ax+xdif; fdata[j].Im:=Ay+ydif; j:=j-incr; //0-й элемент fdata[j].re:=x0+xsum; fdata[j].Im:=y0+ysum; //Теперь, то же самое для элемента -i j:=base-i+big_incr*k; //x0,y0 - без изменений x0:=fdata[j].re; y0:=fdata[j].im; j:=j+incr; //а здесь надо умножить на фаз. множ. //элем. +1 - на W* (т.к -i) tmpWr:=fdata[j].Re; yp1:=fdata[j].Im; xp1:=tmpWr*Wr+yp1*Wi; yp1:=yp1*Wr-tmpWr*Wi; j:=j-2*incr; //элем. -1 умножаем на W tmpWr:=fdata[j].Re; ym1:=fdata[j].Im; xm1:=tmpWr*Wr-ym1*Wi; ym1:=ym1*Wr+tmpWr*Wi; xsum:=xp1+xm1; ysum:=yp1+ym1; ydif:=sqrt3*(xp1-xm1); xdif:=sqrt3*(ym1-yp1); // 4 сложения и 2 умножения (с плав. точкой) Ax:=x0-0.5*xsum; Ay:=y0-0.5*ysum; // 6 сложений и 4 умножения //сейчас j указывает на -1-й элемент fdata[j].Re:=Ax-xdif; fdata[j].Im:=Ay-ydif; j:=j+2*incr; //+1-й элемент fdata[j].Re:=Ax+xdif; fdata[j].Im:=Ay+ydif; j:=j-incr; //0-й элемент fdata[j].Re:=x0+xsum; fdata[j].Im:=y0+ysum; end; end; //конец одного слоя incr:=big_incr; end; end; end.
unit Unit2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TformColor = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var formColor: TformColor; implementation {$R *.dfm} procedure TformColor.Button1Click(Sender: TObject); begin formColor.Color := clYellow; end; procedure TformColor.Button2Click(Sender: TObject); begin formColor.Color := clBlue; end; procedure TformColor.FormCreate(Sender: TObject); begin formColor.Color := clRed; end; end.
unit NtUtils.Sam; interface uses Winapi.WinNt, Ntapi.ntdef, Ntapi.ntsam, NtUtils.Exceptions, NtUtils.Security.Sid; type TRidAndName = record Name: String; RelativeId: Cardinal; end; TGroupMembership = Ntapi.ntsam.TGroupMembership; // Connect to the local SAM server function SamxConnect(out hServer: TSamHandle; DesiredAccess: TAccessMask): TNtxStatus; // Connect to a remote SAM server function SamxConnectRemote(out hServer: TSamHandle; ServerName: String; DesiredAccess: TAccessMask): TNtxStatus; // Close SAM handle function SamxClose(var SamHandle: TSamHandle): NTSTATUS; // Free a buffer returned by a SamxQuery* function function SamxFreeMemory(Buffer: Pointer): NTSTATUS; { --------------------------------- Domains -------------------------------- } // Open a domain function SamxOpenDomain(out hDomain: TSamHandle; DomainId: PSid; DesiredAccess: TAccessMask): TNtxStatus; overload; function SamxOpenDomain(out hDomain: TSamHandle; hServer: TSamHandle; DomainId: PSid; DesiredAccess: TAccessMask): TNtxStatus; overload; // Open the parent of the SID as a domain function SamxOpenParentDomain(out hDomain: TSamHandle; SID: ISid; DesiredAccess: TAccessMask): TNtxStatus; // Lookup a domain function SamxLookupDomain(hServer: TSamHandle; Name: String; out DomainId: ISid): TNtxStatus; // Enumerate domains function SamxEnumerateDomains(hServer: TSamHandle; out Names: TArray<String>): TNtxStatus; // Query domain information; free the result with SamxFreeMemory function SamxQueryDomain(hDomain: TSamHandle; InfoClass: TDomainInformationClass; out Status: TNtxStatus): Pointer; // Set domain information function SamxSetDomain(hDomain: TSamHandle; InfoClass: TDomainInformationClass; Data: Pointer): TNtxStatus; { --------------------------------- Groups ---------------------------------- } // Enumerate groups function SamxEnumerateGroups(hDomain: TSamHandle; out Groups: TArray<TRidAndName>): TNtxStatus; // Open a group function SamxOpenGroup(out hGroup: TSamHandle; hDomain: TSamHandle; GroupId: Cardinal; DesiredAccess: TAccessMask): TNtxStatus; // Open a group by SID function SamxOpenGroupBySid(out hGroup: TSamHandle; Sid: ISid; DesiredAccess: TAccessMask): TNtxStatus; // Get groups members function SamxGetMembersGroup(hGroup: TSamHandle; out Members: TArray<TGroupMembership>): TNtxStatus; // Query group information; free the result with SamxFreeMemory function SamxQueryGroup(hGroup: TSamHandle; InfoClass: TGroupInformationClass; out Status: TNtxStatus): Pointer; // Set group information function SamxSetGroup(hGroup: TSamHandle; InfoClass: TGroupInformationClass; Data: Pointer): TNtxStatus; { --------------------------------- Aliases --------------------------------- } // Enumerate aliases in domain function SamxEnumerateAliases(hDomain: TSamHandle; out Aliases: TArray<TRidAndName>): TNtxStatus; // Open an alias function SamxOpenAlias(out hAlias: TSamHandle; hDomain: TSamHandle; AliasId: Cardinal; DesiredAccess: TAccessMask): TNtxStatus; // Open an alias by SID function SamxOpenAliasBySid(out hAlias: TSamHandle; Sid: ISid; DesiredAccess: TAccessMask): TNtxStatus; // Get alias members function SamxGetMembersAlias(hAlias: TSamHandle; out Members: Tarray<ISid>): TNtxStatus; // Query alias information; free the result with SamxFreeMemory function SamxQueryAlias(hAlias: TSamHandle; InfoClass: TAliasInformationClass; out Status: TNtxStatus): Pointer; // Set alias information function SamxSetAlias(hAlias: TSamHandle; InfoClass: TAliasInformationClass; Data: Pointer): TNtxStatus; { ---------------------------------- Users ---------------------------------- } // Enumerate users in domain function SamxEnumerateUsers(hDomain: TSamHandle; UserType: Cardinal; out Users: TArray<TRidAndName>): TNtxStatus; // Open a user function SamxOpenUser(out hUser: TSamHandle; hDomain: TSamHandle; UserId: Cardinal; DesiredAccess: TAccessMask): TNtxStatus; // Open a user by SID function SamxOpenUserBySid(out hUser: TSamHandle; Sid: ISid; DesiredAccess: TAccessMask): TNtxStatus; // Get groups for a user function SamxGetGroupsForUser(hUser: TSamHandle; out Groups: TArray<TGroupMembership>): TNtxStatus; // Query user information; free the result with SamxFreeMemory function SamxQueryUser(hUser: TSamHandle; InfoClass: TUserInformationClass; out Status: TNtxStatus): Pointer; // Set user information function SamxSetUser(hUser: TSamHandle; InfoClass: TUserInformationClass; Data: Pointer): TNtxStatus; implementation uses Ntapi.ntstatus, NtUtils.Access.Expected; { Server } function SamxConnect(out hServer: TSamHandle; DesiredAccess: TAccessMask): TNtxStatus; var ObjAttr: TObjectAttributes; begin InitializeObjectAttributes(ObjAttr); Result.Location := 'SamConnect'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @SamAccessType; Result.Status := SamConnect(nil, hServer, DesiredAccess, ObjAttr); end; function SamxConnectRemote(out hServer: TSamHandle; ServerName: String; DesiredAccess: TAccessMask): TNtxStatus; var ObjAttr: TObjectAttributes; NameStr: UNICODE_STRING; begin InitializeObjectAttributes(ObjAttr); NameStr.FromString(ServerName); Result.Location := 'SamConnect'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @SamAccessType; Result.Status := SamConnect(@NameStr, hServer, DesiredAccess, ObjAttr); end; function SamxClose(var SamHandle: TSamHandle): NTSTATUS; begin Result := SamCloseHandle(SamHandle); SamHandle := 0; end; function SamxFreeMemory(Buffer: Pointer): NTSTATUS; begin Result := SamFreeMemory(Buffer); end; { Domains } function SamxOpenDomain(out hDomain: TSamHandle; hServer: TSamHandle; DomainId: PSid; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'SamOpenDomain'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @DomainAccessType; Result.LastCall.Expects(SAM_SERVER_LOOKUP_DOMAIN, @SamAccessType); Result.Status := SamOpenDomain(hServer, DesiredAccess, DomainId, hDomain); end; function SamxOpenDomain(out hDomain: TSamHandle; DomainId: PSid; DesiredAccess: TAccessMask): TNtxStatus; var hServer: TSamHandle; begin Result := SamxConnect(hServer, SAM_SERVER_LOOKUP_DOMAIN); if not Result.IsSuccess then Exit; Result := SamxOpenDomain(hDomain, hServer, DomainId, DesiredAccess); SamxClose(hServer); end; function SamxOpenParentDomain(out hDomain: TSamHandle; SID: ISid; DesiredAccess: TAccessMask): TNtxStatus; begin if Sid.SubAuthorities = 0 then begin Result.Location := 'ISid.ParentSid'; Result.Status := STATUS_INVALID_SID; Exit; end; Result := SamxOpenDomain(hDomain, Sid.ParentSid.Sid, DOMAIN_LOOKUP); end; function SamxLookupDomain(hServer: TSamHandle; Name: String; out DomainId: ISid): TNtxStatus; var NameStr: UNICODE_STRING; Buffer: PSid; begin NameStr.FromString(Name); Result.Location := 'SamLookupDomainInSamServer'; Result.LastCall.Expects(SAM_SERVER_LOOKUP_DOMAIN, @SamAccessType); Result.Status := SamLookupDomainInSamServer(hServer, NameStr, Buffer); if not Result.IsSuccess then Exit; DomainId := TSid.CreateCopy(Buffer); SamFreeMemory(Buffer); end; function SamxEnumerateDomains(hServer: TSamHandle; out Names: TArray<String>): TNtxStatus; var EnumContext: TSamEnumerationHandle; Buffer: PSamRidEnumerationArray; Count, i: Integer; begin EnumContext := 0; Result.Location := 'SamEnumerateDomainsInSamServer'; Result.LastCall.Expects(SAM_SERVER_ENUMERATE_DOMAINS, @SamAccessType); Result.Status := SamEnumerateDomainsInSamServer(hServer, EnumContext, Buffer, MAX_PREFERRED_LENGTH, Count); if not Result.IsSuccess then Exit; SetLength(Names, Count); // RelativeId is always zero for domains, but names are available for i := 0 to High(Names) do Names[i] := Buffer{$R-}[i]{$R+}.Name.ToString; SamFreeMemory(Buffer); end; function SamxQueryDomain(hDomain: TSamHandle; InfoClass: TDomainInformationClass; out Status: TNtxStatus): Pointer; begin Status.Location := 'SamQueryInformationDomain'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TDomainInformationClass); RtlxComputeDomainQueryAccess(Status.LastCall, InfoClass); Status.Status := SamQueryInformationDomain(hDomain, InfoClass, Result); end; function SamxSetDomain(hDomain: TSamHandle; InfoClass: TDomainInformationClass; Data: Pointer): TNtxStatus; begin Result.Location := 'SamSetInformationDomain'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TDomainInformationClass); RtlxComputeDomainSetAccess(Result.LastCall, InfoClass); Result.Status := SamSetInformationDomain(hDomain, InfoClass, Data); end; { Groups } function SamxEnumerateGroups(hDomain: TSamHandle; out Groups: TArray<TRidAndName>): TNtxStatus; var EnumContext: TSamEnumerationHandle; Buffer: PSamRidEnumerationArray; Count, i: Integer; begin EnumContext := 0; Result.Location := 'SamEnumerateGroupsInDomain'; Result.LastCall.Expects(DOMAIN_LIST_ACCOUNTS, @DomainAccessType); Result.Status := SamEnumerateGroupsInDomain(hDomain, EnumContext, Buffer, MAX_PREFERRED_LENGTH, Count); if not Result.IsSuccess then Exit; SetLength(Groups, Count); for i := 0 to High(Groups) do begin Groups[i].RelativeId := Buffer{$R-}[i]{$R+}.RelativeId; Groups[i].Name := Buffer{$R-}[i]{$R+}.Name.ToString; end; SamFreeMemory(Buffer); end; function SamxOpenGroup(out hGroup: TSamHandle; hDomain: TSamHandle; GroupId: Cardinal; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'SamOpenGroup'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @GroupAccessType; Result.LastCall.Expects(DOMAIN_LOOKUP, @DomainAccessType); Result.Status := SamOpenGroup(hDomain, DesiredAccess, GroupId, hGroup); end; function SamxOpenGroupBySid(out hGroup: TSamHandle; Sid: ISid; DesiredAccess: TAccessMask): TNtxStatus; var hDomain: TSamHandle; begin Result := SamxOpenParentDomain(hDomain, Sid, DOMAIN_LOOKUP); if not Result.IsSuccess then Exit; Result := SamxOpenGroup(hGroup, hDomain, Sid.Rid, DesiredAccess); SamxClose(hDomain); end; function SamxGetMembersGroup(hGroup: TSamHandle; out Members: TArray<TGroupMembership>): TNtxStatus; var BufferIDs, BufferAttributes: PCardinalArray; Count, i: Integer; begin Result.Location := 'SamGetMembersInGroup'; Result.LastCall.Expects(GROUP_LIST_MEMBERS, @GroupAccessType); Result.Status := SamGetMembersInGroup(hGroup, BufferIDs, BufferAttributes, Count); if not Result.IsSuccess then Exit; SetLength(Members, Count); for i := 0 to High(Members) do begin Members[i].RelativeId := BufferIDs{$R-}[i]{$R+}; Members[i].Attributes := BufferAttributes{$R-}[i]{$R+}; end; SamFreeMemory(BufferIDs); SamFreeMemory(BufferAttributes); end; function SamxQueryGroup(hGroup: TSamHandle; InfoClass: TGroupInformationClass; out Status: TNtxStatus): Pointer; begin Status.Location := 'SamQueryInformationGroup'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TGroupInformationClass); Status.LastCall.Expects(GROUP_READ_INFORMATION, @GroupAccessType); Status.Status := SamQueryInformationGroup(hGroup, InfoClass, Result); end; function SamxSetGroup(hGroup: TSamHandle; InfoClass: TGroupInformationClass; Data: Pointer): TNtxStatus; begin Result.Location := 'SamSetInformationGroup'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TGroupInformationClass); Result.LastCall.Expects(GROUP_WRITE_ACCOUNT, @GroupAccessType); Result.Status := SamSetInformationGroup(hGroup, InfoClass, Data); end; { Aliases } function SamxEnumerateAliases(hDomain: TSamHandle; out Aliases: TArray<TRidAndName>): TNtxStatus; var EnumContext: TSamEnumerationHandle; Buffer: PSamRidEnumerationArray; Count, i: Integer; begin EnumContext := 0; Result.Location := 'SamEnumerateAliasesInDomain'; Result.LastCall.Expects(DOMAIN_LIST_ACCOUNTS, @DomainAccessType); Result.Status := SamEnumerateAliasesInDomain(hDomain, EnumContext, Buffer, MAX_PREFERRED_LENGTH, Count); if not Result.IsSuccess then Exit; SetLength(Aliases, Count); for i := 0 to High(Aliases) do begin Aliases[i].RelativeId := Buffer{$R-}[i]{$R+}.RelativeId; Aliases[i].Name := Buffer{$R-}[i]{$R+}.Name.ToString; end; SamFreeMemory(Buffer); end; function SamxOpenAlias(out hAlias: TSamHandle; hDomain: TSamHandle; AliasId: Cardinal; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'SamOpenAlias'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @AliasAccessType; Result.LastCall.Expects(DOMAIN_LOOKUP, @DomainAccessType); Result.Status := SamOpenAlias(hDomain, DesiredAccess, AliasId, hAlias); end; function SamxOpenAliasBySid(out hAlias: TSamHandle; Sid: ISid; DesiredAccess: TAccessMask): TNtxStatus; var hDomain: TSamHandle; begin Result := SamxOpenParentDomain(hDomain, Sid, DOMAIN_LOOKUP); if not Result.IsSuccess then Exit; Result := SamxOpenAlias(hAlias, hDomain, Sid.Rid, DesiredAccess); SamxClose(hDomain); end; function SamxGetMembersAlias(hAlias: TSamHandle; out Members: Tarray<ISid>): TNtxStatus; var Buffer: PSidArray; Count, i: Integer; begin Result.Location := 'SamGetMembersInAlias'; Result.LastCall.Expects(ALIAS_LIST_MEMBERS, @AliasAccessType); Result.Status := SamGetMembersInAlias(hAlias, Buffer, Count); if not Result.IsSuccess then Exit; SetLength(Members, Count); for i := 0 to High(Members) do Members[i] := TSid.CreateCopy(Buffer{$R-}[i]{$R+}); SamFreeMemory(Buffer); end; function SamxQueryAlias(hAlias: TSamHandle; InfoClass: TAliasInformationClass; out Status: TNtxStatus): Pointer; begin Status.Location := 'SamQueryInformationAlias'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TAliasInformationClass); Status.LastCall.Expects(ALIAS_READ_INFORMATION, @AliasAccessType); Status.Status := SamQueryInformationAlias(hAlias, InfoClass, Result); end; function SamxSetAlias(hAlias: TSamHandle; InfoClass: TAliasInformationClass; Data: Pointer): TNtxStatus; begin Result.Location := 'SamSetInformationAlias'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TAliasInformationClass); Result.LastCall.Expects(ALIAS_WRITE_ACCOUNT, @AliasAccessType); Result.Status := SamSetInformationAlias(hAlias, InfoClass, Data); end; { Users } function SamxEnumerateUsers(hDomain: TSamHandle; UserType: Cardinal; out Users: TArray<TRidAndName>): TNtxStatus; var EnumContext: TSamEnumerationHandle; Buffer: PSamRidEnumerationArray; Count, i: Integer; begin EnumContext := 0; Result.Location := 'SamEnumerateUsersInDomain'; Result.LastCall.Expects(DOMAIN_LIST_ACCOUNTS, @DomainAccessType); Result.Status := SamEnumerateUsersInDomain(hDomain, EnumContext, UserType, Buffer, MAX_PREFERRED_LENGTH, Count); if not Result.IsSuccess then Exit; SetLength(Users, Count); for i := 0 to High(Users) do begin Users[i].RelativeId := Buffer{$R-}[i]{$R+}.RelativeId; Users[i].Name := Buffer{$R-}[i]{$R+}.Name.ToString; end; SamFreeMemory(Buffer); end; function SamxOpenUser(out hUser: TSamHandle; hDomain: TSamHandle; UserId: Cardinal; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'SamOpenUser'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @UserAccessType; Result.LastCall.Expects(DOMAIN_LOOKUP, @DomainAccessType); Result.Status := SamOpenUser(hDomain, DesiredAccess, UserId, hUser); end; // Open a user by SID function SamxOpenUserBySid(out hUser: TSamHandle; Sid: ISid; DesiredAccess: TAccessMask): TNtxStatus; var hDomain: TSamHandle; begin Result := SamxOpenParentDomain(hDomain, Sid, DOMAIN_LOOKUP); if not Result.IsSuccess then Exit; Result := SamxOpenUser(hUser, hDomain, Sid.Rid, DesiredAccess); SamxClose(hDomain); end; function SamxGetGroupsForUser(hUser: TSamHandle; out Groups: TArray<TGroupMembership>): TNtxStatus; var Buffer: PGroupMembershipArray; Count, i: Integer; begin Result.Location := 'SamGetGroupsForUser'; Result.LastCall.Expects(USER_LIST_GROUPS, @UserAccessType); Result.Status := SamGetGroupsForUser(hUser, Buffer, Count); if not Result.IsSuccess then Exit; SetLength(Groups, Count); for i := 0 to High(Groups) do Groups[i] := Buffer{$R-}[i]{$R+}^; SamFreeMemory(Buffer); end; function SamxQueryUser(hUser: TSamHandle; InfoClass: TUserInformationClass; out Status: TNtxStatus): Pointer; begin Status.Location := 'SamQueryInformationUser'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TUserInformationClass); RtlxComputeUserQueryAccess(Status.LastCall, InfoClass); Status.Status := SamQueryInformationUser(hUser, InfoClass, Result); end; // Set user information function SamxSetUser(hUser: TSamHandle; InfoClass: TUserInformationClass; Data: Pointer): TNtxStatus; begin Result.Location := 'SamSetInformationUser'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TUserInformationClass); RtlxComputeUserSetAccess(Result.LastCall, InfoClass); Result.Status := SamSetInformationUser(hUser, InfoClass, Data); end; end.
unit Types; interface uses Classes,Forms,ComCtrls,IniFiles; type TClassOptions = class of TOptions; TOptions = class(TObject) protected FIni:TIniFile; FSection:String; public procedure AssignNode(Node:TTreeNode);virtual; abstract; procedure LoadFromIniSection(Ini:TIniFile; const Section:String);virtual; procedure WriteToIniSection;virtual;abstract; function CreateOptionsFrame(AOwner:TComponent):TFrame;virtual;abstract; function AllowNodeEditing:Boolean;virtual; procedure AfterNodeEditing(var S:String);virtual; public property Ini:TIniFile read FIni; property Section:String read FSection; end; TOptionsList = class(TOptions) public function AllowNodeEditing:Boolean;override; end; { procedure AssignNode(Node:TTreeNode);override; procedure LoadFromIniSection(Ini:TIniFile; const Section:String);override; procedure WriteToIniSection;override; function CreateOptionsFrame(AOwner:TComponent):TFrame;override; } implementation { TOptions } procedure TOptions.AfterNodeEditing(var S: String); begin try Ini.EraseSection(Section); except end; FSection:=S; end; function TOptions.AllowNodeEditing: Boolean; begin Result:=True; end; procedure TOptions.LoadFromIniSection(Ini: TIniFile; const Section: String); begin FIni:=Ini; FSection:=Section; end; { TOptionsList } function TOptionsList.AllowNodeEditing: Boolean; begin Result:=False; end; end.
unit Plugin.MenuItem; interface uses System.classes, WinApi.Windows, System.SysUtils, {$ifdef FMX} FMX.Forms, FMX.Controls,{$else} VCL.Forms, VCL.Controls,{$endif} Plugin.Service, Plugin.Forms, Plugin.Interf; type TPluginMenuItemBase = class(TPluginExecuteService, IPluginMenuItem) public function GetResourceName: String; virtual; function GetCaption: string; virtual; function GetPath: string; virtual; procedure DoClick(const AParent: THandle); virtual; end; TPluginMenuItemService = class(TPluginMenuItemBase) private FFormClass: TFormClass; protected FMenuItemName: string; FCaption: String; procedure init;Virtual; procedure Embedded(const AParent: THandle); override; public constructor Create(AFormClass: TFormClass; AMenuItemName: string; ATypeID: Int64; ACaption: String); virtual; destructor destroy;override; class function New(AFormClass: TFormClass; AMenuItemName: string; ATypeID: Int64; ACaption: String): IPluginMenuItem; procedure DoStart; override; function GetInterface: IPluginExecuteBase; override; function GetCaption: string; override; procedure DoClick(const AParent: THandle); override; end; implementation { TPluginFormMenuService } procedure TPluginMenuItemBase.DoClick(const AParent: THandle); var LForm: TForm; begin LForm := GetForm(AParent); if LForm = nil then exit; LForm.ShowModal; end; function TPluginMenuItemBase.GetResourceName: String; begin result := ''; end; function TPluginMenuItemBase.GetCaption: string; begin result := 'Menu item ' + extractFileName(ParamStr(0)); end; function TPluginMenuItemBase.GetPath: string; begin result := ''; end; { TPluginMenuItemService<T> } constructor TPluginMenuItemService.Create(AFormClass: TFormClass; AMenuItemName: string; ATypeID: Int64; ACaption: String); begin inherited Create; FMenuItemName := AMenuItemName; FCaption := ACaption; FFormClass := AFormClass; TypeID := ATypeID; end; destructor TPluginMenuItemService.destroy; begin inherited; end; procedure TPluginMenuItemService.DoClick(const AParent: THandle); begin init; inherited; end; procedure TPluginMenuItemService.DoStart; begin inherited; PluginApplication.RegisterMenuItem(FMenuItemName, GetCaption, self); end; procedure TPluginMenuItemService.Embedded(const AParent: THandle); begin init; inherited; end; function TPluginMenuItemService.GetCaption: string; begin result := FCaption; end; function TPluginMenuItemService.GetInterface: IPluginExecuteBase; begin result := self as IPluginMenuItem; end; procedure TPluginMenuItemService.init; begin FreeAndNil(FForm); SetForm(FFormClass.Create(nil)); FForm.Caption := FCaption; FOwned := true; end; class function TPluginMenuItemService.New(AFormClass: TFormClass; AMenuItemName: string; ATypeID: Int64; ACaption: String): IPluginMenuItem; var dlg: TPluginMenuItemService; begin dlg := TPluginMenuItemService.Create(AFormClass, AMenuItemName, ATypeID, ACaption); result := dlg; end; end.
unit unitInput; interface type TInput = class(TObject) private { Private declarations } public { Public declarations } caption: String; trigger: String; trigger2: String; props: array[1..10,1..16] of string; constructor Create(ncaption: String); end; implementation constructor TInput.Create(ncaption: String); var i, j: integer; begin inherited Create; caption := ncaption; for i := 1 to 10 do for j := 1 to 16 do props[i,j]:=''; trigger := ''; trigger2 := ''; end; end.
unit MFichas.Model.Caixa.Metodos.Sangria; interface uses System.SysUtils, System.Bluetooth, MFichas.Model.Caixa.Interfaces, MFichas.Model.Entidade.CAIXA, MFichas.Model.Entidade.CAIXAOPERACOES, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Controller.Types; type TModelCaixaMetodosSangria = class(TInterfacedObject, iModelCaixaMetodosSangria) private [weak] FParent : iModelCaixa; FEntidade : TCAIXAOPERACOES; FValorSangria: Currency; FOperador : String; FBluetooth : iModelConexaoBluetooth; constructor Create(AParent: iModelCaixa); procedure Imprimir; procedure Gravar; procedure LimparEntidade; public destructor Destroy; override; class function New(AParent: iModelCaixa): iModelCaixaMetodosSangria; function SetValorSangria(AValue: Currency): iModelCaixaMetodosSangria; function SetOperador(AOperador: String) : iModelCaixaMetodosSangria; function &End : iModelCaixaMetodos; end; implementation { TModelCaixaMetodosSangria } function TModelCaixaMetodosSangria.&End: iModelCaixaMetodos; begin //TODO: IMPLEMENTAR METODO DE SANGRIA Result := FParent.Metodos; Imprimir; Gravar; LimparEntidade; end; procedure TModelCaixaMetodosSangria.Gravar; var LCaixaOperacoes: TCAIXAOPERACOES; begin FParent.DAO.Modify(FParent.Entidade); FParent.Entidade.OPERACOES.Add(TCAIXAOPERACOES.Create); LCaixaOperacoes := FParent.Entidade.OPERACOES.Last; LCaixaOperacoes.CAIXA := FParent.Entidade.GUUID; LCaixaOperacoes.TIPO := Integer(ocSangria); LCaixaOperacoes.VALOR := FValorSangria; LCaixaOperacoes.OPERADOR := FOperador; FParent.DAO.Update(FParent.Entidade); end; procedure TModelCaixaMetodosSangria.Imprimir; var LSocket: TBluetoothSocket; begin FBluetooth.ConectarDispositivo(LSocket); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(49))); LSocket.SendData(TEncoding.UTF8.GetBytes('SANGRIA' + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(49))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(97) + chr(49))); LSocket.SendData(TEncoding.UTF8.GetBytes(DateTimeToStr(Now) + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(100) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(1))); LSocket.SendData(TEncoding.UTF8.GetBytes('(-)VALOR: ' + FormatCurr('#,##0.00', FValorSangria) + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(27) + chr(33) + chr(0))); LSocket.SendData(TEncoding.UTF8.GetBytes('------------------------' + chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(10))); LSocket.SendData(TEncoding.UTF8.GetBytes(chr(10))); end; procedure TModelCaixaMetodosSangria.LimparEntidade; begin FParent.Entidade.OPERACOES.Clear; end; constructor TModelCaixaMetodosSangria.Create(AParent: iModelCaixa); begin FParent := AParent; FEntidade := TCAIXAOPERACOES.Create; FBluetooth := TModelConexaoFactory.New.ConexaoBluetooth; end; destructor TModelCaixaMetodosSangria.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; {$ENDIF} inherited; end; class function TModelCaixaMetodosSangria.New(AParent: iModelCaixa): iModelCaixaMetodosSangria; begin Result := Self.Create(AParent); end; function TModelCaixaMetodosSangria.SetOperador( AOperador: String): iModelCaixaMetodosSangria; begin Result := Self; FOperador := AOperador; end; function TModelCaixaMetodosSangria.SetValorSangria( AValue: Currency): iModelCaixaMetodosSangria; begin Result := Self; if AValue <= 0 then raise Exception.Create( 'Para fazer uma sangria, insira um valor maior que R$0.' ); FValorSangria := AValue; end; end.
unit mnSynHighlighterD; {$mode objfpc}{$H+} {** * * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey *} { } interface uses Classes, SysUtils, SynEdit, SynEditTypes, SynEditHighlighter, SynHighlighterHashEntries, mnSynHighlighterMultiProc; type { TDProcessor } TDProcessor = class(TCommonSynProcessor) private protected function GetIdentChars: TSynIdentChars; override; function GetEndOfLineAttribute: TSynHighlighterAttributes; override; public procedure QuestionProc; procedure SlashProc; procedure AtProc; procedure GreaterProc; procedure LowerProc; procedure Next; override; procedure Prepare; override; procedure MakeProcTable; override; end; { TSynDSyn } TSynDSyn = class(TSynMultiProcSyn) private protected function GetSampleSource: string; override; public class function GetLanguageName: string; override; public constructor Create(AOwner: TComponent); override; procedure InitProcessors; override; published end; const SYNS_LangD = 'D'; SYNS_FilterD = 'D Lang Files (*.d;*.dd)|*.d;*.dd'; cDSample = 'import std.stdio;'#13#10+ '// Computes average line length for standard input.'#13#10+ ''#13#10+ 'void main()'#13#10+ '{'#13#10+ ' ulong lines = 0;'#13#10+ ' double sumLength = 0;'#13#10+ ' foreach (line; stdin.byLine())'#13#10+ ' {'#13#10+ ' ++lines;'#13#10+ ' sumLength += line.length;'#13#10+ ' }'#13#10+ ' writeln("Average line length: ",'#13#10+ ' lines ? sumLength / lines : 0);'#13#10+ '}'#13#10; {$INCLUDE 'DKeywords.inc'} implementation uses mnUtils; procedure TDProcessor.GreaterProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); if Parent.FLine[Parent.Run] in ['=', '>'] then Inc(Parent.Run); end; procedure TDProcessor.LowerProc; begin Parent.FTokenID := tkSymbol; Inc(Parent.Run); case Parent.FLine[Parent.Run] of '=': Inc(Parent.Run); '<': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '=' then Inc(Parent.Run); end; end; end; procedure TDProcessor.SlashProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '/': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '*' then DocumentSLProc else if ScanMatch('TODO') then DocumentSLProc else CommentSLProc; end; '*': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '*' then DocumentMLProc else CommentMLProc; end; '+': begin Inc(Parent.Run); if Parent.FLine[Parent.Run] = '+' then SpecialDocumentMLProc else SpecialCommentMLProc; end else Parent.FTokenID := tkSymbol; end; end; procedure TDProcessor.AtProc; begin Inc(Parent.Run); Parent.FTokenID := tkVariable; WordProc; end; procedure TDProcessor.MakeProcTable; var I: Char; begin inherited; for I := #33 to #255 do case I of '?': ProcTable[I] := @QuestionProc; '@': ProcTable[I] := @AtProc; '''': ProcTable[I] := @StringSQProc; '"': ProcTable[I] := @StringDQProc; '`': ProcTable[I] := @StringBQProc; '/': ProcTable[I] := @SlashProc; '>': ProcTable[I] := @GreaterProc; '<': ProcTable[I] := @LowerProc; '0'..'9': ProcTable[I] := @NumberProc; 'A'..'Z', 'a'..'z', '_': ProcTable[I] := @IdentProc; end; end; procedure TDProcessor.QuestionProc; begin Inc(Parent.Run); case Parent.FLine[Parent.Run] of '>': begin Parent.Processors.Switch(Parent.Processors.MainProcessor); Inc(Parent.Run); Parent.FTokenID := tkProcessor; end else Parent.FTokenID := tkSymbol; end; end; procedure TDProcessor.Next; begin Parent.FTokenPos := Parent.Run; if (Parent.FLine[Parent.Run] in [#0, #10, #13]) then ProcTable[Parent.FLine[Parent.Run]] else case Range of rscComment: begin CommentMLProc; end; rscSpecialComment: begin SpecialCommentMLProc; end; rscDocument: begin DocumentMLProc; end; rscSpecialDocument: begin SpecialDocumentMLProc; end; rscStringSQ, rscStringDQ, rscStringBQ: StringProc; else if ProcTable[Parent.FLine[Parent.Run]] = nil then UnknownProc else ProcTable[Parent.FLine[Parent.Run]]; end; end; procedure TDProcessor.Prepare; begin inherited; EnumerateKeywords(Ord(tkKeyword), sDKeywords, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkFunction), sDFunctions, TSynValidStringChars, @DoAddKeyword); EnumerateKeywords(Ord(tkType), sDTypes, TSynValidStringChars, @DoAddKeyword); SetRange(rscUnknown); end; function TDProcessor.GetEndOfLineAttribute: TSynHighlighterAttributes; begin if (Range in [rscDocument, rscSpecialDocument]) or (LastRange in [rscDocument, rscSpecialDocument]) then Result := Parent.DocumentAttri else Result := inherited GetEndOfLineAttribute; end; function TDProcessor.GetIdentChars: TSynIdentChars; begin Result := TSynValidStringChars + ['$', '.']; end; constructor TSynDSyn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultFilter := SYNS_FilterD; end; procedure TSynDSyn.InitProcessors; begin inherited; Processors.Add(TDProcessor.Create(Self, 'D')); Processors.MainProcessor := 'D'; Processors.DefaultProcessor := 'D'; end; class function TSynDSyn.GetLanguageName: string; begin Result := SYNS_LangD; end; function TSynDSyn.GetSampleSource: string; begin Result := cDSample; end; end.
unit GX_KbdShortCutBroker; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, Menus, GX_EventHook; type EDuplicateShortCut = class(Exception); type TTriggerMethod = TNotifyEvent; IGxKeyboardShortCut = interface(IUnknown) ['{D97839F1-CF61-11D3-A93F-D0E07D000000}'] function GetShortCut: TShortCut; procedure SetShortCut(const Value: TShortCut); property ShortCut: TShortCut read GetShortCut write SetShortCut; end; IGxKeyboardShortCutForMenuItem = interface(IGxKeyboardShortCut) ['{D97839F2-CF61-11D3-A93F-D0E07D000000}'] function GetMenuItemName: string; property MenuItemName: string read GetMenuItemName; end; IGxKeyboardShortCutBroker = interface(IUnknown) ['{0C1C3891-CFEA-11D3-A940-AA8F24000000}'] // Request an *IDE-global* keyboard shortcut. function RequestOneKeyShortCut(const Trigger: TTriggerMethod; ShortCut: TShortCut = 0): IGxKeyboardShortCut; // Request an IDE keyboard shortcut which at the same // time is a keyboard shortcut for a menu item. function RequestMenuShortCut(const Trigger: TTriggerMethod; const MenuItem: TMenuItem): IGxKeyboardShortCut; // If a number of keyboard shortcuts are going to be // changed, use BeginUpdate and EndUpdate to delay // the updating so that the number of cycles for // handler installation / removal is minimized. procedure BeginUpdate; procedure EndUpdate; procedure DoUpdateKeyBindings; end; function GxKeyboardShortCutBroker: IGxKeyboardShortCutBroker; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} ToolsAPI, Forms, Controls, Types, Graphics, Messages, Windows, Contnrs, GX_GenericClasses, GX_GExperts, GX_IdeUtils, GX_ConfigurationInfo, GX_EditorEnhancements, GX_GxUtils, GX_dzVclUtils, GX_OtaUtils; // First of all we have shared code; in // particular, we share a large chunk // from the broker and the basic // shortcut container. type TGxBaseKeyboardShortCutBroker = class(TSingletonInterfacedObject, IGxKeyboardShortCutBroker) private FShortCutList: TObjectList; FKeyboardName: string; private procedure NotifyOneShortCutDestruction(AGxKeyboardShortCut: TObject); procedure RemoveOneKeyShortCut(AGxOneKeyShortCut: TObject); procedure UpdateShortCut(AGxKeyboardShortCut: TObject; NewShortCut: TShortCut); procedure AssertNoDuplicateShortCut(const Value: TShortCut); virtual; function Updating: Boolean; virtual; // Note that while DoUpdateKeyBindings has the magic "key binding" // in the identifier name, it is agnostic to the actual method used // for binding keys to actions. IOW, DoUpdateKeyBindings does not // imply the use if IOTAKeyboardBindingServices (although that // is exactly the way it is implemented in a descendant class). procedure DoUpdateKeyBindings; virtual; abstract; procedure RemoveShortCut(AShortcutList: TObjectList; AGxKeyboardShortCut: TObject); public constructor Create; destructor Destroy; override; procedure BeginUpdate; procedure EndUpdate; function RequestOneKeyShortCut(const ATrigger: TTriggerMethod; AShortCut: TShortCut = 0): IGxKeyboardShortCut; virtual; function RequestMenuShortCut(const ATrigger: TTriggerMethod; const AMenuItem: TMenuItem): IGxKeyboardShortCut; virtual; abstract; function GetKeyboardName: string; end; var PrivateGxKeyboardShortCutBroker: TGxBaseKeyboardShortCutBroker; type TGxKeyboardShortCut = class(TInterfacedObject) protected FOwner: TGxBaseKeyboardShortCutBroker; FTrigger: TTriggerMethod; public constructor Create(AOwner: TGxBaseKeyboardShortCutBroker; ATrigger: TTriggerMethod); procedure Execute; end; type TGxOneKeyShortCut = class(TGxKeyboardShortCut, IGxKeyboardShortCut, IGxKeyboardShortCutForMenuItem) private FShortCut: TShortCut; FMenuItemName: string; protected // IGxKeyboardShortCut function GetShortCut: TShortCut; function GetTrigger: TTriggerMethod; procedure SetShortCut(const Value: TShortCut); // IGxKeyboardShortCutForMenuItem function GetMenuItemName: string; public constructor Create(AOwner: TGxBaseKeyboardShortCutBroker; ATrigger: TTriggerMethod; AShortCut: TShortCut); destructor Destroy; override; property ShortCut: TShortCut read GetShortCut write SetShortCut; property Trigger: TTriggerMethod read GetTrigger write FTrigger; property MenuItemName: string read GetMenuItemName write FMenuItemName; end; // **************************************************************************** function LocateKeyboardShortCut(ShortCutList: TObjectList; KeyCode: TShortCut): TGxOneKeyShortCut; var i: Integer; AShortCutItem: TGxOneKeyShortCut; begin Assert(Assigned(ShortCutList)); Result := nil; i := ShortCutList.Count; while i > 0 do begin Dec(i); AShortCutItem := ShortCutList[i] as TGxOneKeyShortCut; Assert(Assigned(AShortCutItem)); if AShortCutItem.GetShortCut = KeyCode then begin Result := AShortCutItem; Break; end; end; end; // **************************************************************************** { TGxBaseKeyboardShortCutBroker } procedure TGxBaseKeyboardShortCutBroker.AssertNoDuplicateShortCut(const Value: TShortCut); resourcestring SDuplicateShortCut = 'The shortcut "%s" has already been assigned.'; var i: Integer; AGxShortCut: TGxOneKeyShortCut; begin Assert(FShortCutList <> nil); for i := 0 to FShortCutList.Count-1 do begin AGxShortCut := FShortCutList[i] as TGxOneKeyShortCut; if AGxShortCut.GetShortCut = Value then begin // The shortcut being passed in has already // been claimed by someone else. Complain. raise EDuplicateShortCut.CreateFmt(SDuplicateShortCut, [ShortCutToText(Value)]); end; end; end; procedure TGxBaseKeyboardShortCutBroker.BeginUpdate; begin // By default, we do not support BeginUpdate / EndUpdate end; constructor TGxBaseKeyboardShortCutBroker.Create; const DoOwnObjects = True; begin inherited Create; FShortCutList := TObjectList.Create(not DoOwnObjects); end; destructor TGxBaseKeyboardShortCutBroker.Destroy; begin if Assigned(FShortCutList) then begin Assert(FShortCutList.Count = 0); FreeAndNil(FShortCutList); end; inherited Destroy; end; procedure TGxBaseKeyboardShortCutBroker.EndUpdate; begin // By default, we do not support BeginUpdate / EndUpdate end; function TGxBaseKeyboardShortCutBroker.GetKeyboardName: string; begin Result := FKeyboardName; end; procedure TGxBaseKeyboardShortCutBroker.NotifyOneShortCutDestruction( AGxKeyboardShortCut: TObject); begin Assert(Assigned(AGxKeyboardShortCut)); RemoveOneKeyShortCut(AGxKeyboardShortCut); end; procedure TGxBaseKeyboardShortCutBroker.RemoveShortCut(AShortcutList: TObjectList; AGxKeyboardShortCut: TObject); begin Assert(AShortCutList <> nil); // Since all keyboard shortcuts are exposed and // managed through interfaces, they auto-destroy // themselves. Hence we must guarantee that the // internal list to keep their references does // not destroy them, too. Assert(AShortCutList.OwnsObjects = False); Assert(AShortCutList.Remove(AGxKeyboardShortCut) <> -1); if not Updating then DoUpdateKeyBindings; end; procedure TGxBaseKeyboardShortCutBroker.RemoveOneKeyShortCut(AGxOneKeyShortCut: TObject); begin RemoveShortCut(FShortCutList, AGxOneKeyShortCut); end; function TGxBaseKeyboardShortCutBroker.RequestOneKeyShortCut( const ATrigger: TTriggerMethod; AShortCut: TShortCut): IGxKeyboardShortCut; var AShortCutContainer: TGxKeyboardShortCut; begin Assert(Assigned(ATrigger), 'ATrigger not assigned'); Assert(AShortCut <> 0, 'AShortCut is 0'); AShortCutContainer := TGxOneKeyShortCut.Create(Self, ATrigger, AShortCut); FShortCutList.Add(AShortCutContainer); Result := AShortCutContainer as IGxKeyboardShortCut; end; procedure TGxBaseKeyboardShortCutBroker.UpdateShortCut( AGxKeyboardShortCut: TObject; NewShortCut: TShortCut); var ListIndex: Integer; KbdShortCut: TGxOneKeyShortCut; begin Assert(FShortCutList <> nil); ListIndex := FShortCutList.IndexOf(AGxKeyboardShortCut); Assert(ListIndex <> -1); KbdShortCut := FShortCutList.Items[ListIndex] as TGxOneKeyShortCut; if NewShortCut <> KbdShortCut.GetShortCut then begin // Verify that the new shortcut has not been claimed // already; throws an exception if the shortcut has // been claimed already. // This is disabled because it caused more problems than it helped //AssertNoDuplicateShortCut(NewShortCut); // We need to directly update the field here, // as the class itself always forwards requests // for changes to the ShortCut via a property // setter to this method. KbdShortCut.FShortCut := NewShortCut; if not Updating then DoUpdateKeyBindings; end; end; function TGxBaseKeyboardShortCutBroker.Updating: Boolean; begin // By default, we do not support BeginUpdate / EndUpdate Result := False; end; { TGxKeyboardShortCut } constructor TGxKeyboardShortCut.Create(AOwner: TGxBaseKeyboardShortCutBroker; ATrigger: TTriggerMethod); begin inherited Create; Assert(AOwner <> nil); Assert(Assigned(ATrigger)); FOwner := AOwner; FTrigger := ATrigger; end; procedure TGxKeyboardShortCut.Execute; begin if Assigned(FTrigger) then FTrigger(nil); end; { TGxOneKeyShortCut } constructor TGxOneKeyShortCut.Create(AOwner: TGxBaseKeyboardShortCutBroker; ATrigger: TTriggerMethod; AShortCut: TShortCut); begin inherited Create(AOwner, ATrigger); FShortCut := AShortCut; end; destructor TGxOneKeyShortCut.Destroy; begin if FOwner <> nil then FOwner.NotifyOneShortCutDestruction(Self); FOwner := nil; inherited Destroy; end; function TGxOneKeyShortCut.GetMenuItemName: string; begin Result := FMenuItemName; end; function TGxOneKeyShortCut.GetShortCut: TShortCut; begin Result := FShortCut; end; function TGxOneKeyShortCut.GetTrigger: TTriggerMethod; begin Result := FTrigger; end; procedure TGxOneKeyShortCut.SetShortCut(const Value: TShortCut); begin Assert(FOwner <> nil); // UpdateShortCut will update the internal // status of FShortCut on success. FOwner.UpdateShortCut(Self, Value); end; // **************************************************************************** const InvalidIndex = -1; type TGxNativeKeyboardShortCutBroker = class(TGxBaseKeyboardShortCutBroker, IGxKeyboardShortCutBroker) private FKeyboardBindingIndex: Integer; FUpdateCount: Integer; FInstallingKeyboardBinding: Boolean; private procedure InstallKeyboardBindings; procedure RemoveKeyboardBindings; procedure RemoveRemainingShortCuts; //procedure UpdateShortCut(AGxKeyboardShortCut: TObject; NewShortCut: TShortCut); override; function Updating: Boolean; override; procedure DoUpdateKeyBindings; override; procedure AssertNoDuplicateShortCut(const Value: TShortCut); override; public function RequestMenuShortCut(const Trigger: TTriggerMethod; const MenuItem: TMenuItem): IGxKeyboardShortCut; override; procedure BeginUpdate; procedure EndUpdate; public constructor Create; destructor Destroy; override; end; type TGxKeyboardBinding = class(TNotifierObject, IOTAKeyboardBinding) private // IOTAKeyboardBinding function GetBindingType: TBindingType; function GetDisplayName: string; function GetName: string; procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices); private FOwner: TGxNativeKeyboardShortCutBroker; procedure KeyBindingHandler(const Context: IOTAKeyContext; KeyCode: TShortCut; var BindingResult: TKeyBindingResult); public constructor Create(AOwner: TGxNativeKeyboardShortCutBroker); destructor Destroy; override; end; { TGxNativeKeyboardShortCutBroker } procedure TGxNativeKeyboardShortCutBroker.AssertNoDuplicateShortCut(const Value: TShortCut); begin inherited; // Here we could try to implement additional // sanity checks, where we query the IDE for // shortcuts that are in use. end; procedure TGxNativeKeyboardShortCutBroker.BeginUpdate; begin Inc(FUpdateCount); end; constructor TGxNativeKeyboardShortCutBroker.Create; begin inherited Create; FKeyboardBindingIndex := InvalidIndex; end; destructor TGxNativeKeyboardShortCutBroker.Destroy; begin Assert(not Updating); RemoveKeyboardBindings; // In an expert dies during destruction, it might still have a shortcut {$IFOPT D+} if FShortCutList.Count > 0 then SendDebugError(IntToStr(FShortCutList.Count) + ' shortcuts remain unregistered!'); {$ENDIF} RemoveRemainingShortCuts; inherited Destroy; end; procedure TGxNativeKeyboardShortCutBroker.DoUpdateKeyBindings; begin RemoveKeyboardBindings; InstallKeyboardBindings; end; procedure TGxNativeKeyboardShortCutBroker.EndUpdate; begin Assert(FUpdateCount >= 1); Dec(FUpdateCount); if (FUpdateCount = 0) then begin if RunningDelphi8OrGreater then begin if Assigned(GExpertsInst(False)) then if not GExpertsInst.StartingUp then DoUpdateKeyBindings; end else DoUpdateKeyBindings; end end; procedure TGxNativeKeyboardShortCutBroker.InstallKeyboardBindings; var IKeyboardServices: IOTAKeyboardServices; IKeyboardBinding: IOTAKeyboardBinding; begin Assert(FKeyboardBindingIndex = InvalidIndex); // XE5, and probably older versions, will AV when you add a keyboard binding // (IKeyboardServices.AddKeyboardBinding), when Delphi is shutting down. // The AV is in a TMenuItem which is nil. if Assigned(Application) and (csDestroying in Application.ComponentState) then Exit; if FShortCutList.Count > 0 then begin IKeyboardServices := GxOtaGetKeyboardServices; IKeyboardBinding := TGxKeyboardBinding.Create(Self); FKeyboardName := IKeyboardBinding.Name; Assert(Assigned(IKeyboardServices)); try // Starting with Delphi XE3 apparently this gets called again from within // the call to IKeyboardServices.AddKeyboardBinding, so FKeyboardBindingIndex // isn't set. Therefore this workaround: It prevents the second call // and the resulting exception(s) if not FInstallingKeyboardBinding then begin try FInstallingKeyboardBinding := true; if ConfigInfo.EnableKeyboardShortcuts then FKeyboardBindingIndex := IKeyboardServices.AddKeyboardBinding(IKeyboardBinding); finally FInstallingKeyboardBinding := false; end; end; except on E: Exception do begin {$IFOPT D+} SendDebugError('Error registering keyboard shortcuts with IDE: ' + E.Message); {$ENDIF} raise E.Create('Error registering keyboard shortcuts with IDE: ' +E.Message); end; end; end; end; procedure TGxNativeKeyboardShortCutBroker.RemoveKeyboardBindings; var IKeyboardServices: IOTAKeyboardServices; begin // If the keyboard binding has been // installed, remove it - otherwise // ignore the request to remove it. if FKeyboardBindingIndex <> InvalidIndex then begin IKeyboardServices := GxOtaGetKeyboardServices; try IKeyboardServices.RemoveKeyboardBinding(FKeyboardBindingIndex); except on E: Exception do raise E.Create('Error removing keyboard shortcuts from IDE: ' +E.Message); end; FKeyboardBindingIndex := InvalidIndex; end; end; procedure TGxNativeKeyboardShortCutBroker.RemoveRemainingShortCuts; begin BeginUpdate; try while FShortCutList.Count > 0 do RemoveOneKeyShortCut(FShortCutList.Items[0]); finally EndUpdate; end; end; function TGxNativeKeyboardShortCutBroker.RequestMenuShortCut( const Trigger: TTriggerMethod; const MenuItem: TMenuItem): IGxKeyboardShortCut; var AShortCutContainer: TGxOneKeyShortCut; begin Assert(Assigned(Trigger), 'Trigger not assigned'); Assert(Assigned(MenuItem), 'MenuItem not assigned'); Assert(MenuItem.Name <> '', 'MenuItem.Name is empty'); AShortCutContainer := TGxOneKeyShortCut.Create(Self, Trigger, 0); AShortCutContainer.FTrigger := Trigger; AShortCutContainer.FMenuItemName := MenuItem.Name; Result := AShortCutContainer as IGxKeyboardShortCut; FShortCutList.Add(AShortCutContainer); end; function TGxNativeKeyboardShortCutBroker.Updating: Boolean; begin Result := (FUpdateCount > 0); end; { TGxKeyboardBinding } procedure TGxKeyboardBinding.BindKeyboard(const BindingServices: IOTAKeyBindingServices); const DefaultKeyBindingsFlag = kfImplicitShift + kfImplicitModifier + kfImplicitKeypad; var i: Integer; KeyboardName: string; AShortCutItem: TGxOneKeyShortCut; begin Assert(FOwner <> nil); Assert(FOwner.FShortCutList <> nil); if RunningDelphi7OrGreater then KeyboardName := '' else KeyboardName := PrivateGxKeyboardShortCutBroker.GetKeyboardName; for i := 0 to FOwner.FShortCutList.Count-1 do begin AShortCutItem := FOwner.FShortCutList[i] as TGxOneKeyShortCut; if AShortCutItem.ShortCut <> 0 then begin BindingServices.AddKeyBinding([AShortCutItem.ShortCut], KeyBindingHandler, nil, DefaultKeyBindingsFlag, KeyboardName, AShortCutItem.MenuItemName); end; end; end; constructor TGxKeyboardBinding.Create(AOwner: TGxNativeKeyboardShortCutBroker); begin inherited Create; // Store reference to the keyboard shortcut broker here; // we will iterate over the broker for requested shortcuts // and install every item found there. Assert(AOwner <> nil); FOwner := AOwner; end; destructor TGxKeyboardBinding.Destroy; begin FOwner := nil; inherited Destroy; end; function TGxKeyboardBinding.GetBindingType: TBindingType; begin Result := btPartial; end; function TGxKeyboardBinding.GetDisplayName: string; resourcestring SDisplayName = 'GExperts Shortcuts'; begin Result := SDisplayName; end; function TGxKeyboardBinding.GetName: string; begin Result := 'GExperts.' + Self.ClassName; // Do not localize. end; procedure TGxKeyboardBinding.KeyBindingHandler( const Context: IOTAKeyContext; KeyCode: TShortCut; var BindingResult: TKeyBindingResult); var AShortCutItem: TGxOneKeyShortCut; begin BindingResult := krUnhandled; // Locate the shortcut in our list and dispatch // to the Execute function. Assert(FOwner <> nil); Assert(FOwner.FShortCutList <> nil); AShortCutItem := LocateKeyboardShortCut(FOwner.FShortCutList, KeyCode) as TGxOneKeyShortCut; if Assigned(AShortCutItem) and Assigned(AShortCutItem.Trigger) then begin BindingResult := krHandled; try AShortCutItem.Execute; except on E: Exception do begin // If we don't handle these, the hotkey is passed to the editor (inserts // a character) or another expert (may show another error, dialog, etc.) ApplicationShowException(E); end; end; end; end; function GxKeyboardShortCutBroker: IGxKeyboardShortCutBroker; begin if PrivateGxKeyboardShortCutBroker = nil then PrivateGxKeyboardShortCutBroker := TGxNativeKeyboardShortCutBroker.Create; Result := PrivateGxKeyboardShortCutBroker as IGxKeyboardShortCutBroker; end; procedure ReleasePrivateGxShortCutBroker; begin FreeAndNil(PrivateGxKeyboardShortCutBroker); end; initialization finalization ReleasePrivateGxShortCutBroker; end.
unit ReportGen; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; const MaxPreCol = 30; MaxSumLevel = 5; MaxSumItem = 10; fmNormal = 0; fmBold = 1; fmUnder = 2; fmItalic = 4; type THAlign = (haDefault, haLeft, haCenter, haRight); TVAlign = (vaDefault, vaTop, vaMiddle, vaBottom, vaBaseLine); TFontSize = 1..7; TSumLevels = 1..MaxSumLevel; TSumItem = 1..MaxSumItem; TNewPageEvent = procedure(Sender: TObject; PageCount: integer) of object; TGroupEvent = procedure(Sender: TObject; GroupLevel:TSumLevels;var PageBreak:boolean;var NewPageCount:integer) of object; TReportGen = class(TComponent) private FPreTags : string; FPostTags : string; FSumInts : array[TSumItem,TSumLevels] of integer; FSumReals : array[TSumItem,TSumLevels] of real; FSumCurrs : array[TSumItem,TSumLevels] of Currency; FSumLevel : TSumLEvels; FGroupExps : array[TSumLevels] of string; FPreSpacing:integer; FFileName: string; RptFile : TStream; FReportTitle: string; FOutputToFile: boolean; FCellHAlign: TStringList; FCellVAlign: TStringList; FDefaultHAlign : THAlign; FDefaultVAlign : TVAlign; FPageCount: integer; FOnNewPage: TNewPageEvent; FPreCols: array[0..MaxPreCol] of integer; FPreAlign: array[0..MaxPreCol] of THAlign; FPreFmt: array[0..MaxPreCol] of byte; FLineCount: integer; FCurrFontSize : integer; FPaging: boolean; FFontSize: TFontSize; FFontFace: string; FMarginTop: Real; FMarginBottom: Real; FPageLength: Real; FTableBorderSize: integer; FTableCellSpacing: integer; FTableCellPadding: integer; FOnGroup: TGroupEvent; procedure SetFileName(const Value: string); procedure SetReportTitle(const Value: string); procedure WriteBuf(s:string;ACrLf:boolean=true); procedure SetOnNewPage(const Value: TNewPageEvent); function haStr(Align: THAlign): string; function LineBreak(YN: boolean): string; function vaStr(VAlign: TVAlign): string; procedure SetLineCount(const Value: integer); procedure SetPaging(const Value: boolean); procedure SetFontSize(ASize:TFontSize); procedure SetFontFace(AFace:string); procedure SetMarginBottom(const Value: Real); procedure SetMarginTop(const Value: Real); procedure SetPageLength(const Value: Real); function GetSumInt(i: TSumItem): integer; procedure SetSumInt(i: TSumItem; const Value: integer); procedure SetOnGroup(const Value: TGroupEvent); function GetGroupExp(i: TSumLevels): string; function GetSumCurr(i: TSumItem): currency; function GetSumReal(i: TSumItem): real; procedure SetGroupExp(i: TSumLevels; const Value: string); procedure SetSumCurr(i: TSumItem; const Value: currency); procedure SetSumReal(i: TSumItem; const Value: real); procedure SetSumLevel(const Value: TSumLevels); procedure SetGroupInit(i: TSumLevels; const Value: string); function RestoreTags(s: string): string; function StripTags(s: string): string; function StrPadRight(s: string; len: integer): string; function StrPadCenter(s: string; len: integer): string; function FormatIt(s: string; AFmt: byte): string; function StrPadLeft(s: string; len: integer): string; { Private declarations } protected { Protected declarations } public { Public declarations } constructor create(AOwner:TComponent);override; destructor destroy;override; procedure StartReport(InitialFirstPage:boolean=true;AStream:TStream=nil; DefaultHAlign:THAlign=haLeft); procedure EndReport; procedure H1(s:string; HAlign:THAlign=haDefault); procedure H2(s:string; HAlign:THAlign=haDefault); procedure H3(s:string; HAlign:THAlign=haDefault); procedure TableStart(Border:integer=0; Width:integer=600; CellSpacing:integer=0; CellPadding:integer=0; HAlign:THAlign=haDefault); procedure TableRow(data:array of string; HAlign:THAlign=haDefault; VAlign:TVAlign=vaTop); procedure TableRowStart(HAlign:THAlign=haDefault; VAlign:TVAlign=vaTop); procedure TableRowEnd; procedure TableCell(s:string;HAlign:THAlign=haDefault; VAlign:TVAlign=vaTop;Span:integer=1); procedure TableEnd(NoWrap:boolean=true); procedure Txt(s:string;CR:boolean=true); procedure CellWidths(ca:array of integer); procedure CellAligns(ca:array of THAlign); property PageCount:integer read FPageCount; procedure HorizontalLine(AWidth:integer; ASize:integer=1; HAlign:THAlign=haDefault; CR:boolean=true); procedure NewPage(StartPageCount:integer=0); // default of zero means not to reset the page counter procedure NewLine; procedure Pre(AFontSize:TFontSize); procedure PreEnd; procedure PreColSet(pc:array of integer; ASpacing:integer=1); procedure PreColClear; procedure PreAlignSet(ca:array of THAlign); procedure PreFmtSet(fa:array of byte); procedure PreTxt(pa:Array of string); procedure PreStr(s:string;spacing: integer;hAlign:THAlign=haDefault); procedure PreLF(n:integer=1); procedure PreLine(w:integer); procedure PreOut(s:string); // Features procedure UnderOn; procedure UnderOff; procedure BoldOn; procedure BoldOff; procedure ItalicOn; procedure ItalicOff; // Line Counts function LineQuery(n:integer):boolean; function MaxLines: integer; property LineCount:integer read FLineCount write SetLineCount; property FontSize:TFontSize read FFontSize write SetFontSize; property FontFace:string read FFontFace write SetFontFace; procedure FontEnd; // Summary Vars property SumInt[i:TSumItem]:integer read GetSumInt write SetSumInt; property SumReal[i:TSumItem]:real read GetSumReal write SetSumReal; property SumCurr[i:TSumItem]:currency read GetSumCurr write SetSumCurr; property GroupExp[i:TSumLevels]:string read GetGroupExp write SetGroupExp; property GroupInit[i:TSumLevels]:string write SetGroupInit; property SumLevel:TSumLevels read FSumLevel write SetSumLevel; published { Published declarations } property FileName:string read FFileName write SetFileName; property ReportTitle:string read FReportTitle write SetReportTitle; property OnNewPage:TNewPageEvent read FOnNewPage write SetOnNewPage; property OnGroup:TGroupEvent read FOnGroup write SetOnGroup; property Paging:boolean read FPaging write SetPaging; property PageLength:Real read FPageLength write SetPageLength; property MarginTop:Real read FMarginTop write SetMarginTop; property MarginBottom:Real read FMarginBottom write SetMarginBottom; end; function HRef(DisplayText, Link: String): string; procedure RptLineDivide(s:string; AList:TStringList; AMaxLen:integer; LineSplitChar:char=#0); procedure Register; implementation const // FontSizes : array[TFontSize] of integer = (8,10,12,14,18,24,36); not really used. Just here for reference FontHites : array[TFontSize] of integer = (11,14,16,19,24,32,48); // FontHites : array[TFontSize] of integer = (15,17,20,23,28,36,52); PixPerInch = 96; function GTLT(AString:string):string; var x : integer; begin result := ''; for x := 1 to length(AString) do begin if AString[x] = '<' then result := result + '&LT' else if AString[x] = '>' then result := result + '&GT' else result := result + AString[x]; end; end; procedure RptLineDivide(s:string; AList:TStringList; AMaxLen:integer; LineSplitChar:char=#0); var x,y : integer; temp : string; begin AList.Clear; AList.Text := s; if LineSplitChar <> #0 then begin // way to use pipe | to split lines x := 0; while x < AList.Count do begin y := pos(LineSplitChar,AList[x]); if y > 0 then begin AList.Insert(x+1,copy(AList[x],y+1,length(AList[x]))); AList[x] := copy(AList[x],1,y-1); end; inc(x); end; end; x := 0; while (x < AList.count) do begin if Length(AList[x]) > AMaxLen then begin y := AMaxLen; while (y > 0) do begin if AList[x][y] = ' ' then break else dec(y); end; if y > 0 then begin // a space was found to break on temp := copy(AList[x],y+1,length(AList[x])); AList[x] := copy(AList[x],1,y); AList.Insert(x+1,temp); end else begin temp := copy(AList[x], y+1, length(AList[x])); AList[x] := copy(AList[x],1,AMaxLen); AList.Insert(x+1,temp); end; end; inc(x); end; for x := 0 to AList.count-1 do AList[x] := GTLT(AList[x]); end; function NoBlank(s:string):string; begin if trim(s)='' then result := '&nbsp' else result := s; end; function TReportGen.LineBreak(YN:boolean):string; begin if yn then result := '<BR>' else result := ''; end; function TReportGen.haStr(Align:THAlign):string; begin case Align of haDefault : if FDefaultHAlign <> haDefault then result := haStr(FDefaultHAlign) else result := '"Left"'; haLeft : result := '"Left"'; haCenter : result := '"Center"'; haRight : result := '"Right"'; end; end; function TReportGen.vaStr(VAlign:TVAlign):string; begin case VAlign of vaDefault : if FDefaultVAlign <> vaDefault then result := vaStr(FDefaultVAlign) else result := '"Top"'; vaTop : result := '"Top"'; vaMiddle : result := '"Middle"'; vaBottom : result := '"Bottom"'; vaBaseLine : result := '"BaseLine"'; end; end; procedure Register; begin RegisterComponents('FFS Controls', [TReportGen]); end; { TReportGen } procedure TReportGen.CellAligns(ca: array of THAlign); var x : integer; begin FCellHAlign.Clear; for x := low(ca) to high(ca) do FCellHAlign.Add(haStr(ca[x])); end; procedure TReportGen.CellWidths(ca: array of integer); var x : integer; begin writebuf('<TR>'); for x := low(ca) to high(ca) do WriteBuf('<TD WIDTH=' + inttostr(ca[x]) + '></TD>'); writebuf('</TR>'); end; constructor TReportGen.create(AOwner: TComponent); begin inherited; FCellHAlign := TStringList.create; FCellVAlign := TStringList.Create; FDefaultHAlign := haLeft; FDefaultVAlign := vaTop; FPageLength := 11; FMarginTop := 0.5; FMarginBottom := 0.5; end; destructor TReportGen.destroy; begin FCellVAlign.Free; FCellHAlign.Free; inherited; end; procedure TReportGen.EndReport; begin writebuf('</BODY>'); writebuf('</HTML>'); if FOutputToFile then RptFile.Free; end; procedure TReportGen.H1(s: string; HAlign:THAlign); begin writebuf('<H1 ALIGN=' + haStr(HAlign) + '>' + s + '</H1>'); LineCount := LineCount + PixPerInch; {1 inch} end; procedure TReportGen.H2(s: string; HAlign:THAlign); begin writebuf('<H2 ALIGN=' + haStr(HAlign) + '>' + s + '</H2>'); LineCount := LineCount + (PixPerInch div 2); {1/2 inch} end; procedure TReportGen.H3(s: string; HAlign:THAlign); begin writebuf('<H3 ALIGN=' + haStr(HAlign) + '>' + s + '</H3>'); LineCount := LineCount + (PixPerInch div 4); {1/4 inch} end; procedure TReportGen.HorizontalLine(AWidth, ASize: integer; HAlign: THAlign; CR:boolean); var s : string; begin s := '<HR WIDTH=' + inttostr(AWidth) + ' SIZE=' + inttostr(ASize) + ' ALIGN=' + haStr(HAlign) + '>' + LineBreak(cr); writebuf(s); if cr then LineCount := LineCount + (FontHites[FCurrFontSize]); end; procedure TReportGen.NewPage(StartPageCount: integer); begin WriteBuf('<PAGE>'); FLineCount := 0; if StartPageCount > 0 then FPageCount := StartPageCount else FPageCount := FPageCount + 1; if assigned(FOnNewPage) then FOnNewPage(self, PageCount); end; procedure TReportGen.SetFileName(const Value: string); begin FFileName := Value; end; procedure TReportGen.SetOnNewPage(const Value: TNewPageEvent); begin FOnNewPage := Value; end; procedure TReportGen.SetReportTitle(const Value: string); begin FReportTitle := Value; end; procedure TReportGen.StartReport(InitialFirstPage:boolean;AStream:TStream; DefaultHAlign:THAlign); var x : TSumLevels; begin FSumLevel := 1; for x := 1 to MaxSumLevel do FGroupExps[x] := ''; fillchar(Fsumints,sizeof(Fsumints),0); fillchar(Fsumreals,sizeof(Fsumreals),0); fillchar(Fsumcurrs,sizeof(Fsumcurrs),0); LineCount := 0; FCurrFontSize := 3; fillchar(FPreAlign, sizeof(FPreAlign),0); FOutputToFile := AStream = nil; if AStream = nil then begin try if FileExists(FileName) then DeleteFile(FileName); except end; RptFile := TFileStream.Create(FileName, fmCreate); end else RptFile := AStream; FPageCount := 1; writebuf('<HTML>'); writebuf('<HEAD>'); if ReportTitle <> '' then writebuf('<TITLE>' + ReportTitle + '</TITLE>'); writebuf('</HEAD>'); writebuf('<BODY>'); if InitialFirstPage and assigned(FOnNewPage) then FOnNewPage(self, PageCount); end; procedure TReportGen.TableEnd(NoWrap:boolean); begin writebuf('</TABLE>'); if NoWrap then writebuf('<BR CLEAR=all>'); end; procedure TReportGen.TableRow(data:array of string; HAlign:THAlign; VAlign:TVAlign); var x : integer; s : string; begin TableRowStart(HAlign, VAlign); for x := low(data) to high(data) do begin s := '<TD'; try if FCellHAlign[x] <> haStr(HAlign) then s := s + ' ALIGN=' + FCellHAlign[x]; except end; s := s + '>' + NoBlank(data[x]) + '</TD>'; WriteBuf(s); end; TableRowEnd; end; procedure TReportGen.TableRowEnd; begin writebuf('</TR>'); LineCount := LineCount + (FontHites[FCurrFontSize]) + FTableBorderSize + FTableCellSpacing + FTableCellPadding; end; procedure TReportGen.TableStart(Border, Width, CellSpacing, CellPadding: integer; HAlign: THAlign); var s : string; begin FTableBorderSize := Border; FTableCellSpacing := CellSpacing; FTableCellPadding := CellPadding; s := '<TABLE WIDTH=' + inttostr(width) + ' BORDER=' + inttostr(Border) + ' CELLSPACING=' + inttostr(CellSpacing) + ' CELLPADDING=' + inttostr(CellPadding) + ' ALIGN=' + haStr(HAlign) + '>'; writebuf(s); end; procedure TReportGen.Txt(s: string; CR: boolean); begin writebuf(s + LineBreak(CR)); if cr then LineCount := LineCount + (FontHites[FCurrFontSize]); end; procedure TReportGen.WriteBuf(s: string;ACrLf:boolean=true); var i : integer; begin if ACrLf then s := s + #13 + #10; i := length(s); RptFile.Write(s[1], i); end; procedure TReportGen.NewLine; begin writebuf('<BR>'); LineCount := LineCount + (FontHites[FCurrFontSize]); end; procedure TReportGen.TableCell(s: string; HAlign: THAlign; VAlign: TVAlign; Span: integer); var t : string; begin t := '<TD ALIGN=' + haStr(HAlign) + ' VALIGN=' + vaStr(VAlign); if Span > 1 then t := t + ' COLSPAN=' + inttostr(span); t := t + '>'; writebuf(t + NoBlank(s) + '</TD>'); end; procedure TReportGen.TableRowStart(HAlign: THAlign; VAlign: TVAlign); begin writebuf('<TR ALIGN=' + haStr(HAlign) + ' VALIGN=' + vaStr(VAlign) + '>'); end; function HRef(DisplayText, Link: String): string; begin result := '<A HREF="'+ Link + '">'+DisplayText +'</A>'; end; procedure TReportGen.Pre(AFontSize:TFontSize); begin writebuf('<PRE><FONT SIZE="'+inttostr(AFontSize)+'">',false); FCurrFontSize := AFontSize; end; procedure TReportGen.PreEnd; begin writebuf('</FONT></PRE>'); end; function spaces(len:integer):string; var x : integer; begin result := ''; for x := 1 to len do result := result + ' '; end; function TReportGen.StripTags(s:string):string; var temp : string; procedure preremove(st:string); var p : integer; begin p := pos(st,temp); while p > 0 do begin fpretags := fpretags + st; // <B>, etc delete(temp, p, length(st)); p := pos(st,temp); end; end; procedure postremove(st:string); var p : integer; begin p := pos(st,temp); while p > 0 do begin fposttags := fposttags + st; // <B>, etc delete(temp, p, length(st)); p := pos(st,temp); end; end; begin FPreTags := ''; FPostTags := ''; temp := s; preremove('<B>'); preremove('<I>'); preremove('<U>'); postremove('</B>'); postremove('</I>'); postremove('</U>'); result := temp; end; function TReportGen.RestoreTags(s:string):string; begin result := FPreTags + s + FPostTags; end; function TReportGen.StrPadRight(s: string; len: integer): string; begin s := StripTags(s); if length(s) > len then result := copy(s,1,len) else result := s + spaces(len - length(s)); result := GTLT(result); result := restoreTags(result); end; function TReportGen.StrPadCenter(s: string; len: integer): string; var y,z : integer; begin s := StripTags(s); if length(s) > len then result := copy(s,1,len) else begin z := len - length(s); y := z div 2; z := z - y; result := spaces(y) + s + spaces(z); end; result := GTLT(result); result := RestoreTags(result); end; function TReportGen.StrPadLeft(s: string; len: integer): string; begin s := StripTags(s); if length(s) > len then result := copy(s,1,len) else result := spaces(len - length(s)) + s; result := GTLT(result); result := RestoreTags(result); end; function TReportGen.FormatIt(s:string;AFmt:byte):string; begin result := s; if (AFmt and fmBold) = fmBold then result := '<B>' + result + '</B>'; if (AFmt and fmItalic) = fmItalic then result := '<I>' + result + '</I>'; if (AFmt and fmUnder) = fmUnder then result := '<U>' + result + '</U>'; end; procedure TReportGen.PreTxt(pa: array of string); var x : integer; s,t : string; algn : THAlign; begin t := ''; // Bill took out the line query here. It did not follow the same principles that every other print call makes. It is ok for the last line to go over the margin. for x := low(pa) to high(pa) do begin try s := pa[x]; if x <= MaxPreCol then begin if FPreCols[x] > 0 then begin // it was assigned a width algn := FPreAlign[x]; case algn of haDefault, haLeft : s := Formatit(StrPadRight(pa[x], FPreCols[x]-FPreSpacing), FPreFmt[x]); haCenter : s := Formatit(StrPadCenter(pa[x], FPreCols[x]-FPreSpacing), FPreFmt[x]); haRight : s := Formatit(StrPadLeft(pa[x], FPreCols[x]-FPreSpacing), FPreFmt[x]); end; end; end; t := t + s + spaces(FPreSpacing); except end; end; linecount := linecount + fonthites[FCurrFontSize]; WriteBuf(t); end; procedure TReportGen.PreColSet(pc: array of integer; ASpacing:integer); var x : integer; begin for x := low(pc) to high(pc) do begin if x <= maxpreCol then FPreCols[x] := pc[x]; end; FPreSpacing := ASpacing; end; procedure TReportGen.PreColClear; begin fillchar(FPreAlign, sizeof(FPreAlign),0); fillchar(FPreCols, sizeof(FPreCols),0); fillchar(FPreFmt, sizeof(FPreFmt),0); end; procedure TReportGen.PreAlignSet(ca: array of THAlign); var x : integer; begin for x := low(ca) to high(ca) do if x <= maxpreCol then FPreAlign[x] := ca[x]; end; procedure TReportGen.PreLF(n: integer); var s : string; x : integer; begin s := ''; for x := 1 to n do begin LineCount := LineCount + FontHites[FCurrFontSize]; writebuf(s); end; end; procedure TReportGen.PreLine(w: integer); var x : integer; s : string; begin s := ''; for x := 1 to w do s := s + '_'; writebuf(s); linecount := linecount + fonthites[FCurrFontSize]; end; function TReportGen.MaxLines:integer; begin Result := Trunc(PageLength * PixPerInch); Result := Result - Trunc(PixPerInch * MarginBottom); Result := Result - Trunc(PixPerInch * MarginTop); Result := Result - PixPerInch; end; procedure TReportGen.SetLineCount(const Value: integer); begin FLineCount := Value; if Paging and (FLineCount >= MaxLines) then NewPage; end; procedure TReportGen.SetPaging(const Value: boolean); begin FPaging := Value; end; procedure TReportGen.SetFontSize(ASize: TFontSize); begin FCurrFontSize := ASize; FFontSize := ASize; writebuf('<FONT SIZE="'+inttostr(ASize)+'">'); end; procedure TReportGen.SetFontFace(AFace: string); begin FFontFace := AFace; writebuf('<FONT FACE="'+AFace+'">'); end; function TReportGen.LineQuery(n: integer): boolean; begin result := (((n+1)*FontHites[FCurrFontSize]) + LineCount) < MaxLines; end; procedure TReportGen.SetMarginBottom(const Value: Real); begin FMarginBottom := Value; end; procedure TReportGen.SetMarginTop(const Value: Real); begin FMarginTop := Value; end; procedure TReportGen.SetPageLength(const Value: Real); begin FPageLength := Value; end; procedure TReportGen.UnderOff; begin writebuf('</U>',false); end; procedure TReportGen.UnderOn; begin writebuf('<U>',false); end; procedure TReportGen.FontEnd; begin writebuf('</FONT>',false); end; procedure TReportGen.PreOut(s: string); begin writebuf(s); LineCount := LineCount + (FontHites[FCurrFontSize]); end; procedure TReportGen.BoldOff; begin writebuf('</B>',false); end; procedure TReportGen.BoldOn; begin writebuf('<B>',false); end; procedure TReportGen.ItalicOff; begin writebuf('</I>',false); end; procedure TReportGen.ItalicOn; begin writebuf('<I>',false); end; function TReportGen.GetSumInt(i: TSumItem): integer; begin result := FSumInts[i, FSumLevel]; end; procedure TReportGen.SetSumInt(i: TSumItem; const Value: integer); var x : TSumLevels; begin for x := 1 to MaxSumLevel do inc(FSumInts[i,x],Value); end; procedure TReportGen.SetOnGroup(const Value: TGroupEvent); begin FOnGroup := Value; end; function TReportGen.GetGroupExp(i: TSumLevels): string; begin result := FGroupExps[i]; end; function TReportGen.GetSumCurr(i: TSumItem): currency; begin result := FSumCurrs[i, FSumLevel]; end; function TReportGen.GetSumReal(i: TSumItem): real; begin result := FSumReals[i, FSumLevel]; end; procedure TReportGen.SetGroupExp(i: TSumLevels; const Value: string); var x : TSumItem; pb : boolean; npc : integer; begin if FGroupExps[i] <> value then begin pb := false; npc := 0; FSumLevel := i; if assigned(FOnGroup) then FOnGroup(self, i, pb, npc); FGroupExps[i] := value; // reset counters for x := 1 to MaxSumItem do begin FSumCurrs[x,i] := 0; FSumInts[x,i] := 0; FSumReals[x,i] := 0; end; if pb then NewPage(npc); end; end; procedure TReportGen.SetSumCurr(i: TSumItem; const Value: currency); var x : TSumLevels; begin for x := 1 to MaxSumLevel do FSumCurrs[i,x] := FSumCurrs[i,x] + Value; end; procedure TReportGen.SetSumReal(i: TSumItem; const Value: real); var x : TSumLevels; begin for x := 1 to MaxSumLevel do FSumReals[i,x] := FSumReals[i,x] + Value; end; procedure TReportGen.SetSumLevel(const Value: TSumLevels); begin FSumLevel := Value; end; procedure TReportGen.PreFmtSet(fa: array of byte); var x : integer; begin for x := low(fa) to high(fa) do if x <= maxpreCol then FPreFmt[x] := fa[x]; end; procedure TReportGen.SetGroupInit(i: TSumLevels; const Value: string); begin FGroupExps[i] := value; // This does not trigger an event end; procedure TReportGen.PreStr(s: string; spacing: integer; hAlign: THAlign); var t : string; begin t := ''; case HAlign of haDefault, haLeft : s := StrPadRight(s, Spacing); haCenter : s := StrPadCenter(s, Spacing); haRight : s := StrPadLeft(s, Spacing); end; t := t + s; WriteBuf(t,False); end; end.
unit WordsRTTIPack; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\WordsRTTIPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "WordsRTTIPack" MUID: (550C25D70182) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , l3Interfaces , tfwScriptingInterfaces , l3CProtoObject ; type ItfwWordBox = interface ['{16F9981D-A4AE-47B8-940F-7ED27AF34B87}'] function Get_Boxed: TtfwWord; property Boxed: TtfwWord read Get_Boxed; end;//ItfwWordBox TtfwWordBox = class(Tl3CProtoObject, ItfwWordBox) private f_Boxed: TtfwWord; protected function Get_Boxed: TtfwWord; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aWord: TtfwWord); reintroduce; class function Make(aWord: TtfwWord): ItfwWordBox; reintroduce; end;//TtfwWordBox {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwClassLike , TypInfo , tfwDictionary , tfwPropertyLike , tfwTypeInfo , tfwAxiomaticsResNameGetter , seWordsInfo , tfwMembersIterator , kwForwardDeclaration , tfwCodeIterator , kwCompiledWordPrim , kwCompiledWordContainer , kwDualCompiledWordContainer , kwRuntimeWordWithCode , kwForwardDeclarationHolder , kwCompiledWordWorker , tfwWordRefList , tfwScriptEngineExInterfaces , kwCompiledWordWorkerWordRunner , kwCompiledWordWorkerWord , kwCompiledIfElse , SysUtils , tfwWordBoxPack , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *550C25D70182impl_uses* //#UC END# *550C25D70182impl_uses* ; type TkwPopWordGetLeftWordRefValue = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:GetLeftWordRefValue } private function GetLeftWordRefValue(const aCtx: TtfwContext; aWord: TtfwWord; anIndex: Integer): TtfwWord; {* Реализация слова скрипта pop:Word:GetLeftWordRefValue } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordGetLeftWordRefValue TkwPopWordGetParam = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:GetParam } private function GetParam(const aCtx: TtfwContext; aWord: TtfwWord; anIndex: Integer): TtfwWord; {* Реализация слова скрипта pop:Word:GetParam } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordGetParam TkwPopWordSetProducer = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:SetProducer } private procedure SetProducer(const aCtx: TtfwContext; aWord: TtfwWord; aProducer: TtfwWord); {* Реализация слова скрипта pop:Word:SetProducer } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordSetProducer TkwPopWordFindMember = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:FindMember } private function FindMember(const aCtx: TtfwContext; aWord: TtfwWord; const aName: Il3CString): TtfwKeyWord; {* Реализация слова скрипта pop:Word:FindMember } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordFindMember TkwPopWordGetRef = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:GetRef } private function GetRef(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:GetRef } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordGetRef TkwPopWordSourcePointString = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:SourcePointString } private function SourcePointString(const aCtx: TtfwContext; aWord: TtfwWord): AnsiString; {* Реализация слова скрипта pop:Word:SourcePointString } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordSourcePointString TkwPopWordIsVarLike = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:IsVarLike } private function IsVarLike(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsVarLike } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordIsVarLike TkwPopWordIsInParam = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:IsInParam } private function IsInParam(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsInParam } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordIsInParam TkwPopWordSetValue = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:SetValue } private procedure SetValue(const aCtx: TtfwContext; aWord: TtfwWord; const aValue: TtfwStackValue); {* Реализация слова скрипта pop:Word:SetValue } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordSetValue TkwPopWordInfo = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:Info } private function Info(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWordInfo; {* Реализация слова скрипта pop:Word:Info } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordInfo TkwPopWordIsForHelp = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:IsForHelp } private function IsForHelp(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsForHelp } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordIsForHelp TkwPopWordIsImmediate = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:IsImmediate } private function IsImmediate(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsImmediate } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordIsImmediate TkwPopWordIncRef = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:IncRef } private procedure IncRef(const aCtx: TtfwContext; aWord: TtfwWord); {* Реализация слова скрипта pop:Word:IncRef } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordIncRef TkwPopWordDecRef = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:DecRef } private procedure DecRef(const aCtx: TtfwContext; aWord: TtfwWord); {* Реализация слова скрипта pop:Word:DecRef } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordDecRef TkwPopWordMembersIterator = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:MembersIterator } private function MembersIterator(const aCtx: TtfwContext; aWord: TtfwWord): ItfwValueList; {* Реализация слова скрипта pop:Word:MembersIterator } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordMembersIterator TkwPopWordInnerDictionary = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:InnerDictionary } private function InnerDictionary(const aCtx: TtfwContext; aWord: TtfwWord): TtfwDictionary; {* Реализация слова скрипта pop:Word:InnerDictionary } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordInnerDictionary TkwPopWordCodeIterator = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:CodeIterator } private function CodeIterator(const aCtx: TtfwContext; aWord: TtfwWord): ItfwValueList; {* Реализация слова скрипта pop:Word:CodeIterator } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordCodeIterator TkwPopWordSetValuePrim = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:SetValuePrim } private procedure SetValuePrim(const aCtx: TtfwContext; aWord: TtfwWord; const aValue: TtfwStackValue); {* Реализация слова скрипта pop:Word:SetValuePrim } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordSetValuePrim TkwPopWordKeyWord = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:KeyWord } private function KeyWord(const aCtx: TtfwContext; aWord: TtfwWord): TtfwKeyWord; {* Реализация слова скрипта pop:Word:KeyWord } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordKeyWord TkwPopWordSetParent = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:SetParent } private procedure SetParent(const aCtx: TtfwContext; aWord: TtfwWord; aParent: TtfwWord); {* Реализация слова скрипта pop:Word:SetParent } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordSetParent TkwPopWordSetKey = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:SetKey } private procedure SetKey(const aCtx: TtfwContext; aWord: TtfwWord; aKey: TtfwKeyWord); {* Реализация слова скрипта pop:Word:SetKey } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordSetKey TkwPopWordBox = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:Box } private function Box(const aCtx: TtfwContext; aWord: TtfwWord): ItfwWordBox; {* Реализация слова скрипта pop:Word:Box } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordBox TkwPopWordGetRefForCompare = {final} class(TtfwClassLike) {* Слово скрипта pop:Word:GetRefForCompare } private function GetRefForCompare(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:GetRefForCompare } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwPopWordGetRefForCompare TkwPopWordDirectives = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:Directives } private function Directives(const aCtx: TtfwContext; aWord: TtfwWord): Il3CString; {* Реализация слова скрипта pop:Word:Directives } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordDirectives TkwPopWordEndBracket = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:EndBracket } private function EndBracket(const aCtx: TtfwContext; aWord: TtfwWord): AnsiString; {* Реализация слова скрипта pop:Word:EndBracket } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordEndBracket TkwPopWordLeftWordRefValuesCount = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:LeftWordRefValuesCount } private function LeftWordRefValuesCount(const aCtx: TtfwContext; aWord: TtfwWord): Integer; {* Реализация слова скрипта pop:Word:LeftWordRefValuesCount } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordLeftWordRefValuesCount TkwPopWordName = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:Name } private function Name(const aCtx: TtfwContext; aWord: TtfwWord): Il3CString; {* Реализация слова скрипта pop:Word:Name } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordName TkwPopWordParent = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:Parent } private function Parent(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:Parent } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordParent TkwPopWordProducer = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:Producer } private function Producer(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:Producer } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordProducer TkwPopWordRedefines = {final} class(TtfwPropertyLike) {* Слово скрипта pop:Word:Redefines } private function Redefines(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:Redefines } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwPopWordRedefines TWordsRTTIPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TWordsRTTIPackResNameGetter constructor TtfwWordBox.Create(aWord: TtfwWord); //#UC START# *567A8DFB0357_567A8DB002B6_var* //#UC END# *567A8DFB0357_567A8DB002B6_var* begin //#UC START# *567A8DFB0357_567A8DB002B6_impl* inherited Create; aWord.SetrefTo(f_Boxed); //#UC END# *567A8DFB0357_567A8DB002B6_impl* end;//TtfwWordBox.Create class function TtfwWordBox.Make(aWord: TtfwWord): ItfwWordBox; var l_Inst : TtfwWordBox; begin l_Inst := Create(aWord); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TtfwWordBox.Make function TtfwWordBox.Get_Boxed: TtfwWord; //#UC START# *567A8D840243_567A8DB002B6get_var* //#UC END# *567A8D840243_567A8DB002B6get_var* begin //#UC START# *567A8D840243_567A8DB002B6get_impl* Result := f_Boxed; //#UC END# *567A8D840243_567A8DB002B6get_impl* end;//TtfwWordBox.Get_Boxed procedure TtfwWordBox.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_567A8DB002B6_var* //#UC END# *479731C50290_567A8DB002B6_var* begin //#UC START# *479731C50290_567A8DB002B6_impl* FreeAndNil(f_Boxed); inherited; //#UC END# *479731C50290_567A8DB002B6_impl* end;//TtfwWordBox.Cleanup function TkwPopWordGetLeftWordRefValue.GetLeftWordRefValue(const aCtx: TtfwContext; aWord: TtfwWord; anIndex: Integer): TtfwWord; {* Реализация слова скрипта pop:Word:GetLeftWordRefValue } //#UC START# *550C278901A4_550C278901A4_4DAEED140007_Word_var* //#UC END# *550C278901A4_550C278901A4_4DAEED140007_Word_var* begin //#UC START# *550C278901A4_550C278901A4_4DAEED140007_Word_impl* Result := aWord.GetLeftWordRefValue(aCtx, anIndex); //#UC END# *550C278901A4_550C278901A4_4DAEED140007_Word_impl* end;//TkwPopWordGetLeftWordRefValue.GetLeftWordRefValue class function TkwPopWordGetLeftWordRefValue.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:GetLeftWordRefValue'; end;//TkwPopWordGetLeftWordRefValue.GetWordNameForRegister function TkwPopWordGetLeftWordRefValue.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordGetLeftWordRefValue.GetResultTypeInfo function TkwPopWordGetLeftWordRefValue.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordGetLeftWordRefValue.GetAllParamsCount function TkwPopWordGetLeftWordRefValue.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), TypeInfo(Integer)]); end;//TkwPopWordGetLeftWordRefValue.ParamsTypes procedure TkwPopWordGetLeftWordRefValue.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_anIndex: Integer; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetLeftWordRefValue(aCtx, l_aWord, l_anIndex)); end;//TkwPopWordGetLeftWordRefValue.DoDoIt function TkwPopWordGetParam.GetParam(const aCtx: TtfwContext; aWord: TtfwWord; anIndex: Integer): TtfwWord; {* Реализация слова скрипта pop:Word:GetParam } //#UC START# *550C27BB0382_550C27BB0382_4DAEED140007_Word_var* //#UC END# *550C27BB0382_550C27BB0382_4DAEED140007_Word_var* begin //#UC START# *550C27BB0382_550C27BB0382_4DAEED140007_Word_impl* Result := aWord.GetInParam(aCtx, anIndex); //#UC END# *550C27BB0382_550C27BB0382_4DAEED140007_Word_impl* end;//TkwPopWordGetParam.GetParam class function TkwPopWordGetParam.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:GetParam'; end;//TkwPopWordGetParam.GetWordNameForRegister function TkwPopWordGetParam.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordGetParam.GetResultTypeInfo function TkwPopWordGetParam.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordGetParam.GetAllParamsCount function TkwPopWordGetParam.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), TypeInfo(Integer)]); end;//TkwPopWordGetParam.ParamsTypes procedure TkwPopWordGetParam.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_anIndex: Integer; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anIndex := aCtx.rEngine.PopInt; except on E: Exception do begin RunnerError('Ошибка при получении параметра anIndex: Integer : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetParam(aCtx, l_aWord, l_anIndex)); end;//TkwPopWordGetParam.DoDoIt procedure TkwPopWordSetProducer.SetProducer(const aCtx: TtfwContext; aWord: TtfwWord; aProducer: TtfwWord); {* Реализация слова скрипта pop:Word:SetProducer } //#UC START# *558ABFC70287_558ABFC70287_4DAEED140007_Word_var* //#UC END# *558ABFC70287_558ABFC70287_4DAEED140007_Word_var* begin //#UC START# *558ABFC70287_558ABFC70287_4DAEED140007_Word_impl* aWord.WordProducer := aProducer; //#UC END# *558ABFC70287_558ABFC70287_4DAEED140007_Word_impl* end;//TkwPopWordSetProducer.SetProducer class function TkwPopWordSetProducer.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:SetProducer'; end;//TkwPopWordSetProducer.GetWordNameForRegister function TkwPopWordSetProducer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordSetProducer.GetResultTypeInfo function TkwPopWordSetProducer.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordSetProducer.GetAllParamsCount function TkwPopWordSetProducer.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), TypeInfo(TtfwWord)]); end;//TkwPopWordSetProducer.ParamsTypes procedure TkwPopWordSetProducer.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_aProducer: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aProducer := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aProducer: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetProducer(aCtx, l_aWord, l_aProducer); end;//TkwPopWordSetProducer.DoDoIt function TkwPopWordFindMember.FindMember(const aCtx: TtfwContext; aWord: TtfwWord; const aName: Il3CString): TtfwKeyWord; {* Реализация слова скрипта pop:Word:FindMember } //#UC START# *558D53EF03DB_558D53EF03DB_4DAEED140007_Word_var* //#UC END# *558D53EF03DB_558D53EF03DB_4DAEED140007_Word_var* begin //#UC START# *558D53EF03DB_558D53EF03DB_4DAEED140007_Word_impl* if (aWord = nil) then Result := nil else if (aWord.InnerDictionary <> nil) then Result := (aWord.InnerDictionary As TtfwDictionary).DRbyCName[aName] else Result := nil; //#UC END# *558D53EF03DB_558D53EF03DB_4DAEED140007_Word_impl* end;//TkwPopWordFindMember.FindMember class function TkwPopWordFindMember.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:FindMember'; end;//TkwPopWordFindMember.GetWordNameForRegister function TkwPopWordFindMember.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwKeyWord); end;//TkwPopWordFindMember.GetResultTypeInfo function TkwPopWordFindMember.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordFindMember.GetAllParamsCount function TkwPopWordFindMember.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), @tfw_tiString]); end;//TkwPopWordFindMember.ParamsTypes procedure TkwPopWordFindMember.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_aName: Il3CString; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aName := Il3CString(aCtx.rEngine.PopString); except on E: Exception do begin RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(FindMember(aCtx, l_aWord, l_aName)); end;//TkwPopWordFindMember.DoDoIt function TkwPopWordGetRef.GetRef(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:GetRef } //#UC START# *558D76DE02E9_558D76DE02E9_4DAEED140007_Word_var* //#UC END# *558D76DE02E9_558D76DE02E9_4DAEED140007_Word_var* begin //#UC START# *558D76DE02E9_558D76DE02E9_4DAEED140007_Word_impl* Result := aWord.GetRef(aCtx); //#UC END# *558D76DE02E9_558D76DE02E9_4DAEED140007_Word_impl* end;//TkwPopWordGetRef.GetRef class function TkwPopWordGetRef.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:GetRef'; end;//TkwPopWordGetRef.GetWordNameForRegister function TkwPopWordGetRef.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordGetRef.GetResultTypeInfo function TkwPopWordGetRef.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordGetRef.GetAllParamsCount function TkwPopWordGetRef.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordGetRef.ParamsTypes procedure TkwPopWordGetRef.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetRef(aCtx, l_aWord)); end;//TkwPopWordGetRef.DoDoIt function TkwPopWordSourcePointString.SourcePointString(const aCtx: TtfwContext; aWord: TtfwWord): AnsiString; {* Реализация слова скрипта pop:Word:SourcePointString } //#UC START# *559BDE5C03AB_559BDE5C03AB_4DAEED140007_Word_var* //#UC END# *559BDE5C03AB_559BDE5C03AB_4DAEED140007_Word_var* begin //#UC START# *559BDE5C03AB_559BDE5C03AB_4DAEED140007_Word_impl* Result := aWord.SourcePoint.ToString; //#UC END# *559BDE5C03AB_559BDE5C03AB_4DAEED140007_Word_impl* end;//TkwPopWordSourcePointString.SourcePointString class function TkwPopWordSourcePointString.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:SourcePointString'; end;//TkwPopWordSourcePointString.GetWordNameForRegister function TkwPopWordSourcePointString.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopWordSourcePointString.GetResultTypeInfo function TkwPopWordSourcePointString.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordSourcePointString.GetAllParamsCount function TkwPopWordSourcePointString.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordSourcePointString.ParamsTypes procedure TkwPopWordSourcePointString.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(SourcePointString(aCtx, l_aWord)); end;//TkwPopWordSourcePointString.DoDoIt function TkwPopWordIsVarLike.IsVarLike(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsVarLike } //#UC START# *559D45FC0043_559D45FC0043_4DAEED140007_Word_var* //#UC END# *559D45FC0043_559D45FC0043_4DAEED140007_Word_var* begin //#UC START# *559D45FC0043_559D45FC0043_4DAEED140007_Word_impl* Result := aWord.IsVarLike; //#UC END# *559D45FC0043_559D45FC0043_4DAEED140007_Word_impl* end;//TkwPopWordIsVarLike.IsVarLike class function TkwPopWordIsVarLike.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:IsVarLike'; end;//TkwPopWordIsVarLike.GetWordNameForRegister function TkwPopWordIsVarLike.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopWordIsVarLike.GetResultTypeInfo function TkwPopWordIsVarLike.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordIsVarLike.GetAllParamsCount function TkwPopWordIsVarLike.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordIsVarLike.ParamsTypes procedure TkwPopWordIsVarLike.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsVarLike(aCtx, l_aWord)); end;//TkwPopWordIsVarLike.DoDoIt function TkwPopWordIsInParam.IsInParam(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsInParam } //#UC START# *559D46110368_559D46110368_4DAEED140007_Word_var* //#UC END# *559D46110368_559D46110368_4DAEED140007_Word_var* begin //#UC START# *559D46110368_559D46110368_4DAEED140007_Word_impl* Result := aWord.IsInParam; //#UC END# *559D46110368_559D46110368_4DAEED140007_Word_impl* end;//TkwPopWordIsInParam.IsInParam class function TkwPopWordIsInParam.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:IsInParam'; end;//TkwPopWordIsInParam.GetWordNameForRegister function TkwPopWordIsInParam.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopWordIsInParam.GetResultTypeInfo function TkwPopWordIsInParam.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordIsInParam.GetAllParamsCount function TkwPopWordIsInParam.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordIsInParam.ParamsTypes procedure TkwPopWordIsInParam.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsInParam(aCtx, l_aWord)); end;//TkwPopWordIsInParam.DoDoIt procedure TkwPopWordSetValue.SetValue(const aCtx: TtfwContext; aWord: TtfwWord; const aValue: TtfwStackValue); {* Реализация слова скрипта pop:Word:SetValue } //#UC START# *55C2043A0132_55C2043A0132_4DAEED140007_Word_var* //#UC END# *55C2043A0132_55C2043A0132_4DAEED140007_Word_var* begin //#UC START# *55C2043A0132_55C2043A0132_4DAEED140007_Word_impl* aWord.SetValue(aValue, aCtx); //#UC END# *55C2043A0132_55C2043A0132_4DAEED140007_Word_impl* end;//TkwPopWordSetValue.SetValue class function TkwPopWordSetValue.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:SetValue'; end;//TkwPopWordSetValue.GetWordNameForRegister function TkwPopWordSetValue.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordSetValue.GetResultTypeInfo function TkwPopWordSetValue.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordSetValue.GetAllParamsCount function TkwPopWordSetValue.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), @tfw_tiStruct]); end;//TkwPopWordSetValue.ParamsTypes procedure TkwPopWordSetValue.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_aValue: TtfwStackValue; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aValue := aCtx.rEngine.Pop; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetValue(aCtx, l_aWord, l_aValue); end;//TkwPopWordSetValue.DoDoIt function TkwPopWordInfo.Info(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWordInfo; {* Реализация слова скрипта pop:Word:Info } //#UC START# *55C385720214_55C385720214_4DAEED140007_Word_var* //#UC END# *55C385720214_55C385720214_4DAEED140007_Word_var* begin //#UC START# *55C385720214_55C385720214_4DAEED140007_Word_impl* Result := aWord.ResultTypeInfo[aCtx]; //#UC END# *55C385720214_55C385720214_4DAEED140007_Word_impl* end;//TkwPopWordInfo.Info class function TkwPopWordInfo.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Info'; end;//TkwPopWordInfo.GetWordNameForRegister function TkwPopWordInfo.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWordInfo); end;//TkwPopWordInfo.GetResultTypeInfo function TkwPopWordInfo.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordInfo.GetAllParamsCount function TkwPopWordInfo.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordInfo.ParamsTypes procedure TkwPopWordInfo.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Info(aCtx, l_aWord)); end;//TkwPopWordInfo.DoDoIt function TkwPopWordIsForHelp.IsForHelp(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsForHelp } begin Result := aWord.IsForHelp; end;//TkwPopWordIsForHelp.IsForHelp class function TkwPopWordIsForHelp.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:IsForHelp'; end;//TkwPopWordIsForHelp.GetWordNameForRegister function TkwPopWordIsForHelp.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopWordIsForHelp.GetResultTypeInfo function TkwPopWordIsForHelp.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordIsForHelp.GetAllParamsCount function TkwPopWordIsForHelp.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordIsForHelp.ParamsTypes procedure TkwPopWordIsForHelp.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsForHelp(aCtx, l_aWord)); end;//TkwPopWordIsForHelp.DoDoIt function TkwPopWordIsImmediate.IsImmediate(const aCtx: TtfwContext; aWord: TtfwWord): Boolean; {* Реализация слова скрипта pop:Word:IsImmediate } //#UC START# *55CDED9E02BF_55CDED9E02BF_4DAEED140007_Word_var* //#UC END# *55CDED9E02BF_55CDED9E02BF_4DAEED140007_Word_var* begin //#UC START# *55CDED9E02BF_55CDED9E02BF_4DAEED140007_Word_impl* Result := aWord.IsImmediate(aCtx); //#UC END# *55CDED9E02BF_55CDED9E02BF_4DAEED140007_Word_impl* end;//TkwPopWordIsImmediate.IsImmediate class function TkwPopWordIsImmediate.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:IsImmediate'; end;//TkwPopWordIsImmediate.GetWordNameForRegister function TkwPopWordIsImmediate.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwPopWordIsImmediate.GetResultTypeInfo function TkwPopWordIsImmediate.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordIsImmediate.GetAllParamsCount function TkwPopWordIsImmediate.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordIsImmediate.ParamsTypes procedure TkwPopWordIsImmediate.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsImmediate(aCtx, l_aWord)); end;//TkwPopWordIsImmediate.DoDoIt procedure TkwPopWordIncRef.IncRef(const aCtx: TtfwContext; aWord: TtfwWord); {* Реализация слова скрипта pop:Word:IncRef } //#UC START# *55E08D220146_55E08D220146_4DAEED140007_Word_var* //#UC END# *55E08D220146_55E08D220146_4DAEED140007_Word_var* begin //#UC START# *55E08D220146_55E08D220146_4DAEED140007_Word_impl* aWord.Use; //#UC END# *55E08D220146_55E08D220146_4DAEED140007_Word_impl* end;//TkwPopWordIncRef.IncRef class function TkwPopWordIncRef.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:IncRef'; end;//TkwPopWordIncRef.GetWordNameForRegister function TkwPopWordIncRef.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordIncRef.GetResultTypeInfo function TkwPopWordIncRef.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordIncRef.GetAllParamsCount function TkwPopWordIncRef.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordIncRef.ParamsTypes procedure TkwPopWordIncRef.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except IncRef(aCtx, l_aWord); end;//TkwPopWordIncRef.DoDoIt procedure TkwPopWordDecRef.DecRef(const aCtx: TtfwContext; aWord: TtfwWord); {* Реализация слова скрипта pop:Word:DecRef } //#UC START# *55E08D570094_55E08D570094_4DAEED140007_Word_var* //#UC END# *55E08D570094_55E08D570094_4DAEED140007_Word_var* begin //#UC START# *55E08D570094_55E08D570094_4DAEED140007_Word_impl* aWord.Free; //#UC END# *55E08D570094_55E08D570094_4DAEED140007_Word_impl* end;//TkwPopWordDecRef.DecRef class function TkwPopWordDecRef.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:DecRef'; end;//TkwPopWordDecRef.GetWordNameForRegister function TkwPopWordDecRef.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordDecRef.GetResultTypeInfo function TkwPopWordDecRef.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordDecRef.GetAllParamsCount function TkwPopWordDecRef.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordDecRef.ParamsTypes procedure TkwPopWordDecRef.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except DecRef(aCtx, l_aWord); end;//TkwPopWordDecRef.DoDoIt function TkwPopWordMembersIterator.MembersIterator(const aCtx: TtfwContext; aWord: TtfwWord): ItfwValueList; {* Реализация слова скрипта pop:Word:MembersIterator } //#UC START# *55E708220353_55E708220353_4DAEED140007_Word_var* //#UC END# *55E708220353_55E708220353_4DAEED140007_Word_var* begin //#UC START# *55E708220353_55E708220353_4DAEED140007_Word_impl* if (aWord = nil) then Result := TtfwMembersIterator.Make(nil) else if (aWord Is TkwForwardDeclaration) then Result := TtfwMembersIterator.Make(TkwForwardDeclaration(aWord).RealWord.InnerDictionary) else Result := TtfwMembersIterator.Make(aWord.InnerDictionary); //#UC END# *55E708220353_55E708220353_4DAEED140007_Word_impl* end;//TkwPopWordMembersIterator.MembersIterator class function TkwPopWordMembersIterator.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:MembersIterator'; end;//TkwPopWordMembersIterator.GetWordNameForRegister function TkwPopWordMembersIterator.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(ItfwValueList); end;//TkwPopWordMembersIterator.GetResultTypeInfo function TkwPopWordMembersIterator.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordMembersIterator.GetAllParamsCount function TkwPopWordMembersIterator.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordMembersIterator.ParamsTypes procedure TkwPopWordMembersIterator.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushList(MembersIterator(aCtx, l_aWord)); end;//TkwPopWordMembersIterator.DoDoIt function TkwPopWordInnerDictionary.InnerDictionary(const aCtx: TtfwContext; aWord: TtfwWord): TtfwDictionary; {* Реализация слова скрипта pop:Word:InnerDictionary } //#UC START# *55E727A202B7_55E727A202B7_4DAEED140007_Word_var* //#UC END# *55E727A202B7_55E727A202B7_4DAEED140007_Word_var* begin //#UC START# *55E727A202B7_55E727A202B7_4DAEED140007_Word_impl* Result := aWord.InnerDictionary As TtfwDictionary; //#UC END# *55E727A202B7_55E727A202B7_4DAEED140007_Word_impl* end;//TkwPopWordInnerDictionary.InnerDictionary class function TkwPopWordInnerDictionary.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:InnerDictionary'; end;//TkwPopWordInnerDictionary.GetWordNameForRegister function TkwPopWordInnerDictionary.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwDictionary); end;//TkwPopWordInnerDictionary.GetResultTypeInfo function TkwPopWordInnerDictionary.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordInnerDictionary.GetAllParamsCount function TkwPopWordInnerDictionary.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordInnerDictionary.ParamsTypes procedure TkwPopWordInnerDictionary.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(InnerDictionary(aCtx, l_aWord)); end;//TkwPopWordInnerDictionary.DoDoIt function TkwPopWordCodeIterator.CodeIterator(const aCtx: TtfwContext; aWord: TtfwWord): ItfwValueList; {* Реализация слова скрипта pop:Word:CodeIterator } //#UC START# *55E8430C020E_55E8430C020E_4DAEED140007_Word_var* function DoWord(aWord : TtfwWord) : ItfwValueList; var l_List : TtfwWordRefList; l_RightParamsCount : Integer; l_Index : Integer; begin//DoWord if (aWord Is TkwForwardDeclaration) then Result := DoWord(TkwForwardDeclaration(aWord).RealWord) else if (aWord is TkwCompiledWordWorkerWord) then Result := DoWord(TkwCompiledWordWorkerWord(aWord).Compiled) else if (aWord is TkwForwardDeclarationHolder) then begin l_List := TtfwWordRefList.Create; try l_List.Add(TkwForwardDeclarationHolder(aWord).Holded); Result := TtfwCodeIterator.Make(l_List); finally FreeAndNil(l_List); end;//try..finally end//aWord is TkwForwardDeclarationHolder else if (aWord is TkwCompiledIfElse) then begin l_List := TtfwWordRefList.Create; try l_List.Add(TkwCompiledIfElse(aWord).Condition); l_List.Add(TkwCompiledIfElse(aWord).WordToWork); if (TkwCompiledIfElse(aWord).ElseBranch <> nil) then l_List.Add(TkwCompiledIfElse(aWord).ElseBranch); Result := TtfwCodeIterator.Make(l_List); finally FreeAndNil(l_List); end;//try..finally end//aWord is TkwCompiledIfElse else if (aWord is TkwDualCompiledWordContainer) then begin l_List := TtfwWordRefList.Create; try l_List.Add(TkwDualCompiledWordContainer(aWord).WordToWork); if (TkwDualCompiledWordContainer(aWord).ElseBranch <> nil) then l_List.Add(TkwDualCompiledWordContainer(aWord).ElseBranch); Result := TtfwCodeIterator.Make(l_List); finally FreeAndNil(l_List); end;//try..finally end//aWord is TkwDualCompiledWordContainer else if (aWord is TkwCompiledWordContainer) then begin l_List := TtfwWordRefList.Create; try l_List.Add(TkwCompiledWordContainer(aWord).WordToWork); Result := TtfwCodeIterator.Make(l_List); finally FreeAndNil(l_List); end;//try..finally end//aWord is TkwCompiledWordContainer else if (aWord is TkwCompiledWordWorkerWordRunner) then begin l_List := TtfwWordRefList.Create; try l_RightParamsCount := TkwCompiledWordWorkerWordRunner(aWord).WordToRun.RightParamsCount(aCtx); if (l_RightParamsCount = 1) then l_List.Add(TkwCompiledWordWorkerWordRunner(aWord).WordToWork) else begin for l_Index := 0 to Pred(l_RightParamsCount) do l_List.Add((TkwCompiledWordWorkerWordRunner(aWord).WordToWork As TkwRuntimeWordWithCode).Code[l_Index]); end;//l_RightParamsCount = 1 Result := TtfwCodeIterator.Make(l_List); finally FreeAndNil(l_List); end;//try..finally end//aWord is TkwCompiledWordWorkerWordRunner else if (aWord is TkwCompiledWordWorker) then begin l_List := TtfwWordRefList.Create; try l_List.Add(TkwCompiledWordWorker(aWord).WordToWork); Result := TtfwCodeIterator.Make(l_List); finally FreeAndNil(l_List); end;//try..finally end//aWord is TkwCompiledWordWorker else if (aWord = nil) OR not (aWord Is TkwRuntimeWordWithCode) then Result := TtfwCodeIterator.Make(nil) else Result := TtfwCodeIterator.Make(TkwCompiledWordPrim(aWord).GetCode(aCtx)); end;//DoWord //#UC END# *55E8430C020E_55E8430C020E_4DAEED140007_Word_var* begin //#UC START# *55E8430C020E_55E8430C020E_4DAEED140007_Word_impl* Result := DoWord(aWord); //#UC END# *55E8430C020E_55E8430C020E_4DAEED140007_Word_impl* end;//TkwPopWordCodeIterator.CodeIterator class function TkwPopWordCodeIterator.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:CodeIterator'; end;//TkwPopWordCodeIterator.GetWordNameForRegister function TkwPopWordCodeIterator.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(ItfwValueList); end;//TkwPopWordCodeIterator.GetResultTypeInfo function TkwPopWordCodeIterator.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordCodeIterator.GetAllParamsCount function TkwPopWordCodeIterator.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordCodeIterator.ParamsTypes procedure TkwPopWordCodeIterator.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushList(CodeIterator(aCtx, l_aWord)); end;//TkwPopWordCodeIterator.DoDoIt procedure TkwPopWordSetValuePrim.SetValuePrim(const aCtx: TtfwContext; aWord: TtfwWord; const aValue: TtfwStackValue); {* Реализация слова скрипта pop:Word:SetValuePrim } //#UC START# *5609675401ED_5609675401ED_4DAEED140007_Word_var* //#UC END# *5609675401ED_5609675401ED_4DAEED140007_Word_var* begin //#UC START# *5609675401ED_5609675401ED_4DAEED140007_Word_impl* aWord.SetValuePrim(aValue, aCtx); //#UC END# *5609675401ED_5609675401ED_4DAEED140007_Word_impl* end;//TkwPopWordSetValuePrim.SetValuePrim class function TkwPopWordSetValuePrim.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:SetValuePrim'; end;//TkwPopWordSetValuePrim.GetWordNameForRegister function TkwPopWordSetValuePrim.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordSetValuePrim.GetResultTypeInfo function TkwPopWordSetValuePrim.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordSetValuePrim.GetAllParamsCount function TkwPopWordSetValuePrim.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), @tfw_tiStruct]); end;//TkwPopWordSetValuePrim.ParamsTypes procedure TkwPopWordSetValuePrim.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_aValue: TtfwStackValue; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aValue := aCtx.rEngine.Pop; except on E: Exception do begin RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetValuePrim(aCtx, l_aWord, l_aValue); end;//TkwPopWordSetValuePrim.DoDoIt function TkwPopWordKeyWord.KeyWord(const aCtx: TtfwContext; aWord: TtfwWord): TtfwKeyWord; {* Реализация слова скрипта pop:Word:KeyWord } //#UC START# *5613CB150380_5613CB150380_4DAEED140007_Word_var* //#UC END# *5613CB150380_5613CB150380_4DAEED140007_Word_var* begin //#UC START# *5613CB150380_5613CB150380_4DAEED140007_Word_impl* if (aWord = nil) then Result := nil else Result := aWord.Key As TtfwKeyWord; //#UC END# *5613CB150380_5613CB150380_4DAEED140007_Word_impl* end;//TkwPopWordKeyWord.KeyWord class function TkwPopWordKeyWord.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:KeyWord'; end;//TkwPopWordKeyWord.GetWordNameForRegister function TkwPopWordKeyWord.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwKeyWord); end;//TkwPopWordKeyWord.GetResultTypeInfo function TkwPopWordKeyWord.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordKeyWord.GetAllParamsCount function TkwPopWordKeyWord.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordKeyWord.ParamsTypes procedure TkwPopWordKeyWord.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(KeyWord(aCtx, l_aWord)); end;//TkwPopWordKeyWord.DoDoIt procedure TkwPopWordSetParent.SetParent(const aCtx: TtfwContext; aWord: TtfwWord; aParent: TtfwWord); {* Реализация слова скрипта pop:Word:SetParent } //#UC START# *5673E6BA0364_5673E6BA0364_4DAEED140007_Word_var* //#UC END# *5673E6BA0364_5673E6BA0364_4DAEED140007_Word_var* begin //#UC START# *5673E6BA0364_5673E6BA0364_4DAEED140007_Word_impl* aWord.SetParent(aParent); //#UC END# *5673E6BA0364_5673E6BA0364_4DAEED140007_Word_impl* end;//TkwPopWordSetParent.SetParent class function TkwPopWordSetParent.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:SetParent'; end;//TkwPopWordSetParent.GetWordNameForRegister function TkwPopWordSetParent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordSetParent.GetResultTypeInfo function TkwPopWordSetParent.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordSetParent.GetAllParamsCount function TkwPopWordSetParent.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), TypeInfo(TtfwWord)]); end;//TkwPopWordSetParent.ParamsTypes procedure TkwPopWordSetParent.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_aParent: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aParent := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aParent: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetParent(aCtx, l_aWord, l_aParent); end;//TkwPopWordSetParent.DoDoIt procedure TkwPopWordSetKey.SetKey(const aCtx: TtfwContext; aWord: TtfwWord; aKey: TtfwKeyWord); {* Реализация слова скрипта pop:Word:SetKey } //#UC START# *5673F2E60341_5673F2E60341_4DAEED140007_Word_var* //#UC END# *5673F2E60341_5673F2E60341_4DAEED140007_Word_var* begin //#UC START# *5673F2E60341_5673F2E60341_4DAEED140007_Word_impl* aWord.Key := aKey; //#UC END# *5673F2E60341_5673F2E60341_4DAEED140007_Word_impl* end;//TkwPopWordSetKey.SetKey class function TkwPopWordSetKey.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:SetKey'; end;//TkwPopWordSetKey.GetWordNameForRegister function TkwPopWordSetKey.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwPopWordSetKey.GetResultTypeInfo function TkwPopWordSetKey.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwPopWordSetKey.GetAllParamsCount function TkwPopWordSetKey.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord), TypeInfo(TtfwKeyWord)]); end;//TkwPopWordSetKey.ParamsTypes procedure TkwPopWordSetKey.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; var l_aKey: TtfwKeyWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_aKey := TtfwKeyWord(aCtx.rEngine.PopObjAs(TtfwKeyWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aKey: TtfwKeyWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except SetKey(aCtx, l_aWord, l_aKey); end;//TkwPopWordSetKey.DoDoIt function TkwPopWordBox.Box(const aCtx: TtfwContext; aWord: TtfwWord): ItfwWordBox; {* Реализация слова скрипта pop:Word:Box } //#UC START# *567A8D980275_567A8D980275_4DAEED140007_Word_var* //#UC END# *567A8D980275_567A8D980275_4DAEED140007_Word_var* begin //#UC START# *567A8D980275_567A8D980275_4DAEED140007_Word_impl* Result := TtfwWordBox.Make(aWord); //#UC END# *567A8D980275_567A8D980275_4DAEED140007_Word_impl* end;//TkwPopWordBox.Box class function TkwPopWordBox.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Box'; end;//TkwPopWordBox.GetWordNameForRegister function TkwPopWordBox.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(ItfwWordBox); end;//TkwPopWordBox.GetResultTypeInfo function TkwPopWordBox.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordBox.GetAllParamsCount function TkwPopWordBox.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordBox.ParamsTypes procedure TkwPopWordBox.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushIntf(Box(aCtx, l_aWord), TypeInfo(ItfwWordBox)); end;//TkwPopWordBox.DoDoIt function TkwPopWordGetRefForCompare.GetRefForCompare(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:GetRefForCompare } //#UC START# *57500AC802FC_57500AC802FC_4DAEED140007_Word_var* //#UC END# *57500AC802FC_57500AC802FC_4DAEED140007_Word_var* begin //#UC START# *57500AC802FC_57500AC802FC_4DAEED140007_Word_impl* Result := aWord.GetRefForCompare; //#UC END# *57500AC802FC_57500AC802FC_4DAEED140007_Word_impl* end;//TkwPopWordGetRefForCompare.GetRefForCompare class function TkwPopWordGetRefForCompare.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:GetRefForCompare'; end;//TkwPopWordGetRefForCompare.GetWordNameForRegister function TkwPopWordGetRefForCompare.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordGetRefForCompare.GetResultTypeInfo function TkwPopWordGetRefForCompare.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordGetRefForCompare.GetAllParamsCount function TkwPopWordGetRefForCompare.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordGetRefForCompare.ParamsTypes procedure TkwPopWordGetRefForCompare.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(GetRefForCompare(aCtx, l_aWord)); end;//TkwPopWordGetRefForCompare.DoDoIt function TkwPopWordDirectives.Directives(const aCtx: TtfwContext; aWord: TtfwWord): Il3CString; {* Реализация слова скрипта pop:Word:Directives } //#UC START# *550C26A10073_550C26A10073_4DAEED140007_Word_var* //#UC END# *550C26A10073_550C26A10073_4DAEED140007_Word_var* begin //#UC START# *550C26A10073_550C26A10073_4DAEED140007_Word_impl* Result := GetWordDirectives(aCtx, aWord); //#UC END# *550C26A10073_550C26A10073_4DAEED140007_Word_impl* end;//TkwPopWordDirectives.Directives class function TkwPopWordDirectives.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Directives'; end;//TkwPopWordDirectives.GetWordNameForRegister function TkwPopWordDirectives.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopWordDirectives.GetResultTypeInfo function TkwPopWordDirectives.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordDirectives.GetAllParamsCount function TkwPopWordDirectives.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordDirectives.ParamsTypes procedure TkwPopWordDirectives.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Directives', aCtx); end;//TkwPopWordDirectives.SetValuePrim procedure TkwPopWordDirectives.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(Directives(aCtx, l_aWord)); end;//TkwPopWordDirectives.DoDoIt function TkwPopWordEndBracket.EndBracket(const aCtx: TtfwContext; aWord: TtfwWord): AnsiString; {* Реализация слова скрипта pop:Word:EndBracket } //#UC START# *550C274E00CA_550C274E00CA_4DAEED140007_Word_var* var l_B : RtfwWord; //#UC END# *550C274E00CA_550C274E00CA_4DAEED140007_Word_var* begin //#UC START# *550C274E00CA_550C274E00CA_4DAEED140007_Word_impl* try if (aWord = nil) then l_B := nil else l_B := aWord.GetEndBracket(aCtx, true); except l_B := nil; end;//try..except if (l_B = nil) then Result := '' else Result := aCtx.rEngine.KeywordByName(TtfwCStringFactory.C(l_B.NameForRegister)).AsString; //#UC END# *550C274E00CA_550C274E00CA_4DAEED140007_Word_impl* end;//TkwPopWordEndBracket.EndBracket class function TkwPopWordEndBracket.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:EndBracket'; end;//TkwPopWordEndBracket.GetWordNameForRegister function TkwPopWordEndBracket.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopWordEndBracket.GetResultTypeInfo function TkwPopWordEndBracket.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordEndBracket.GetAllParamsCount function TkwPopWordEndBracket.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordEndBracket.ParamsTypes procedure TkwPopWordEndBracket.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству EndBracket', aCtx); end;//TkwPopWordEndBracket.SetValuePrim procedure TkwPopWordEndBracket.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(EndBracket(aCtx, l_aWord)); end;//TkwPopWordEndBracket.DoDoIt function TkwPopWordLeftWordRefValuesCount.LeftWordRefValuesCount(const aCtx: TtfwContext; aWord: TtfwWord): Integer; {* Реализация слова скрипта pop:Word:LeftWordRefValuesCount } //#UC START# *550C27EA0141_550C27EA0141_4DAEED140007_Word_var* //#UC END# *550C27EA0141_550C27EA0141_4DAEED140007_Word_var* begin //#UC START# *550C27EA0141_550C27EA0141_4DAEED140007_Word_impl* Result := aWord.LeftWordRefValuesCount(aCtx); //#UC END# *550C27EA0141_550C27EA0141_4DAEED140007_Word_impl* end;//TkwPopWordLeftWordRefValuesCount.LeftWordRefValuesCount class function TkwPopWordLeftWordRefValuesCount.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:LeftWordRefValuesCount'; end;//TkwPopWordLeftWordRefValuesCount.GetWordNameForRegister function TkwPopWordLeftWordRefValuesCount.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Integer); end;//TkwPopWordLeftWordRefValuesCount.GetResultTypeInfo function TkwPopWordLeftWordRefValuesCount.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordLeftWordRefValuesCount.GetAllParamsCount function TkwPopWordLeftWordRefValuesCount.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordLeftWordRefValuesCount.ParamsTypes procedure TkwPopWordLeftWordRefValuesCount.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству LeftWordRefValuesCount', aCtx); end;//TkwPopWordLeftWordRefValuesCount.SetValuePrim procedure TkwPopWordLeftWordRefValuesCount.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushInt(LeftWordRefValuesCount(aCtx, l_aWord)); end;//TkwPopWordLeftWordRefValuesCount.DoDoIt function TkwPopWordName.Name(const aCtx: TtfwContext; aWord: TtfwWord): Il3CString; {* Реализация слова скрипта pop:Word:Name } //#UC START# *550C28100270_550C28100270_4DAEED140007_Word_var* //#UC END# *550C28100270_550C28100270_4DAEED140007_Word_var* begin //#UC START# *550C28100270_550C28100270_4DAEED140007_Word_impl* if (aWord = nil) then Result := TtfwCStringFactory.C('??? Unexisting word ???') else Result := aWord.WordName; //#UC END# *550C28100270_550C28100270_4DAEED140007_Word_impl* end;//TkwPopWordName.Name class function TkwPopWordName.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Name'; end;//TkwPopWordName.GetWordNameForRegister function TkwPopWordName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiString; end;//TkwPopWordName.GetResultTypeInfo function TkwPopWordName.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordName.GetAllParamsCount function TkwPopWordName.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordName.ParamsTypes procedure TkwPopWordName.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Name', aCtx); end;//TkwPopWordName.SetValuePrim procedure TkwPopWordName.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushString(Name(aCtx, l_aWord)); end;//TkwPopWordName.DoDoIt function TkwPopWordParent.Parent(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:Parent } //#UC START# *550C283B01A0_550C283B01A0_4DAEED140007_Word_var* //#UC END# *550C283B01A0_550C283B01A0_4DAEED140007_Word_var* begin //#UC START# *550C283B01A0_550C283B01A0_4DAEED140007_Word_impl* Result := aWord.ParentWord; //#UC END# *550C283B01A0_550C283B01A0_4DAEED140007_Word_impl* end;//TkwPopWordParent.Parent class function TkwPopWordParent.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Parent'; end;//TkwPopWordParent.GetWordNameForRegister function TkwPopWordParent.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordParent.GetResultTypeInfo function TkwPopWordParent.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordParent.GetAllParamsCount function TkwPopWordParent.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordParent.ParamsTypes procedure TkwPopWordParent.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Parent', aCtx); end;//TkwPopWordParent.SetValuePrim procedure TkwPopWordParent.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Parent(aCtx, l_aWord)); end;//TkwPopWordParent.DoDoIt function TkwPopWordProducer.Producer(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:Producer } //#UC START# *550C286D0202_550C286D0202_4DAEED140007_Word_var* //#UC END# *550C286D0202_550C286D0202_4DAEED140007_Word_var* begin //#UC START# *550C286D0202_550C286D0202_4DAEED140007_Word_impl* if (aWord = nil) then Result := nil else Result := aWord.WordProducer; //#UC END# *550C286D0202_550C286D0202_4DAEED140007_Word_impl* end;//TkwPopWordProducer.Producer class function TkwPopWordProducer.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Producer'; end;//TkwPopWordProducer.GetWordNameForRegister function TkwPopWordProducer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordProducer.GetResultTypeInfo function TkwPopWordProducer.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordProducer.GetAllParamsCount function TkwPopWordProducer.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordProducer.ParamsTypes procedure TkwPopWordProducer.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Producer', aCtx); end;//TkwPopWordProducer.SetValuePrim procedure TkwPopWordProducer.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Producer(aCtx, l_aWord)); end;//TkwPopWordProducer.DoDoIt function TkwPopWordRedefines.Redefines(const aCtx: TtfwContext; aWord: TtfwWord): TtfwWord; {* Реализация слова скрипта pop:Word:Redefines } begin Result := aWord.Redefines; end;//TkwPopWordRedefines.Redefines class function TkwPopWordRedefines.GetWordNameForRegister: AnsiString; begin Result := 'pop:Word:Redefines'; end;//TkwPopWordRedefines.GetWordNameForRegister function TkwPopWordRedefines.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TtfwWord); end;//TkwPopWordRedefines.GetResultTypeInfo function TkwPopWordRedefines.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwPopWordRedefines.GetAllParamsCount function TkwPopWordRedefines.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TtfwWord)]); end;//TkwPopWordRedefines.ParamsTypes procedure TkwPopWordRedefines.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Redefines', aCtx); end;//TkwPopWordRedefines.SetValuePrim procedure TkwPopWordRedefines.DoDoIt(const aCtx: TtfwContext); var l_aWord: TtfwWord; begin try l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Redefines(aCtx, l_aWord)); end;//TkwPopWordRedefines.DoDoIt class function TWordsRTTIPackResNameGetter.ResName: AnsiString; begin Result := 'WordsRTTIPack'; end;//TWordsRTTIPackResNameGetter.ResName {$R WordsRTTIPack.res} initialization TkwPopWordGetLeftWordRefValue.RegisterInEngine; {* Регистрация pop_Word_GetLeftWordRefValue } TkwPopWordGetParam.RegisterInEngine; {* Регистрация pop_Word_GetParam } TkwPopWordSetProducer.RegisterInEngine; {* Регистрация pop_Word_SetProducer } TkwPopWordFindMember.RegisterInEngine; {* Регистрация pop_Word_FindMember } TkwPopWordGetRef.RegisterInEngine; {* Регистрация pop_Word_GetRef } TkwPopWordSourcePointString.RegisterInEngine; {* Регистрация pop_Word_SourcePointString } TkwPopWordIsVarLike.RegisterInEngine; {* Регистрация pop_Word_IsVarLike } TkwPopWordIsInParam.RegisterInEngine; {* Регистрация pop_Word_IsInParam } TkwPopWordSetValue.RegisterInEngine; {* Регистрация pop_Word_SetValue } TkwPopWordInfo.RegisterInEngine; {* Регистрация pop_Word_Info } TkwPopWordIsForHelp.RegisterInEngine; {* Регистрация pop_Word_IsForHelp } TkwPopWordIsImmediate.RegisterInEngine; {* Регистрация pop_Word_IsImmediate } TkwPopWordIncRef.RegisterInEngine; {* Регистрация pop_Word_IncRef } TkwPopWordDecRef.RegisterInEngine; {* Регистрация pop_Word_DecRef } TkwPopWordMembersIterator.RegisterInEngine; {* Регистрация pop_Word_MembersIterator } TkwPopWordInnerDictionary.RegisterInEngine; {* Регистрация pop_Word_InnerDictionary } TkwPopWordCodeIterator.RegisterInEngine; {* Регистрация pop_Word_CodeIterator } TkwPopWordSetValuePrim.RegisterInEngine; {* Регистрация pop_Word_SetValuePrim } TkwPopWordKeyWord.RegisterInEngine; {* Регистрация pop_Word_KeyWord } TkwPopWordSetParent.RegisterInEngine; {* Регистрация pop_Word_SetParent } TkwPopWordSetKey.RegisterInEngine; {* Регистрация pop_Word_SetKey } TkwPopWordBox.RegisterInEngine; {* Регистрация pop_Word_Box } TkwPopWordGetRefForCompare.RegisterInEngine; {* Регистрация pop_Word_GetRefForCompare } TkwPopWordDirectives.RegisterInEngine; {* Регистрация pop_Word_Directives } TkwPopWordEndBracket.RegisterInEngine; {* Регистрация pop_Word_EndBracket } TkwPopWordLeftWordRefValuesCount.RegisterInEngine; {* Регистрация pop_Word_LeftWordRefValuesCount } TkwPopWordName.RegisterInEngine; {* Регистрация pop_Word_Name } TkwPopWordParent.RegisterInEngine; {* Регистрация pop_Word_Parent } TkwPopWordProducer.RegisterInEngine; {* Регистрация pop_Word_Producer } TkwPopWordRedefines.RegisterInEngine; {* Регистрация pop_Word_Redefines } TWordsRTTIPackResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwWord)); {* Регистрация типа TtfwWord } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeyWord)); {* Регистрация типа TtfwKeyWord } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwWordInfo)); {* Регистрация типа TtfwWordInfo } TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwValueList)); {* Регистрация типа ItfwValueList } TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwDictionary)); {* Регистрация типа TtfwDictionary } TtfwTypeRegistrator.RegisterType(TypeInfo(ItfwWordBox)); {* Регистрация типа ItfwWordBox } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа Il3CString } TtfwTypeRegistrator.RegisterType(TypeInfo(Integer)); {* Регистрация типа Integer } TtfwTypeRegistrator.RegisterType(@tfw_tiStruct); {* Регистрация типа TtfwStackValue } {$IfEnd} // NOT Defined(NoScripts) end.
(* Translate SDL scancodes to PS/2 codeset 2 scancodes.*) UNIT riscps2; INTERFACE USES SDL2; FUNCTION ps2_encode(sdl_scancode: integer; make: boolean; VAR outs : string): integer; IMPLEMENTATION TYPE modety = (K_UNKNOWN, K_NORMAL, K_EXTENDED, K_NUMLOCK_HACK, K_SHIFT_HACK); codety = 0..255; k_infoty = RECORD code: codety; type_: modety; END; keymapty = ARRAY[0..Pred(SDL_NUM_SCANCODES)] of k_infoty; VAR keymap : keymapty; function ps2_encode(sdl_scancode: integer; make: boolean; VAR outs : string): integer; VAR codes : char; info : k_infoty; mod_ : TSDL_KeyMod; BEGIN info := keymap[sdl_scancode]; ps2_encode := 0; outs := ''; codes := chr(info.code); CASE info.type_ OF K_UNKNOWN: BEGIN END; K_NORMAL: BEGIN IF NOT(make) THEN outs := #$F0; outs := outs + codes; END; K_EXTENDED: BEGIN outs := #$E0; IF NOT(make) THEN outs := outs + #$F0; outs := outs + codes; END; K_NUMLOCK_HACK: BEGIN IF (make) THEN BEGIN outs := #$E0 + #$12 +#$E0 + codes; (* fake shift press*) END ELSE BEGIN outs := #$E0 + #$F0 + codes + #$E0 + #$F0 + #$12; (* fake shift release*) END; END; K_SHIFT_HACK: BEGIN mod_ :=SDL_GetModState(); IF make THEN BEGIN (* fake shift release*) IF ((mod_ and KMOD_LSHIFT) > 0) THEN outs := outs + #$E0 + #$F0 + #$12; IF ((mod_ and KMOD_RSHIFT) > 0) THEN outs := outs + #$E0 + #$F0 + #$59; outs := outs + #$E0; outs := outs + codes; END else BEGIN outs := outs + #$E0 + #$F0 + codes; (* fake shift press*) IF ((mod_ and KMOD_RSHIFT) > 0) THEN outs := outs + #$E0 + #$59; IF ((mod_ and KMOD_LSHIFT) > 0) THEN outs := outs + #$E0 + #$12; END; END; END;{case} ps2_encode := length(outs); END; BEGIN keymap[SDL_SCANCODE_A].code:=($1C); keymap[SDL_SCANCODE_B].code:=($32); keymap[SDL_SCANCODE_C].code:=($21); keymap[SDL_SCANCODE_D].code:=($23); keymap[SDL_SCANCODE_E].code:=($24); keymap[SDL_SCANCODE_F].code:=($2B); keymap[SDL_SCANCODE_G].code:=($34); keymap[SDL_SCANCODE_H].code:=($33); keymap[SDL_SCANCODE_I].code:=($43); keymap[SDL_SCANCODE_J].code:=($3B); keymap[SDL_SCANCODE_K].code:=($42); keymap[SDL_SCANCODE_L].code:=($4B); keymap[SDL_SCANCODE_M].code:=($3A); keymap[SDL_SCANCODE_N].code:=($31); keymap[SDL_SCANCODE_O].code:=($44); keymap[SDL_SCANCODE_P].code:=($4D); keymap[SDL_SCANCODE_Q].code:=($15); keymap[SDL_SCANCODE_R].code:=($2D); keymap[SDL_SCANCODE_S].code:=($1B); keymap[SDL_SCANCODE_T].code:=($2C); keymap[SDL_SCANCODE_U].code:=($3C); keymap[SDL_SCANCODE_V].code:=($2A); keymap[SDL_SCANCODE_W].code:=($1D); keymap[SDL_SCANCODE_X].code:=($22); keymap[SDL_SCANCODE_Y].code:=($35); keymap[SDL_SCANCODE_Z].code:=($1A); keymap[SDL_SCANCODE_1].code:=($16); keymap[SDL_SCANCODE_2].code:=($1E); keymap[SDL_SCANCODE_3].code:=($26); keymap[SDL_SCANCODE_4].code:=($25); keymap[SDL_SCANCODE_5].code:=($2E); keymap[SDL_SCANCODE_6].code:=($36); keymap[SDL_SCANCODE_7].code:=($3D); keymap[SDL_SCANCODE_8].code:=($3E); keymap[SDL_SCANCODE_9].code:=($46); keymap[SDL_SCANCODE_0].code:=($45); keymap[SDL_SCANCODE_RETURN].code:= ($5a); keymap[SDL_SCANCODE_ESCAPE].code:= ($76); keymap[SDL_SCANCODE_BACKSPACE].code:=($66); keymap[SDL_SCANCODE_TAB].code:= ($0D); keymap[SDL_SCANCODE_SPACE].code:= ($29); keymap[SDL_SCANCODE_MINUS].code:=($4E); keymap[SDL_SCANCODE_EQUALS].code:=($55); keymap[SDL_SCANCODE_LEFTBRACKET].code:=($54); keymap[SDL_SCANCODE_RIGHTBRACKET].code:=($5B); keymap[SDL_SCANCODE_BACKSLASH].code:=($5D); keymap[SDL_SCANCODE_NONUSHASH].code:=($5D); keymap[SDL_SCANCODE_SEMICOLON].code:=($4C); keymap[SDL_SCANCODE_APOSTROPHE].code:=($52); keymap[SDL_SCANCODE_GRAVE].code:=($0E); keymap[SDL_SCANCODE_COMMA].code:=($41); keymap[SDL_SCANCODE_PERIOD].code:=($49); keymap[SDL_SCANCODE_SLASH].code:=($4A); keymap[SDL_SCANCODE_F1].code:=($05); keymap[SDL_SCANCODE_F2].code:=($06); keymap[SDL_SCANCODE_F3].code:=($04); keymap[SDL_SCANCODE_F4].code:=($0c); keymap[SDL_SCANCODE_F5].code:=($03); keymap[SDL_SCANCODE_F6].code:=($0B); keymap[SDL_SCANCODE_F7].code:=($83); keymap[SDL_SCANCODE_F8].code:=($0A); keymap[SDL_SCANCODE_F9].code:=($01); keymap[SDL_SCANCODE_F10].code:=($09); keymap[SDL_SCANCODE_F11].code:=($78); keymap[SDL_SCANCODE_F12].code:=($07); keymap[SDL_SCANCODE_INSERT].code:=($70); keymap[SDL_SCANCODE_HOME].code:=($6C); keymap[SDL_SCANCODE_PAGEUP].code:=($7D); keymap[SDL_SCANCODE_DELETE].code:=($71); keymap[SDL_SCANCODE_END].code:=($69); keymap[SDL_SCANCODE_PAGEDOWN].code:=($7A); keymap[SDL_SCANCODE_RIGHT].code:=($74); keymap[SDL_SCANCODE_LEFT].code:=($6B); keymap[SDL_SCANCODE_DOWN].code:=($72); keymap[SDL_SCANCODE_UP].code:=($75); keymap[SDL_SCANCODE_KP_DIVIDE].code:=($4A); keymap[SDL_SCANCODE_KP_MULTIPLY].code:=($7C); keymap[SDL_SCANCODE_KP_MINUS].code:=($7B); keymap[SDL_SCANCODE_KP_PLUS].code:=($79); keymap[SDL_SCANCODE_KP_ENTER].code:=($5A); keymap[SDL_SCANCODE_KP_1].code:=($69); keymap[SDL_SCANCODE_KP_2].code:=($72); keymap[SDL_SCANCODE_KP_3].code:=($7A); keymap[SDL_SCANCODE_KP_4].code:=($6B); keymap[SDL_SCANCODE_KP_5].code:=($73); keymap[SDL_SCANCODE_KP_6].code:=($74); keymap[SDL_SCANCODE_KP_7].code:=($6C); keymap[SDL_SCANCODE_KP_8].code:=($75); keymap[SDL_SCANCODE_KP_9].code:=($7D); keymap[SDL_SCANCODE_KP_0].code:=($70); keymap[SDL_SCANCODE_KP_PERIOD].code:=($71); keymap[SDL_SCANCODE_NONUSBACKSLASH].code:=($61); keymap[SDL_SCANCODE_APPLICATION].code:=($2F); keymap[SDL_SCANCODE_LCTRL].code:=($14); keymap[SDL_SCANCODE_LSHIFT].code:=($12); keymap[SDL_SCANCODE_LALT].code:=($11); keymap[SDL_SCANCODE_LGUI].code:=($1F); keymap[SDL_SCANCODE_RCTRL].code:=($14); keymap[SDL_SCANCODE_RSHIFT].code:=($59); keymap[SDL_SCANCODE_RALT].code:=($11); keymap[SDL_SCANCODE_RGUI].code:=($27); keymap[SDL_SCANCODE_A].type_:=(K_NORMAL); keymap[SDL_SCANCODE_B].type_:=(K_NORMAL); keymap[SDL_SCANCODE_C].type_:=(K_NORMAL); keymap[SDL_SCANCODE_D].type_:=(K_NORMAL); keymap[SDL_SCANCODE_E].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F].type_:=(K_NORMAL); keymap[SDL_SCANCODE_G].type_:=(K_NORMAL); keymap[SDL_SCANCODE_H].type_:=(K_NORMAL); keymap[SDL_SCANCODE_I].type_:=(K_NORMAL); keymap[SDL_SCANCODE_J].type_:=(K_NORMAL); keymap[SDL_SCANCODE_K].type_:=(K_NORMAL); keymap[SDL_SCANCODE_L].type_:=(K_NORMAL); keymap[SDL_SCANCODE_M].type_:=(K_NORMAL); keymap[SDL_SCANCODE_N].type_:=(K_NORMAL); keymap[SDL_SCANCODE_O].type_:=(K_NORMAL); keymap[SDL_SCANCODE_P].type_:=(K_NORMAL); keymap[SDL_SCANCODE_Q].type_:=(K_NORMAL); keymap[SDL_SCANCODE_R].type_:=(K_NORMAL); keymap[SDL_SCANCODE_S].type_:=(K_NORMAL); keymap[SDL_SCANCODE_T].type_:=(K_NORMAL); keymap[SDL_SCANCODE_U].type_:=(K_NORMAL); keymap[SDL_SCANCODE_V].type_:=(K_NORMAL); keymap[SDL_SCANCODE_W].type_:=(K_NORMAL); keymap[SDL_SCANCODE_X].type_:=(K_NORMAL); keymap[SDL_SCANCODE_Y].type_:=(K_NORMAL); keymap[SDL_SCANCODE_Z].type_:=(K_NORMAL); keymap[SDL_SCANCODE_1].type_:=(K_NORMAL); keymap[SDL_SCANCODE_2].type_:=(K_NORMAL); keymap[SDL_SCANCODE_3].type_:=(K_NORMAL); keymap[SDL_SCANCODE_4].type_:=(K_NORMAL); keymap[SDL_SCANCODE_5].type_:=(K_NORMAL); keymap[SDL_SCANCODE_6].type_:=(K_NORMAL); keymap[SDL_SCANCODE_7].type_:=(K_NORMAL); keymap[SDL_SCANCODE_8].type_:=(K_NORMAL); keymap[SDL_SCANCODE_9].type_:=(K_NORMAL); keymap[SDL_SCANCODE_0].type_:=(K_NORMAL); keymap[SDL_SCANCODE_RETURN].type_:= (K_NORMAL); keymap[SDL_SCANCODE_ESCAPE].type_:= (K_NORMAL); keymap[SDL_SCANCODE_BACKSPACE].type_:=(K_NORMAL); keymap[SDL_SCANCODE_TAB].type_:= (K_NORMAL); keymap[SDL_SCANCODE_SPACE].type_:= (K_NORMAL); keymap[SDL_SCANCODE_MINUS].type_:=(K_NORMAL); keymap[SDL_SCANCODE_EQUALS].type_:=(K_NORMAL); keymap[SDL_SCANCODE_LEFTBRACKET].type_:=(K_NORMAL); keymap[SDL_SCANCODE_RIGHTBRACKET].type_:=(K_NORMAL); keymap[SDL_SCANCODE_BACKSLASH].type_:=(K_NORMAL); keymap[SDL_SCANCODE_NONUSHASH].type_:=(K_NORMAL); keymap[SDL_SCANCODE_SEMICOLON].type_:=(K_NORMAL); keymap[SDL_SCANCODE_APOSTROPHE].type_:=(K_NORMAL); keymap[SDL_SCANCODE_GRAVE].type_:=(K_NORMAL); keymap[SDL_SCANCODE_COMMA].type_:=(K_NORMAL); keymap[SDL_SCANCODE_PERIOD].type_:=(K_NORMAL); keymap[SDL_SCANCODE_SLASH].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F1].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F2].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F3].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F4].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F5].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F6].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F7].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F8].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F9].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F10].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F11].type_:=(K_NORMAL); keymap[SDL_SCANCODE_F12].type_:=(K_NORMAL); keymap[SDL_SCANCODE_INSERT].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_HOME].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_PAGEUP].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_DELETE].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_END].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_PAGEDOWN].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_RIGHT].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_LEFT].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_DOWN].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_UP].type_:=(K_NUMLOCK_HACK); keymap[SDL_SCANCODE_KP_DIVIDE].type_:=(K_SHIFT_HACK); keymap[SDL_SCANCODE_KP_MULTIPLY].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_MINUS].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_PLUS].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_ENTER].type_:=(K_EXTENDED); keymap[SDL_SCANCODE_KP_1].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_2].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_3].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_4].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_5].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_6].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_7].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_8].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_9].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_0].type_:=(K_NORMAL); keymap[SDL_SCANCODE_KP_PERIOD].type_:=(K_NORMAL); keymap[SDL_SCANCODE_NONUSBACKSLASH].type_:=(K_NORMAL); keymap[SDL_SCANCODE_APPLICATION].type_:=(K_EXTENDED); keymap[SDL_SCANCODE_LCTRL].type_:=(K_NORMAL); keymap[SDL_SCANCODE_LSHIFT].type_:=(K_NORMAL); keymap[SDL_SCANCODE_LALT].type_:=(K_NORMAL); keymap[SDL_SCANCODE_LGUI].type_:=(K_EXTENDED); keymap[SDL_SCANCODE_RCTRL].type_:=(K_EXTENDED); keymap[SDL_SCANCODE_RSHIFT].type_:=(K_NORMAL); keymap[SDL_SCANCODE_RALT].type_:=(K_EXTENDED); keymap[SDL_SCANCODE_RGUI].type_:=(K_EXTENDED); END.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> } unit Unit1; { The objective of this demo is to prove dbugsrv is thread-safe } { Tested as thread-safe on Windows only } { https://www.freepascal.org/docs-html/fcl/dbugintf/index-5.html } { Debug Message Viewer, File, Quit: terminate dbugsrv process } {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, StdCtrls, threadunit, dbugintf; type { TForm1 } TForm1 = class(TForm) btnStartThread: TButton; btnStartUnit: TButton; btnStartBoth: TButton; Memo1: TMemo; procedure btnStartBothClick(Sender: TObject); procedure btnStartUnitClick(Sender: TObject); procedure btnStartThreadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private procedure StopThreads; public Threads: array of TThreadUnit; nThreads: integer; end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btnStartThreadClick(Sender: TObject); var i: integer; begin nThreads:=8; SetLength(Threads,nThreads); for i:=0 to nThreads-1 do begin; Threads[i]:=TThreadUnit.Create(True); Threads[i].Name:='T'+i.ToString; Threads[i].Start; end; end; procedure TForm1.btnStartUnitClick(Sender: TObject); var i: integer; begin for i:=1 to 10 do begin Sleep(500); Application.ProcessMessages; Memo1.Append('Unit1 count: '+i.ToString); SendDebugFmt('Unit1 count: %d', [i]); end; Memo1.Append('Unit1 done.'); SendDebug('Unit1 done.'); StopThreads; end; procedure TForm1.btnStartBothClick(Sender: TObject); begin SendDateTime('Date/Time: ', Now); SendSeparator; SendMethodEnter('btnStartBothClick'); btnStartThreadClick(nil); btnStartUnitClick(nil); SendMethodExit('btnStartBothClick'); SendSeparator; SendDateTime('Date/Time: ', Now); end; procedure TForm1.StopThreads; var i: integer; begin for i:=Low(Threads) to High(Threads) do begin if Assigned(Threads[i]) then begin Threads[i].Terminate; Threads[i].WaitFor; FreeAndNil(Threads[i]); end; end; end; procedure TForm1.FormDestroy(Sender: TObject); begin StopThreads; end; procedure TForm1.FormShow(Sender: TObject); begin //SendDebug('FormShow'); SendBoolean('GetDebuggingEnabled', GetDebuggingEnabled); SendDebugEx('Demo Info', dlInformation); SendDebugEx('Demo Warning', dlWarning); SendDebugEx('Demo Error', dlError); SendSeparator; SendDebugFmtEx('Demo: %s', ['a message'], dlInformation); SendDebugFmtEx('Demo: %s', ['a warning'], dlWarning); SendDebugFmtEx('Demo: %s', ['an error'], dlError); SendSeparator; end; end.
unit TestFramework.DataValidators.TestTIntegerDataValidator; interface uses TestFramework, System.SysUtils, System.Variants, Interfaces.IDataValidator, DataValidators.TIntegerDataValidator; type TestTIntegerDataValidator = class(TTestCase) strict private FIntegerDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Integer; procedure TestParse_StringInteger_Valid; procedure TestParse_StringInteger_Invalid; end; implementation procedure TestTIntegerDataValidator.SetUp; begin FIntegerDataValidator := TIntegerDataValidator.Create; end; procedure TestTIntegerDataValidator.TearDown; begin end; procedure TestTIntegerDataValidator.TestParse_Integer; var ReturnValue: Boolean; AValue: Variant; begin AValue := 12; ReturnValue := FIntegerDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TestTIntegerDataValidator.TestParse_StringInteger_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := 'invalid integer'; ReturnValue := FIntegerDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TestTIntegerDataValidator.TestParse_StringInteger_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1234'; ReturnValue := FIntegerDataValidator.Parse(AValue); Check(ReturnValue = True); end; initialization // Register any test cases with the test runner RegisterTest(TestTIntegerDataValidator.Suite); end.
{ Copyright (C) 2018 Benito van der Zander (BeniBela) benito@benibela.de www.benibela.de This file is distributed under under the same license as Lazarus and the LCL itself: This file is distributed under the Library GNU General Public License 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. } {** @abstract(Mutable and immutable persistent maps as hash array mapped trie (HAMT)) Public generic classes: * TReadOnlyMap * TMutableMap * TImmutableMap Public specialized classes: * TMutableMapStringString * TMutableMapStringObject * TImmutableMapStringString * TImmutableMapStringObject } unit hamt.maps; {$mode objfpc}{$H+}{$ModeSwitch autoderef}{$ModeSwitch advancedrecords} interface uses sysutils, hamt.internals; type THAMTTypeInfo = hamt.internals.THAMTTypeInfo; generic THAMTPairInfo<TKey, TValue, TInfo> = record type TPair = packed record key: TKey; value: TValue; end; TValueSizeEquivalent = packed array[1..sizeof(TValue)] of byte; class function hash(const p: TPair): THAMTHash; static; inline; class function equal(const p, q: TPair): boolean; static; inline; class procedure addRef(var p: TPair); static; inline; class procedure release(var p: TPair); static; inline; class procedure assignEqual(var p: TPair; const q: TPair); static; inline; class function toString(const p: TPair): string; static; inline; end; //** @abstract(Generic read-only map) //** //** The data in this map can be read, but there are no public methods to modify it. generic TReadOnlyMap<TKey, TValue, TInfo> = class(specialize TReadOnlyCustomSet<specialize THAMTPairInfo<TKey, TValue, TInfo>.TPair, specialize THAMTPairInfo<TKey, TValue, TInfo>>) type PKey = ^TKey; PValue = ^TValue; TKeySizeEquivalent = packed array[1..sizeof(TKey)] of byte; TValueSizeEquivalent = packed array[1..sizeof(TValue)] of byte; PPair = THAMTNode.PItem; private function forceInclude(const key: TKey; const value: TValue; allowOverride: boolean): boolean; inline; function forceExclude(const key: TKey): boolean; inline; protected function find(const key: TKey): PPair; inline; class procedure raiseKeyError(const message: string; const key: TKey); static; public //** Creates an empty map constructor Create; //** Creates a map equal to other. No data is copied, till either map is modified (copy-on-write). constructor Create(other: specialize TReadOnlyCustomSet<THAMTNode.TItem, THAMTNode.TInfo>); //** Returns if the map contains a certain key function contains(const key:TKey): boolean; inline; //** Returns the value for a certain key, or default value def if the map does not contain the key function get(const key: TKey; const def: TValue): TValue; inline; //** Returns the value for a certain key, or default(TValue) if the map does not contain the key function getOrDefault(const key: TKey): TValue; inline; //** Returns the value for a certain key, or raises an exception if the map does not contain the key function get(const key: TKey): TValue; inline; //** Default parameter, so you can read elements with @code(map[key]) property items[key: TKey]: TValue read get; default; end; {** @abstract(Generic mutable map) Data in this map can be read (see ancestor TReadOnlyMap) and modified. Example: @longcode(# type TMutableMapStringString = specialize TMutableMap<string, string, THAMTTypeInfo>; var map: TMutableMapStringString; p: TMutableMapStringString.PPair; begin map := TMutableMapStringString.create; map.Insert('hello', 'world'); map.insert('foo', 'bar'); map['abc'] := 'def'; writeln(map['hello']); // world writeln(map.get('foo')); // bar writeln(map.get('abc', 'default')); // def //enumerate all for p in map do writeln(p^.key, ': ', p^.value); map.free; end. #) } generic TMutableMap<TKey, TValue, TInfo> = class(specialize TReadOnlyMap<TKey, TValue, TInfo>) protected procedure includeItem(const key: TKey; const value: TValue); inline; function getRef(const key: TKey): PValue; public //** Inserts a (key, value) pair, if allowOverride is true or key did not exist //** @returns If the map did not contain key function include(const key: TKey; const value: TValue; allowOverride: boolean = true): boolean; inline; //** Removes a (key, value) pair //** @returns If the map did contain key function exclude(const key: TKey): boolean; inline; //** Inserts a (key, value) pair, or raises an exception if the map did not contain key procedure insert(const key: TKey; const value: TValue); inline; //** Removes key (and the associated value), or raises an exception if the map did not contain key procedure remove(const key:TKey); inline; //** Removes everything from the map; procedure clear; //** Creates a new map equal to self. No data is copied, till either map is modified (copy-on-write). function clone: TMutableMap; //** Default parameter, so you can read or write elements with @code(map[key]) property items[key: TKey]: TValue read get write includeItem; default; //** Pointer to value property mutable[key: TKey]: PValue read getRef; end; {** @abstract(Generic immutable map) Data in this map can be read (see ancestor TReadOnlyMap) and modified by creating new maps. Example: @longcode(# type TImmutableMapStringString = specialize TImmutableMap<string, string, THAMTTypeInfo>; var map, map2, map3: TImmutableMapStringString; p: TImmutableMapStringString.PPair; begin map := TImmutableMapStringString.create; map2 := map.Insert('hello', 'world'); map3 := map2.insert('foo', 'bar'); writeln(map.get('hello', 'default')); // default writeln(map.get('foo', 'default')); // default writeln(map2.get('hello')); // world writeln(map2.get('foo', 'default')); // default writeln(map3['hello']); // world writeln(map3['foo']); // bar //enumerate all for p in map3 do writeln(p^.key, ': ', p^.value); map.free; map2.free; map3.free; end. #) } generic TImmutableMap<TKey, TValue, TInfo> = class(specialize TReadOnlyMap<TKey, TValue, TInfo>) public //** Creates a new map containing (key, value). If the map does not contain key or allowOverride is true, the value associated with the key is @code(value), otherwise the value is unchanged. //** @returns The new map function include(const key: TKey; const value: TValue; allowOverride: boolean = true): TImmutableMap; inline; overload; //** Creates a new map without key and its associated value //** @returns The new map function exclude(const key: TKey): TImmutableMap; inline; //** Creates a new map containing (key, value), or raises an exception if the map already contained key //** @returns The new map function insert(const key: TKey; const value: TValue): TImmutableMap; inline; //** Creates a new map without key and its associated value, or raises an exception if the map did not contain key //** @returns The new map function remove(const key:TKey): TImmutableMap; inline; //** Creates a new map equal to self. No data is copied, till either map is modified (copy-on-write). function clone: TImmutableMap; end; //** @abstract(A TMutableMap mapping string keys to string values.) //** The map handles reference counting and freeing of the strings. TMutableMapStringString = specialize TMutableMap<string, string, THAMTTypeInfo>; //** @abstract(A TMutableMap mapping string keys to TObject values.) //** The map handles reference counting and freeing of the string keys, but the objects are neither changed nor freed. TMutableMapStringObject = specialize TMutableMap<string, TObject, THAMTTypeInfo>; //** @abstract(A TImmutableMap mapping string keys to string values.) //** The map handles reference counting and freeing of the strings. TImmutableMapStringString = specialize TImmutableMap<string, string, THAMTTypeInfo>; //** @abstract(A TImmutableMap mapping string keys to TObject values.) //** The map handles reference counting and freeing of the string keys, but the objects are neither changed nor freed. TImmutableMapStringObject = specialize TImmutableMap<string, TObject, THAMTTypeInfo>; implementation class function THAMTPairInfo.hash(const p: TPair): THAMTHash; begin result := TInfo.hash(p.key); end; class function THAMTPairInfo.equal(const p, q: TPair): boolean; begin result := TInfo.equal(p.key, q.key); end; class procedure THAMTPairInfo.addRef(var p: TPair); begin with p do begin TInfo.addRef(key); TInfo.addRef(value); end; end; class procedure THAMTPairInfo.release(var p: TPair); begin with p do begin TInfo.release(key); TInfo.release(value); end; end; class procedure THAMTPairInfo.assignEqual(var p: TPair; const q: TPair); begin TInfo.release(p.value); TValueSizeEquivalent(p.value) := TValueSizeEquivalent(q.value); TInfo.addRef(p.value); end; class function THAMTPairInfo.toString(const p: TPair): string; begin result := TInfo.toString(p.key); end; constructor TReadOnlyMap.Create; begin froot := THAMTNode.allocateEmpty; fcount := 0; end; constructor TReadOnlyMap.Create(other: specialize TReadOnlyCustomSet<THAMTNode.TItem, THAMTNode.TInfo>); begin fcount := other.fcount; froot := other.froot; InterLockedIncrement(froot.refCount); end; function TReadOnlyMap.forceInclude(const key: TKey; const value: TValue; allowOverride: boolean): boolean; var tempPair: packed array[1..sizeof(TKey)+sizeof(TValue)] of byte; begin TKeySizeEquivalent(PPair(@tempPair).key) := TKeySizeEquivalent(key); TValueSizeEquivalent(PPair(@tempPair).value) := TValueSizeEquivalent(value); result := THAMTNode.include(@froot, PPair(@tempPair)^, allowOverride); if result then inc(fcount); end; function TReadOnlyMap.forceExclude(const key: TKey): boolean; begin result := THAMTNode.exclude(@froot, PPair(@key)^ ); //this cast should work, because key is the first element of TPair if result then dec(fcount); end; function TReadOnlyMap.find(const key: TKey): PPair; begin result := froot.find( PPair(@key)^ ); //this cast should work, because key is the first element of TPair end; class procedure TReadOnlyMap.raiseKeyError(const message: string; const key: TKey); var s: string; begin s := TInfo.toString(key); raise EHAMTException.Create(Format(message, [s]) ); end; function TReadOnlyMap.contains(const key: TKey): boolean; begin result := find(key) <> nil; end; function TReadOnlyMap.get(const key: TKey; const def: TValue): TValue; var pair: PPair; begin pair := find(key); if pair = nil then result := def else result := pair.value; end; function TReadOnlyMap.getOrDefault(const key: TKey): TValue; var pair: PPair; begin pair := find(key); if pair = nil then result := default(TValue) else result := pair.value; end; function TReadOnlyMap.get(const key: TKey): TValue; var pair: PPair; begin pair := find(key); if pair = nil then raiseKeyError(rsMissingKey, key); result := pair.value; end; procedure TMutableMap.includeItem(const key: TKey; const value: TValue); begin forceInclude(key, value, true); end; function TMutableMap.getRef(const key: TKey): PValue; var pair: PPair; begin pair := THAMTNode.findAndUnique(@froot, PPair(@key)^ ); //this cast should work, because key is the first element of TPair if pair = nil then raiseKeyError(rsMissingKey, key); result := @pair.value; end; function TMutableMap.include(const key: TKey; const value: TValue; allowOverride: boolean): boolean; begin result := forceInclude(key, value, allowOverride); end; function TMutableMap.exclude(const key: TKey): boolean; begin result := forceExclude(key); end; procedure TMutableMap.insert(const key: TKey; const value: TValue); begin if not forceInclude(key, value, false) then raiseKeyError(rsDuplicateKey, key); end; procedure TMutableMap.remove(const key:TKey); begin if not forceExclude(key) then raiseKeyError(rsMissingKey, key); end; procedure TMutableMap.clear; begin THAMTNode.decrementRefCount(froot); froot := THAMTNode.allocateEmpty; fcount := 0; end; function TMutableMap.clone: TMutableMap; begin result := TMutableMap.Create(self); end; function TImmutableMap.include(const key: TKey; const value: TValue; allowOverride: boolean): TImmutableMap; inline; begin result := TImmutableMap.Create(self); result.forceInclude(key, value, allowOverride) end; function TImmutableMap.exclude(const key: TKey): TImmutableMap; inline; begin result := TImmutableMap.Create(self); result.forceExclude(key); end; function TImmutableMap.insert(const key: TKey; const value: TValue): TImmutableMap; inline; begin result := TImmutableMap.Create(self); if not result.forceInclude(key, value, false) then begin result.free; raiseKeyError(rsDuplicateKey, key); end; end; function TImmutableMap.remove(const key:TKey): TImmutableMap; inline; begin result := TImmutableMap.Create(self); if not result.forceExclude(key) then begin result.free; raiseKeyError(rsMissingKey, key); end; end; function TImmutableMap.clone: TImmutableMap; begin result := TImmutableMap.Create(self); end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : https://preproducao.roadcard.com.br/sistemapamcard/services/WSTransacional?wsdl // >Import : https://preproducao.roadcard.com.br/sistemapamcard/services/WSTransacional?wsdl>0 // (13/03/2017 14:45:40 - - $Rev: 56641 $) // ************************************************************************ // unit WSTransacional11; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; const IS_OPTN = $0001; IS_UNBD = $0002; IS_NLBL = $0004; IS_UNQL = $0008; 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. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] requestTO = class; { "http://webservice.pamcard.jee.pamcary.com.br"[GblCplx] } fieldTO = class; { "http://webservice.pamcard.jee.pamcary.com.br"[GblCplx] } responseTO = array of fieldTO; { "http://webservice.pamcard.jee.pamcary.com.br"[GblCplx] } // ************************************************************************ // // XML : requestTO, global, <complexType> // Namespace : http://webservice.pamcard.jee.pamcary.com.br // ************************************************************************ // requestTO = class(TRemotable) private Fcontext: string; Fcontext_Specified: boolean; Ffields: responseTO; Ffields_Specified: boolean; procedure Setcontext(Index: Integer; const Astring: string); function context_Specified(Index: Integer): boolean; procedure Setfields(Index: Integer; const AresponseTO: responseTO); function fields_Specified(Index: Integer): boolean; public destructor Destroy; override; published property context: string Index (IS_OPTN or IS_UNQL) read Fcontext write Setcontext stored context_Specified; property fields: responseTO Index (IS_OPTN or IS_UNBD or IS_NLBL or IS_UNQL) read Ffields write Setfields stored fields_Specified; end; // ************************************************************************ // // XML : fieldTO, global, <complexType> // Namespace : http://webservice.pamcard.jee.pamcary.com.br // ************************************************************************ // fieldTO = class(TRemotable) private Fkey: string; Fkey_Specified: boolean; Fvalue: string; Fvalue_Specified: boolean; procedure Setkey(Index: Integer; const Astring: string); function key_Specified(Index: Integer): boolean; procedure Setvalue(Index: Integer; const Astring: string); function value_Specified(Index: Integer): boolean; published property key: string Index (IS_OPTN or IS_UNQL) read Fkey write Setkey stored key_Specified; property value: string Index (IS_OPTN or IS_UNQL) read Fvalue write Setvalue stored value_Specified; end; // ************************************************************************ // // Namespace : http://webservice.pamcard.jee.pamcary.com.br // transport : http://schemas.xmlsoap.org/soap/http // style : document // use : literal // binding : WSTransacionalBinding // service : WSTransacional // port : WSTransacional // URL : https://preproducao.roadcard.com.br/sistemapamcard/services/WSTransacional // ************************************************************************ // WSTransacional = interface(IInvokable) ['{A6A849BF-5D18-B19D-674A-39B261FB9539}'] function execute(const arg0: requestTO): responseTO; stdcall; end; function GetWSTransacional(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): WSTransacional; implementation uses SysUtils; function GetWSTransacional(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): WSTransacional; const defWSDL = 'https://preproducao.roadcard.com.br/sistemapamcard/services/WSTransacional?wsdl'; defURL = 'https://preproducao.roadcard.com.br/sistemapamcard/services/WSTransacional'; defSvc = 'WSTransacional'; defPrt = 'WSTransacional'; 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 WSTransacional); 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 requestTO.Destroy; var I: Integer; begin for I := 0 to System.Length(Ffields)-1 do SysUtils.FreeAndNil(Ffields[I]); System.SetLength(Ffields, 0); inherited Destroy; end; procedure requestTO.Setcontext(Index: Integer; const Astring: string); begin Fcontext := Astring; Fcontext_Specified := True; end; function requestTO.context_Specified(Index: Integer): boolean; begin Result := Fcontext_Specified; end; procedure requestTO.Setfields(Index: Integer; const AresponseTO: responseTO); begin Ffields := AresponseTO; Ffields_Specified := True; end; function requestTO.fields_Specified(Index: Integer): boolean; begin Result := Ffields_Specified; end; procedure fieldTO.Setkey(Index: Integer; const Astring: string); begin Fkey := Astring; Fkey_Specified := True; end; function fieldTO.key_Specified(Index: Integer): boolean; begin Result := Fkey_Specified; end; procedure fieldTO.Setvalue(Index: Integer; const Astring: string); begin Fvalue := Astring; Fvalue_Specified := True; end; function fieldTO.value_Specified(Index: Integer): boolean; begin Result := Fvalue_Specified; end; initialization { WSTransacional } InvRegistry.RegisterInterface(TypeInfo(WSTransacional), 'http://webservice.pamcard.jee.pamcary.com.br', ''); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(WSTransacional), ''); InvRegistry.RegisterInvokeOptions(TypeInfo(WSTransacional), ioDocument); { WSTransacional.execute } InvRegistry.RegisterMethodInfo(TypeInfo(WSTransacional), 'execute', '', '[ReturnName="return"]', IS_OPTN or IS_UNQL); InvRegistry.RegisterParamInfo(TypeInfo(WSTransacional), 'execute', 'arg0', '', '', IS_UNQL); InvRegistry.RegisterParamInfo(TypeInfo(WSTransacional), 'execute', 'return', '', '[ArrayItemName="fields"]', IS_UNQL); RemClassRegistry.RegisterXSInfo(TypeInfo(responseTO), 'http://webservice.pamcard.jee.pamcary.com.br', 'responseTO'); RemClassRegistry.RegisterXSClass(requestTO, 'http://webservice.pamcard.jee.pamcary.com.br', 'requestTO'); RemClassRegistry.RegisterExternalPropName(TypeInfo(requestTO), 'fields', '[ArrayItemName="fields"]'); RemClassRegistry.RegisterXSClass(fieldTO, 'http://webservice.pamcard.jee.pamcary.com.br', 'fieldTO'); end.
var x: integer; // двузначное число c1, c2: integer;// первая и вторая цифры двузначного числа begin write('Введите двузначное число: '); readln(x); c1 := x div 10; c2 := x mod 10; writeln('Первая и вторая цифры двузначного числа: ', c1, ' ', c2); end.
unit ce_symlist; {$I ce_defines.inc} interface uses Classes, SysUtils, TreeFilterEdit, Forms, Controls, Graphics, ExtCtrls, Menus, ComCtrls, ce_widget, jsonparser, process, actnlist, Buttons, Clipbrd, LCLProc, ce_common, ce_observer, ce_synmemo, ce_interfaces, ce_writableComponent; type // Enumerates the possible symbol kind. To be kept in sync with the tool declaration. TSymbolType = ( _alias, _class, _enum, _error, _function, _interface, _import, _mixin, _struct, _template, _union, _variable, _warning ); TSymbolCollection = class; // Encapsulates a symbol to enable structured serialization TSymbol = class(TCollectionItem) private fline, fCol: nativeUint; fName: string; fType: TSymbolType; fSubs: TSymbolCollection; procedure setSubs(aValue: TSymbolCollection); published property line: nativeUint read fline write fLine; property col: nativeUint read fCol write fCol; property name: string read fName write fName; property symType: TSymbolType read fType write fType; property subs: TSymbolCollection read fSubs write setSubs; public constructor Create(ACollection: TCollection); override; destructor destroy; override; end; // Encapsulates a the sub symbols. TSymbolCollection = class(TCollection) private function getSub(index: Integer): TSymbol; public constructor create; property sub[index: Integer]: TSymbol read getSub; default; end; // Serializable symbol list TSymbolList = class(TComponent) private fSymbols: TSymbolCollection; procedure setSymbols(aValue: TSymbolCollection); published property symbols: TSymbolCollection read fSymbols write setSymbols; public constructor create(aOwner: TCOmponent); override; destructor destroy; override; // procedure LoadFromTool(str: TStream); end; TCESymbolListOptions = class(TWritableLfmTextComponent) private fAutoRefresh: boolean; fRefreshOnChange: boolean; fRefreshOnFocus: boolean; fShowChildCategories: boolean; fAutoRefreshDelay: Integer; fSmartFilter: boolean; fAutoExpandErrors: boolean; fSortSymbols: boolean; published property autoRefresh: boolean read fAutoRefresh write fAutoRefresh; property refreshOnChange: boolean read fRefreshOnChange write fRefreshOnChange; property refreshOnFocus: boolean read fRefreshOnFocus write fRefreshOnFocus; property showChildCategories: boolean read fShowChildCategories write fShowChildCategories; property autoRefreshDelay: Integer read fAutoRefreshDelay write fAutoRefreshDelay; property smartFilter: boolean read fSmartFilter write fSmartFilter; property autoExpandErrors: boolean read fAutoExpandErrors write fAutoExpandErrors; property sortSymbols: boolean read fSortSymbols write fSortSymbols; public constructor Create(AOwner: TComponent); override; procedure Assign(Source: TPersistent); override; procedure AssignTo(Dest: TPersistent); override; end; { TCESymbolListWidget } TCESymbolListWidget = class(TCEWidget, ICEMultiDocObserver, ICEEditableOptions) btnRefresh: TBitBtn; imgList: TImageList; Panel1: TPanel; Tree: TTreeView; TreeFilterEdit1: TTreeFilterEdit; procedure btnRefreshClick(Sender: TObject); procedure TreeCompare(Sender: TObject; Node1, Node2: TTreeNode; var Compare: Integer); procedure TreeDeletion(Sender: TObject; Node: TTreeNode); procedure TreeFilterEdit1AfterFilter(Sender: TObject); function TreeFilterEdit1FilterItem(Item: TObject; out Done: Boolean): Boolean; procedure TreeFilterEdit1MouseEnter(Sender: TObject); procedure TreeKeyPress(Sender: TObject; var Key: char); private fHasToolExe: boolean; fOptions: TCESymbolListOptions; fSyms: TSymbolList; fMsgs: ICEMessagesDisplay; fToolProc: TCheckedAsyncProcess; fActCopyIdent: TAction; fActRefresh: TAction; fActRefreshOnChange: TAction; fActRefreshOnFocus: TAction; fActAutoRefresh: TAction; fActSelectInSource: TAction; fDoc: TCESynMemo; fAutoRefresh: boolean; fRefreshOnChange: boolean; fRefreshOnFocus: boolean; fShowChildCategories: boolean; fSmartFilter: boolean; fAutoExpandErrors: boolean; fSortSymbols: boolean; fToolOutput: TMemoryStream; ndAlias, ndClass, ndEnum, ndFunc, ndUni: TTreeNode; ndImp, ndIntf, ndMix, ndStruct, ndTmp: TTreeNode; ndVar, ndWarn, ndErr: TTreeNode; procedure TreeDblClick(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure actAutoRefreshExecute(Sender: TObject); procedure actRefreshOnChangeExecute(Sender: TObject); procedure actRefreshOnFocusExecute(Sender: TObject); procedure actCopyIdentExecute(Sender: TObject); procedure updateVisibleCat; procedure clearTree; // procedure checkIfHasToolExe; procedure callToolProc; procedure toolOutputData(sender: TObject); procedure toolTerminated(sender: TObject); // procedure docNew(aDoc: TCESynMemo); procedure docClosing(aDoc: TCESynMemo); procedure docFocused(aDoc: TCESynMemo); procedure docChanged(aDoc: TCESynMemo); // function optionedWantCategory(): string; function optionedWantEditorKind: TOptionEditorKind; function optionedWantContainer: TPersistent; procedure optionedEvent(anEvent: TOptionEditorEvent); function optionedOptionsModified: boolean; protected procedure updateDelayed; override; // function contextName: string; override; function contextActionCount: integer; override; function contextAction(index: integer): TAction; override; // procedure SetVisible(Value: boolean); override; published property autoRefresh: boolean read fAutoRefresh write fAutoRefresh; property refreshOnChange: boolean read fRefreshOnChange write fRefreshOnChange; property refreshOnFocus: boolean read fRefreshOnFocus write fRefreshOnFocus; public constructor create(aOwner: TComponent); override; destructor destroy; override; end; implementation {$R *.lfm} const OptsFname = 'symbollist.txt'; toolExeName = 'cesyms' + exeExt; {$REGION Serializable symbols---------------------------------------------------} constructor TSymbol.create(ACollection: TCollection); begin inherited create(ACollection); fSubs := TSymbolCollection.create; end; destructor TSymbol.destroy; begin fSubs.Free; inherited; end; procedure TSymbol.setSubs(aValue: TSymbolCollection); begin fSubs.Assign(aValue); end; constructor TSymbolCollection.create; begin inherited create(TSymbol); end; function TSymbolCollection.getSub(index: Integer): TSymbol; begin exit(TSymbol(self.Items[index])); end; constructor TSymbolList.create(aOwner: TCOmponent); begin inherited; fSymbols := TSymbolCollection.create; end; destructor TSymbolList.destroy; begin fSymbols.free; inherited; end; procedure TSymbolList.setSymbols(aValue: TSymbolCollection); begin fSymbols.Assign(aValue); end; procedure TSymbolList.LoadFromTool(str: TStream); var bin: TMemoryStream; begin bin := TMemoryStream.Create; try str.Position:=0; try ObjectTextToBinary(str, bin); except exit; end; bin.Position:=0; bin.ReadComponent(self); finally bin.Free; end; end; {$ENDREGION} {$REGION TCESymbolListOptions --------------------------------------------------} constructor TCESymbolListOptions.Create(AOwner: TComponent); begin inherited; fRefreshOnFocus := true; fShowChildCategories := true; fAutoExpandErrors := true; fSmartFilter := true; fSortSymbols := false; fAutoRefreshDelay := 1500; end; procedure TCESymbolListOptions.Assign(Source: TPersistent); var widg: TCESymbolListWidget; begin if Source is TCESymbolListWidget then begin widg := TCESymbolListWidget(Source); // fAutoRefreshDelay := widg.updaterByDelayDuration; fRefreshOnFocus := widg.fRefreshOnFocus; fRefreshOnChange := widg.fRefreshOnChange; fAutoRefresh := widg.fAutoRefresh; fShowChildCategories := widg.fShowChildCategories; fSmartFilter := widg.fSmartFilter; fAutoExpandErrors := widg.fAutoExpandErrors; fSortSymbols := widg.fSortSymbols; end else inherited; end; procedure TCESymbolListOptions.AssignTo(Dest: TPersistent); var widg: TCESymbolListWidget; begin if Dest is TCESymbolListWidget then begin widg := TCESymbolListWidget(Dest); // widg.updaterByDelayDuration := fAutoRefreshDelay; widg.fRefreshOnFocus := fRefreshOnFocus; widg.fRefreshOnChange := fRefreshOnChange; widg.fAutoRefresh := fAutoRefresh; widg.fShowChildCategories := fShowChildCategories; widg.fSmartFilter := fSmartFilter; widg.fAutoExpandErrors := fAutoExpandErrors; widg.fSortSymbols := fSortSymbols; // widg.fActAutoRefresh.Checked := fAutoRefresh; widg.fActRefreshOnChange.Checked:= fRefreshOnChange; widg.fActRefreshOnFocus.Checked := fRefreshOnFocus; // //if fSortSymbols then // widg.Tree.SortType := stText //else // widg.Tree.SortType:= stNone; end else inherited; end; {$ENDREGIOn} {$REGION Standard Comp/Obj------------------------------------------------------} constructor TCESymbolListWidget.create(aOwner: TComponent); var png: TPortableNetworkGraphic; fname: string; begin fAutoRefresh := false; fRefreshOnFocus := true; fRefreshOnChange := false; checkIfHasToolExe; // fActCopyIdent := TAction.Create(self); fActCopyIdent.OnExecute:=@actCopyIdentExecute; fActCopyIdent.Caption := 'Copy identifier'; fActRefresh := TAction.Create(self); fActRefresh.OnExecute := @actRefreshExecute; fActRefresh.Caption := 'Refresh'; fActAutoRefresh := TAction.Create(self); fActAutoRefresh.OnExecute := @actAutoRefreshExecute; fActAutoRefresh.Caption := 'Auto-refresh'; fActAutoRefresh.AutoCheck := true; fActAutoRefresh.Checked := fAutoRefresh; fActRefreshOnChange := TAction.Create(self); fActRefreshOnChange.OnExecute := @actRefreshOnChangeExecute; fActRefreshOnChange.Caption := 'Refresh on change'; fActRefreshOnChange.AutoCheck := true; fActRefreshOnChange.Checked := fRefreshOnChange; fActRefreshOnFocus := TAction.Create(self); fActRefreshOnFocus.OnExecute := @actRefreshOnFocusExecute; fActRefreshOnFocus.Caption := 'Refresh on focused'; fActRefreshOnFocus.AutoCheck := true; fActRefreshOnFocus.Checked := fRefreshOnFocus; fActSelectInSource := TAction.Create(self); fActSelectInSource.OnExecute := @TreeDblClick; fActSelectInSource.Caption := 'Select in source'; // inherited; // allow empty name if owner is nil fSyms := TSymbolList.create(nil); fToolOutput := TMemoryStream.create; // fOptions := TCESymbolListOptions.Create(self); fOptions.Name:= 'symbolListOptions'; fname := getCoeditDocPath + OptsFname; if FileExists(fname) then fOptions.loadFromFile(fname); fOptions.AssignTo(self); // ndAlias := Tree.Items[0]; ndClass := Tree.Items[1]; ndEnum := Tree.Items[2]; ndFunc := Tree.Items[3]; ndImp := Tree.Items[4]; ndIntf := Tree.Items[5]; ndMix := Tree.Items[6]; ndStruct := Tree.Items[7]; ndTmp := Tree.Items[8]; ndUni := Tree.Items[9]; ndVar := Tree.Items[10]; ndWarn := Tree.Items[11]; ndErr := Tree.Items[12]; // png := TPortableNetworkGraphic.Create; try png.LoadFromLazarusResource('arrow_update'); btnRefresh.Glyph.Assign(png); finally png.Free; end; // Tree.OnDblClick := @TreeDblClick; Tree.PopupMenu := contextMenu; // EntitiesConnector.addObserver(self); end; destructor TCESymbolListWidget.destroy; begin EntitiesConnector.removeObserver(self); // killProcess(fToolProc); fToolOutput.free; fSyms.Free; // fOptions.saveToFile(getCoeditDocPath + OptsFname); fOptions.Free; // inherited; end; procedure TCESymbolListWidget.SetVisible(Value: boolean); begin inherited; checkIfHasToolExe; getMessageDisplay(fMsgs); if Value then callToolProc; end; {$ENDREGION} {$REGION ICEContextualActions---------------------------------------------------} function TCESymbolListWidget.contextName: string; begin result := 'Static explorer'; end; function TCESymbolListWidget.contextActionCount: integer; begin result := 6; end; function TCESymbolListWidget.contextAction(index: integer): TAction; begin case index of 0: exit(fActSelectInSource); 1: exit(fActCopyIdent); 2: exit(fActRefresh); 3: exit(fActAutoRefresh); 4: exit(fActRefreshOnChange); 5: exit(fActRefreshOnFocus); else result := nil; end; end; procedure TCESymbolListWidget.actRefreshExecute(Sender: TObject); begin if Updating then exit; callToolProc; end; procedure TCESymbolListWidget.actAutoRefreshExecute(Sender: TObject); begin autoRefresh := fActAutoRefresh.Checked; fOptions.Assign(self); end; procedure TCESymbolListWidget.actRefreshOnChangeExecute(Sender: TObject); begin refreshOnChange := fActRefreshOnChange.Checked; fOptions.Assign(self); end; procedure TCESymbolListWidget.actRefreshOnFocusExecute(Sender: TObject); begin refreshOnFocus := fActRefreshOnFocus.Checked; fOptions.Assign(self); end; procedure TCESymbolListWidget.actCopyIdentExecute(Sender: TObject); begin if Tree.Selected = nil then exit; Clipboard.AsText:= Tree.Selected.Text; end; {$ENDREGION} {$REGION ICEEditableOptions ----------------------------------------------------} function TCESymbolListWidget.optionedWantCategory(): string; begin exit('Symbol list'); end; function TCESymbolListWidget.optionedWantEditorKind: TOptionEditorKind; begin exit(oekGeneric); end; function TCESymbolListWidget.optionedWantContainer: TPersistent; begin fOptions.Assign(self); exit(fOptions); end; procedure TCESymbolListWidget.optionedEvent(anEvent: TOptionEditorEvent); begin if anEvent <> oeeAccept then exit; fOptions.AssignTo(self); callToolProc; end; function TCESymbolListWidget.optionedOptionsModified: boolean; begin exit(false); end; {$ENDREGION} {$REGION ICEMultiDocObserver ---------------------------------------------------} procedure TCESymbolListWidget.docNew(aDoc: TCESynMemo); begin fDoc := aDoc; beginDelayedUpdate; end; procedure TCESymbolListWidget.docClosing(aDoc: TCESynMemo); begin if fDoc <> aDoc then exit; fDoc := nil; clearTree; updateVisibleCat; end; procedure TCESymbolListWidget.docFocused(aDoc: TCESynMemo); begin if fDoc = aDoc then exit; fDoc := aDoc; if not Visible then exit; // if fAutoRefresh then beginDelayedUpdate else if fRefreshOnFocus then callToolProc; end; procedure TCESymbolListWidget.docChanged(aDoc: TCESynMemo); begin if fDoc <> aDoc then exit; if not Visible then exit; // if fAutoRefresh then beginDelayedUpdate else if fRefreshOnChange then callToolProc; end; {$ENDREGION} {$REGION Symbol-tree things ----------------------------------------------------} procedure TCESymbolListWidget.updateDelayed; begin if not fAutoRefresh then exit; callToolProc; end; procedure TCESymbolListWidget.TreeDeletion(Sender: TObject; Node: TTreeNode); begin if (node.Data <> nil) then Dispose(PNativeUint(node.Data)); end; procedure TCESymbolListWidget.btnRefreshClick(Sender: TObject); begin fActRefresh.Execute; end; procedure TCESymbolListWidget.TreeCompare(Sender: TObject; Node1, Node2: TTreeNode; var Compare: Integer); begin Compare := CompareStr(Node1.Text, Node2.text); end; procedure TCESymbolListWidget.updateVisibleCat; begin if (fDoc <> nil) then begin ndAlias.Visible := ndAlias.Count > 0; ndClass.Visible := ndClass.Count > 0; ndEnum.Visible := ndEnum.Count > 0; ndFunc.Visible := ndFunc.Count > 0; ndImp.Visible := ndImp.Count > 0; ndIntf.Visible := ndIntf.Count > 0; ndMix.Visible := ndMix.Count > 0; ndStruct.Visible:= ndStruct.Count > 0; ndTmp.Visible := ndTmp.Count > 0; ndUni.Visible := ndUni.Count > 0; ndVar.Visible := ndVar.Count > 0; ndWarn.Visible := ndWarn.Count > 0; ndErr.Visible := ndErr.Count > 0; end else begin ndAlias.Visible := true; ndClass.Visible := true; ndEnum.Visible := true; ndFunc.Visible := true; ndImp.Visible := true; ndIntf.Visible := true; ndMix.Visible := true; ndStruct.Visible:= true; ndTmp.Visible := true; ndUni.Visible := true; ndVar.Visible := true; ndWarn.Visible := true; ndErr.Visible := true; end; end; procedure TCESymbolListWidget.clearTree; begin ndAlias.DeleteChildren; ndClass.DeleteChildren; ndEnum.DeleteChildren; ndFunc.DeleteChildren; ndImp.DeleteChildren; ndIntf.DeleteChildren; ndMix.DeleteChildren; ndStruct.DeleteChildren; ndTmp.DeleteChildren; ndUni.DeleteChildren; ndVar.DeleteChildren; ndWarn.DeleteChildren; ndErr.DeleteChildren; end; procedure TCESymbolListWidget.TreeFilterEdit1AfterFilter(Sender: TObject); begin if TreeFilterEdit1.Filter ='' then updateVisibleCat; end; function TCESymbolListWidget.TreeFilterEdit1FilterItem(Item: TObject; out Done: Boolean): Boolean; begin if not fSmartFilter then exit; // if TreeFilterEdit1.Filter <> '' then tree.FullExpand else if tree.Selected = nil then tree.FullCollapse else tree.MakeSelectionVisible; result := false; end; procedure TCESymbolListWidget.TreeFilterEdit1MouseEnter(Sender: TObject); begin if not fSmartFilter then exit; // tree.Selected := nil; end; procedure TCESymbolListWidget.TreeKeyPress(Sender: TObject; var Key: char); begin if Key = #13 then TreeDblClick(nil); end; procedure TCESymbolListWidget.TreeDblClick(Sender: TObject); var line: NativeUint; begin if fDoc = nil then exit; if Tree.Selected = nil then exit; if Tree.Selected.Data = nil then exit; // line := PNativeUInt(Tree.Selected.Data)^; fDoc.CaretY := line; fDoc.SelectLine; end; procedure TCESymbolListWidget.checkIfHasToolExe; begin fHasToolExe := exeInSysPath(toolExeName); end; procedure TCESymbolListWidget.callToolProc; var srcFname: string; begin if not fHasToolExe then exit; if fDoc = nil then exit; if fDoc.Lines.Count = 0 then exit; if not fDoc.isDSource then exit; // standard process options killProcess(fToolProc); fToolProc := TCheckedAsyncProcess.Create(nil); fToolProc.ShowWindow := swoHIDE; fToolProc.Options := [poUsePipes]; fToolProc.Executable := exeFullName(toolExeName); fToolProc.OnTerminate := @toolTerminated; fToolProc.OnReadData := @toolOutputData; fToolProc.CurrentDirectory := ExtractFileDir(Application.ExeName); // focused source srcFname := fDoc.fileName; if not fileExists(srcFname) or (srcFname = fDoc.tempFilename) then fDoc.saveTempFile; srcFname := fDoc.fileName; fToolProc.Parameters.Add(srcFname); fToolProc.Execute; end; procedure TCESymbolListWidget.toolOutputData(sender: TObject); begin processOutputToStream(TProcess(sender), fToolOutput); end; procedure TCESymbolListWidget.toolTerminated(sender: TObject); // function getCatNode(node: TTreeNode; stype: TSymbolType ): TTreeNode; // function newCat(const aCat: string): TTreeNode; begin result := node.FindNode(aCat); if result = nil then result := node.TreeNodes.AddChild(node, aCat); end; // begin if node = nil then case stype of _alias : exit(ndAlias); _class : exit(ndClass); _enum : exit(ndEnum); _function : exit(ndFunc); _import : exit(ndImp); _interface: exit(ndIntf); _mixin : exit(ndMix); _struct : exit(ndStruct); _template : exit(ndTmp); _union : exit(ndUni); _variable : exit(ndVar); _warning : exit(ndWarn); _error : exit(ndErr); end else case stype of _alias: exit(newCat('Alias')); _class: exit(newCat('Class')); _enum: exit(newCat('Enum')); _function: exit(newCat('Function')); _import: exit(newCat('Import')); _interface: exit(newCat('Interface')); _mixin: exit(newCat('Mixin')); _struct: exit(newCat('Struct')); _template: exit(newCat('Template')); _union: exit(newCat('Union')); _variable: exit(newCat('Variable')); _warning: exit(ndWarn); _error: exit(ndErr); end; end; // procedure symbolToTreeNode(origin: TTreenode; sym: TSymbol); var data: PNativeUint; cat: TTreeNode; node: TTreeNode; i: Integer; begin cat := getCatNode(origin, sym.symType); data := new(PNativeUint); data^ := sym.fline; node := tree.Items.AddChildObject(cat, sym.name, data); if not fShowChildCategories then node := nil; cat.Visible:=true; for i := 0 to sym.subs.Count-1 do symbolToTreeNode(node, sym.subs[i]); end; // var i: Integer; begin if ndAlias = nil then exit; clearTree; updateVisibleCat; if fDoc = nil then exit; // processOutputToStream(TProcess(sender), fToolOutput); fToolOutput.Position := 0; fSyms.LoadFromTool(fToolOutput); fToolProc.OnTerminate := nil; fToolProc.OnReadData := nil; fToolOutput.Clear; // tree.BeginUpdate; for i := 0 to fSyms.symbols.Count-1 do symbolToTreeNode(nil, fSyms.symbols[i]); if fAutoExpandErrors then begin if ndWarn.Visible then ndWarn.Expand(true); if ndErr.Visible then ndErr.Expand(true); end; if fSortSymbols then for i:= 0 to tree.Items.Count-1 do if Tree.Items[i].Count > 0 then tree.Items[i].CustomSort(nil); tree.EndUpdate; end; {$ENDREGION --------------------------------------------------------------------} end.
unit ProgramSettings; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, printers,WinSpool, FFSUtils, FFSTypes; type TProgramSettings = class(Tcomponent) private FINetConnection: integer; FINetSMTP: string; FMasterUpdate: string; FRegistryKey: string; FINetDialUser: string; FINetDialup: string; FINetMailUser: string; FINetDialPass: string; FServerIP: string; FServerPort: string; FApplPrinters : array[1..3] of string; FLastCommandLine: string; procedure SetINetConnection(const Value: integer); procedure SetINetDialPass(const Value: string); procedure SetINetDialup(const Value: string); procedure SetINetDialUser(const Value: string); procedure SetINetMailUser(const Value: string); procedure SetINetSMTP(const Value: string); procedure SetMasterUpdate(const Value: string); procedure SetRegistryKey(const Value: string); procedure SetDirWork(const Value: string); procedure SetServerIP(const Value: string); procedure SetServerPort(const Value: string); function GetPrinters(Index: Integer): string; procedure SetPrinters(Index: Integer; const Value: string); function GetDirWork: string; { Private declarations } protected { Protected declarations } public { Public declarations } procedure SaveSettings; procedure ReadSettings; property ApplPrinters[Index: Integer]: string read GetPrinters write SetPrinters; property LastCommandLine:string read FLastCommandLine ; published { Published declarations } property RegistryKey:string read FRegistryKey write SetRegistryKey; property DirWork:string read GetDirWork write SetDirWork; property MasterUpdate:string read FMasterUpdate write SetMasterUpdate; property INetConnection:integer read FINetConnection write SetINetConnection; property INetDialup:string read FINetDialup write SetINetDialup; property INetDialUser:string read FINetDialUser write SetINetDialUser; property INetDialPass:string read FINetDialPass write SetINetDialPass; property INetMailUser:string read FINetMailUser write SetINetMailUser; property INetSMTP:string read FINetSMTP write SetINetSMTP; property ServerIP: string read FServerIP write SetServerIP; property ServerPort: string read FServerPort write SetServerPort; end; TFFSDirectory = (drData, drReports, drToDo, drDone, drLtrAddOn, drUpdate, drExport, drUserRpts, drCacheReports, drCacheExport); TFFSDirSet = set of TFFSDirectory; function Dir(ADir:TFFSDirectory;DoRaise:boolean=true):string; function DirTemp:string; function DirExe:string; procedure MakeDirs(ASet:TFFSDirSet); procedure SetBaseDir(ABaseDir:string); procedure Register; implementation uses registry, filectrl; var FBaseDir:string; procedure Register; begin RegisterComponents('FFS Common', [TProgramSettings]); end; { TProgramSettings } function TProgramSettings.GetDirWork: string; begin result := FBaseDir; end; function TProgramSettings.GetPrinters(Index: Integer): string; begin result := FApplPrinters[Index]; end; procedure TProgramSettings.ReadSettings; var reg : TRegistry; x: integer; OkKey : boolean; begin reg := TRegistry.Create; try reg.RootKey := HKEY_CURRENT_USER; OkKey := reg.OpenKey(RegistryKey, false); if not OkKey then begin reg.RootKey := HKEY_LOCAL_MACHINE; OkKey := reg.OpenKey(RegistryKey, false); end; if OkKey then begin try DirWork := reg.ReadString('DataDirectory'); except DirWork := ''; end; try MasterUpdate := reg.ReadString('MasterUpdate'); except MasterUpdate := ''; end; try INetConnection := reg.ReadInteger('INetConnection'); except INetConnection := 0; end; try INetDialup := reg.ReadString('INetDialup'); except INetDialup := ''; end; try INetDialUser := reg.ReadString('INetDialUser'); except INetDialUser := ''; end; try INetDialPass := reg.ReadString('INetDialPass'); except INetDialPass := ''; end; try INetMailUser := reg.ReadString('INetMailUser'); except INetMailUser := ''; end; try INetSMTP := reg.ReadString('INetSMTP'); except INetSMTP := ''; end; try FServerIP := reg.ReadString('ServerIP'); except FServerIP := ''; end; try FServerPort := reg.ReadString('ServerPort'); except FServerPort := ''; end; for x := 1 to 3 do begin try FApplPrinters[x] := reg.ReadString('Printer' + InttoStr(x)); if empty(FApplPrinters[x]) or (not ValidPrinter(FApplPrinters[x])) then FApplPrinters[x] := FFSDEFAULTPRINTER; except FApplPrinters[x] := FFSDEFAULTPRINTER; end; end; try FLastCommandLine := reg.ReadString('LastCommandLine'); except FLastCommandLine := ''; end; reg.CloseKey; end else raise exception.create('No Such Key ' + RegistryKey ); finally reg.free; end; end; procedure TProgramSettings.SaveSettings; var reg : TRegistry; begin FLastCommandLine := strpas(CmdLine); reg := TRegistry.Create; try if reg.OpenKey(RegistryKey, true) then begin reg.WriteString('DataDirectory', DirWork); reg.WriteString('MasterUpdate', MasterUpdate); reg.WriteInteger('INetConnection', INetConnection); reg.WriteString('INetDialup', INetDialup); reg.WriteString('INetDialUser', INetDialUser); reg.WriteString('INetDialPass', INetDialPass); reg.WriteString('INetMailUser', INetMailUser); reg.WriteString('INetSMTP', INetSMTP); reg.WriteString('ServerIP',ServerIP); reg.WriteString('ServerPort',ServerPort); reg.WriteString('Printer1', ApplPrinters[1]); reg.WriteString('Printer2', ApplPrinters[2]); reg.WriteString('Printer3', ApplPrinters[3]); reg.WriteString('LastCommandLine', FLastCommandLine); reg.CloseKey; end; finally reg.free; end; end; procedure TProgramSettings.SetDirWork(const Value: string); begin if length(value) > 0 then SetBaseDir(IncludeTrailingBackslash(value)); end; procedure TProgramSettings.SetINetConnection(const Value: integer); begin FINetConnection := Value; end; procedure TProgramSettings.SetINetDialPass(const Value: string); begin FINetDialPass := Value; end; procedure TProgramSettings.SetINetDialup(const Value: string); begin FINetDialup := Value; end; procedure TProgramSettings.SetINetDialUser(const Value: string); begin FINetDialUser := Value; end; procedure TProgramSettings.SetINetMailUser(const Value: string); begin FINetMailUser := Value; end; procedure TProgramSettings.SetINetSMTP(const Value: string); begin FINetSMTP := Value; end; procedure TProgramSettings.SetMasterUpdate(const Value: string); begin FMasterUpdate := Value; end; procedure TProgramSettings.SetPrinters(Index: Integer; const Value: string); begin FApplPrinters[Index] := Value; end; procedure TProgramSettings.SetRegistryKey(const Value: string); begin FRegistryKey := Value; end; procedure TProgramSettings.SetServerIP(const Value: string); begin FServerIP := Value; end; procedure TProgramSettings.SetServerPort(const Value: string); begin FServerPort := Value; end; function Dirs(ADir:TFFSDirectory):string; begin result := ''; case ADir of drData : result := 'Data'; drReports : result := 'Reports'; drToDo : result := 'ToDo'; drDone : result := 'Done'; drLtrAddOn : result := 'LtrAddOn'; drUpdate : result := 'Update'; drExport : result := 'Export'; end; end; function DirTemp:string; var temp : array[0..255] of Char; Ptemp : PChar; begin Ptemp := temp; getTempPath(sizeof(temp),Ptemp); result := Ptemp; end; function Dir(ADir:TFFSDirectory;DoRaise:boolean=true):string; var s : string; begin result := ''; s := IncludeTrailingBackslash(ExtractFileDir(Application.ExeName)); case ADir of {$ifdef THINVER} drReports : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drData : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drToDo : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drDone : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drUpdate : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drExport : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; drLtrAddOn : begin if not empty(FBaseDir) then result := FBaseDir + Dirs(ADir) else result := s + Dirs(ADir); end; {$else} drReports : result := FBaseDir + Dirs(ADir); drData : result := FBaseDir + Dirs(ADir); drToDo : result := FBaseDir + Dirs(ADir); drDone : result := FBaseDir + Dirs(ADir); drUpdate : result := FBaseDir + Dirs(ADir); drExport : result := FBaseDir + Dirs(ADir); drLtrAddOn : result := FBaseDir + Dirs(ADir); {$endif} end; result := IncludeTrailingBackslash(result); if (not DirectoryExists(result)) and (DoRaise) then raise Exception.Create(Format('Tickler: Directory (%s) does not exist',[result])); end; procedure MakeDirs(ASet:TFFSDirSet); var x : TFFSDirectory; s : string; begin if Aset = [] then begin // for x := drData to drUpdate do begin for x := drData to drUpdate do begin // any reason not to create them all? s := Dir(x,false); if not DirectoryExists(s) then try ForceDirectories(s); except end; end; end else begin for x := low(TFFSDirectory) to high(TFFSDirectory) do begin if x in ASet then begin s := Dir(x,false); if not DirectoryExists(s) then ForceDirectories(s); end; end; end; end; function DirExe:string; begin result := IncludeTrailingBackslash(ExtractFileDir(Application.ExeName)); end; procedure SetBaseDir(ABaseDir:string); begin FBaseDir := ABaseDir; end; initialization FBaseDir := ''; end.
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ooControlClass.Factory, ooControlClass.Item; type TMainForm = class(TForm) Button1: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private ControlClassFactory: TControlClassFactory; LastTopPos: Integer; end; var NewMainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.Button1Click(Sender: TObject); var LabelTmp: TLabel; procedure AlignControl(Control: TControl; const Left: Integer); begin Control.Left := Left; Control.Top := LastTopPos; Control.Height := 22; Control.Width := 100; end; begin Inc(LastTopPos, 30); AlignControl(ControlClassFactory.CreateControl(Self, TButton), 10); AlignControl(ControlClassFactory.CreateControl(Self, TSpeedButton), 130); LabelTmp := TLabel(ControlClassFactory.CreateControl(Self, TLabel)); AlignControl(LabelTmp, 240); LabelTmp.Caption := 'Test'; end; procedure TMainForm.FormCreate(Sender: TObject); begin LastTopPos := 0; ControlClassFactory := TControlClassFactory.Create; ControlClassFactory.Add(TControlClassItem.New(TButton)); ControlClassFactory.Add(TControlClassItem.New(TSpeedButton)); ControlClassFactory.Add(TControlClassItem.New(TLabel)); end; procedure TMainForm.FormDestroy(Sender: TObject); begin ControlClassFactory.Free; end; end.
//Exercicio 39: Escreva um algoritmo que pergunte ao usuário qual tabuada ele deseja ver na tela. Calcular e exibir a tabuada. { Solução em Portugol Algoritmo Exercicio 39; Var tabuada, contador: inteiro; Inicio exiba("Programa que exibe tabuadas."); exiba("Digite uma tabuada que você quer saber: "); leia(tabuada); contador <- 1; enquanto(contador <= 10) faca exiba(tabuada," x ",contador," = ", tabuada * contador); contador <- contador + 1; fimenquanto; Fim. } // Solução em Pascal Program Exercicio39; uses crt; var tabuada, contador: integer; begin clrscr; writeln('Programa que exibe tabuadas.'); writeln('Digite uma tabuada que você quer saber: '); readln(tabuada); contador := 1; while(contador <= 10) do Begin writeln(tabuada,' x ',contador,' = ', tabuada * contador); contador := contador + 1; End; repeat until keypressed; end.
{******************************************************************************* 作者: dmzn@163.com 2020-08-12 描述: 基础信息管理 *******************************************************************************} unit UFrameBaseInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameNormal, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxContainer, Menus, cxGridCustomPopupMenu, cxGridPopupMenu, ADODB, cxLabel, UBitmapPanel, cxSplitter, dxLayoutControl, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ComCtrls, ToolWin, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxButtonEdit; type TfFrameBaseInfo = class(TfFrameNormal) EditTypes: TcxComboBox; dxLayout1Item1: TdxLayoutItem; cxTextEdit1: TcxTextEdit; dxLayout1Item2: TdxLayoutItem; cxTextEdit2: TcxTextEdit; dxLayout1Item3: TdxLayoutItem; EditName: TcxButtonEdit; dxLayout1Item4: TdxLayoutItem; cxTextEdit3: TcxTextEdit; dxLayout1Item5: TdxLayoutItem; procedure EditTypesPropertiesEditValueChanged(Sender: TObject); procedure EditNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure BtnAddClick(Sender: TObject); procedure BtnEditClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); private { Private declarations } procedure FrameConfig(const nLoad: Boolean); {*配置信息*} public { Public declarations } class function FrameID: integer; override; procedure OnCreateFrame; override; procedure OnDestroyFrame; override; {*基类函数*} function InitFormDataSQL(const nWhere: string): string; override; {*查询SQL*} end; implementation {$R *.dfm} uses IniFiles, UDataModule, UFormBase, ULibFun, UMgrControl, USysConst, USysDB, USysPopedom; class function TfFrameBaseInfo.FrameID: integer; begin Result := cFI_FrameBaseInfo; end; procedure TfFrameBaseInfo.OnCreateFrame; var nIdx: Integer; begin inherited; with EditTypes.Properties do begin Items.Clear; Items.Add('0.全部'); for nIdx:=Low(cBaseData) to High(cBaseData) do Items.AddObject(IntToStr(nIdx+1) + '.' + cBaseData[nIdx].FDesc, Pointer(nIdx)); //xxxxx end; FrameConfig(True); end; procedure TfFrameBaseInfo.OnDestroyFrame; begin FrameConfig(False); inherited; end; procedure TfFrameBaseInfo.FrameConfig(const nLoad: Boolean); var nStr: string; nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try if nLoad then begin nStr := nIni.ReadString(Name, 'DefaultType', ''); if nStr <> '' then EditTypes.ItemIndex := EditTypes.Properties.Items.IndexOf(nStr); //xxxxx if EditTypes.ItemIndex < 0 then EditTypes.ItemIndex := 0; //xxxxx end else begin nIni.WriteString(Name, 'DefaultType', EditTypes.Text); end; finally nIni.Free; end; end; function TfFrameBaseInfo.InitFormDataSQL(const nWhere: string): string; var nIdx: Integer; begin Result := ''; if EditTypes.ItemIndex > 0 then begin nIdx := Integer(EditTypes.Properties.Items.Objects[EditTypes.ItemIndex]); Result := Result + Format(' Where B_Group=''%s''', [cBaseData[nIdx].FName]); end; if nWhere <> '' then begin if Result = '' then Result := ' Where (' + nWhere + ')' else Result := Result + ' And (' + nWhere + ')'; end; Result := 'Select * From ' + sTable_BaseInfo + Result; end; procedure TfFrameBaseInfo.EditTypesPropertiesEditValueChanged(Sender: TObject); begin if EditTypes.IsFocused then InitFormData(FWhere); end; procedure TfFrameBaseInfo.EditNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin if Sender = EditName then begin EditName.Text := Trim(EditName.Text); if EditName.Text = '' then Exit; FWhere := 'B_Text like ''%%%s%%'' Or B_Py like ''%%%s%%'''; FWhere := Format(FWhere, [EditName.Text, EditName.Text]); InitFormData(FWhere); end end; //------------------------------------------------------------------------------ //Desc: 添加 procedure TfFrameBaseInfo.BtnAddClick(Sender: TObject); var nParam: TFormCommandParam; begin if EditTypes.ItemIndex <= 0 then nParam.FParamA := -1 else nParam.FParamA := Integer(EditTypes.Properties.Items.Objects[EditTypes.ItemIndex]); nParam.FCommand := cCmd_AddData; CreateBaseFormItem(cFI_FormBaseInfo, PopedomItem, @nParam); if (nParam.FCommand = cCmd_ModalResult) and (nParam.FParamA = mrOK) then begin InitFormData(''); end; end; //Desc: 修改 procedure TfFrameBaseInfo.BtnEditClick(Sender: TObject); var nParam: TFormCommandParam; begin if cxView1.DataController.GetSelectedCount < 1 then begin ShowMsg('请选择要编辑的记录', sHint); Exit; end; nParam.FCommand := cCmd_EditData; nParam.FParamA := SQLQuery.FieldByName('B_ID').AsString; CreateBaseFormItem(cFI_FormBaseInfo, PopedomItem, @nParam); if (nParam.FCommand = cCmd_ModalResult) and (nParam.FParamA = mrOK) then begin InitFormData(FWhere); end; end; //Desc: 删除 procedure TfFrameBaseInfo.BtnDelClick(Sender: TObject); var nStr: string; begin if cxView1.DataController.GetSelectedCount < 1 then begin ShowMsg('请选择要删除的档案', sHint); Exit; end; nStr := SQLQuery.FieldByName('B_Text').AsString; if not QueryDlg('确定要删除[ ' + nStr + ' ]档案吗?', sAsk) then Exit; nStr := SQLQuery.FieldByName('B_ID').AsString; nStr := Format('Delete From %s Where B_ID=%s', [sTable_BaseInfo, nStr]); FDM.ExecuteSQL(nStr); InitFormData(FWhere); ShowMsg('删除成功', sHint); end; initialization gControlManager.RegCtrl(TfFrameBaseInfo, TfFrameBaseInfo.FrameID); end.
unit JunoAi4DelphiResources; interface uses JunoApi4Delphi.Interfaces; type TJunoApi4DelphiResources = class(TInterfacedObject, iJunoApi4DelphiResources) private FParent : iJunoApi4DelphiConig; public constructor Create(Parent : iJunoApi4DelphiConig); destructor Destroy; override; class function New(Parent : iJunoApi4DelphiConig) : iJunoApi4DelphiResources; function DataService : iDataService; function ChargeService : iChargeService; function BalanceService : iBalanceService; function PaymentService : iPaymentService; function DocumentService : iDocumentService; function TransferService : iTransferService; function CreditCardService : iCreditCardService; function BillPaymentService : iBillPaymentService; function CredentialsService : iCredentialsService; function NotificationService : iNotificationService; function AuthorizationService : iAuthorizationService; function DigitalAccountService : iDigitalAccountService; function PlansService : iPlans; function Subscriptions : iSubscriptions; end; implementation uses DataService, ChargeService, BalanceService, CreditCardService, CredentialsService, BillPaymentService, DigitalAccountService, DocumentService, NotificationService, PaymentService, AuthorizationService, TransferService,PlansService, SubscriptionsService; { TJunoApi4DelphiResources } function TJunoApi4DelphiResources.AuthorizationService: iAuthorizationService; begin Result := TAuthorizationService.New(FParent); end; function TJunoApi4DelphiResources.BalanceService: iBalanceService; begin Result := TBalanceService.New(FParent, Self.AuthorizationService); end; function TJunoApi4DelphiResources.BillPaymentService: iBillPaymentService; begin Result := TBillPaymentService.New; end; function TJunoApi4DelphiResources.ChargeService: iChargeService; begin Result := TChargeService.New(FParent, Self.AuthorizationService); end; constructor TJunoApi4DelphiResources.Create(Parent : iJunoApi4DelphiConig); begin FParent := Parent; end; function TJunoApi4DelphiResources.CredentialsService: iCredentialsService; begin Result := TCredentialsService.New; end; function TJunoApi4DelphiResources.CreditCardService: iCreditCardService; begin Result := TCreditCardService.New; end; function TJunoApi4DelphiResources.DataService: iDataService; begin Result := TDataService.New(FParent, Self.AuthorizationService); end; destructor TJunoApi4DelphiResources.Destroy; begin inherited; end; function TJunoApi4DelphiResources.DigitalAccountService: iDigitalAccountService; begin Result := TDigitalAccountService.New; end; function TJunoApi4DelphiResources.DocumentService: iDocumentService; begin Result := TDocumentService.New; end; class function TJunoApi4DelphiResources.New(Parent : iJunoApi4DelphiConig) : iJunoApi4DelphiResources; begin Result := Self.Create(Parent); end; function TJunoApi4DelphiResources.NotificationService: iNotificationService; begin Result := TNotificationService.New(FParent, Self.AuthorizationService); end; function TJunoApi4DelphiResources.PaymentService: iPaymentService; begin Result := TPaymentService.New; end; function TJunoApi4DelphiResources.PlansService: iPlans; begin Result := TPlansService.New(FParent, Self.AuthorizationService); end; function TJunoApi4DelphiResources.Subscriptions: iSubscriptions; begin Result := TSubscriptionsService.New(FParent, Self.AuthorizationService); end; function TJunoApi4DelphiResources.TransferService: iTransferService; begin Result := TTransferService.New; end; end.
{******************************************************************************} { } { Library: Fundamentals TLS } { File name: flcTLSRandom.pas } { File version: 5.02 } { Description: TLS Random } { } { Copyright: Copyright (c) 2008-2020, David J Butler } { 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. } { 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. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2008/01/18 0.01 Initial development. } { 2020/05/09 5.02 Create flcTLSRandom unit from flcTLSUtils unit. } { } {******************************************************************************} {$INCLUDE flcTLS.inc} unit flcTLSRandom; interface uses { Utils } flcStdTypes; { } { Random } { } type TTLSRandom = packed record gmt_unix_time : Word32; random_bytes : array[0..27] of Byte; end; PTLSRandom = ^TTLSRandom; const TLSRandomSize = Sizeof(TTLSRandom); procedure InitTLSRandom(var Random: TTLSRandom); function TLSRandomToStr(const Random: TTLSRandom): RawByteString; { } { Test } { } {$IFDEF TLS_TEST} procedure Test; {$ENDIF} implementation uses { System } SysUtils, { Crypto } flcCryptoRandom; { } { Random } { gmt_unix_time The current time and date in standard UNIX } { 32-bit format according to the sender's } { internal clock. Clocks are not required to be } { set correctly by the basic SSL Protocol; higher } { level or application protocols may define } { additional requirements. } { random_bytes 28 bytes generated by a secure random number } { generator. } { } procedure InitTLSRandom(var Random: TTLSRandom); begin Random.gmt_unix_time := Word32(DateTimeToFileDate(Now)); SecureRandomBuf(Random.random_bytes, SizeOf(Random.random_bytes)); end; function TLSRandomToStr(const Random: TTLSRandom): RawByteString; begin SetLength(Result, TLSRandomSize); Move(Random, Result[1], TLSRandomSize); end; { } { Test } { } {$IFDEF TLS_TEST} {$ASSERTIONS ON} procedure Test; begin Assert(TLSRandomSize = 32); end; {$ENDIF} end.
{ Fast Memory Manager: FullDebugMode Borlndmm.dll support unit If you use the replacement Borlndmm.dll compiled in FullDebugMode, and you need access to some of the extended functionality that is not imported by sharemem.pas, then you may use this unit to get access to it. Please note that you will still need to add sharemem.pas as the first unit in the "uses" section of the .dpr, and the FastMM_FullDebugMode.dll must be available on the path. Also, the borlndmm.dll that you will be using *must* be compiled using FullDebugMode.} unit FastMMDebugSupport; interface {Specify the full path and name for the filename to be used for logging memory errors, etc. If ALogFileName is nil or points to an empty string it will revert to the default log file name.} procedure SetMMLogFileName(ALogFileName: PAnsiChar = nil); {Returns the current "allocation group". Whenever a GetMem request is serviced in FullDebugMode, the current "allocation group" is stored in the block header. This may help with debugging. Note that if a block is subsequently reallocated that it keeps its original "allocation group" and "allocation number" (all allocations are also numbered sequentially).} function GetCurrentAllocationGroup: Cardinal; {Allocation groups work in a stack like fashion. Group numbers are pushed onto and popped off the stack. Note that the stack size is limited, so every push should have a matching pop.} procedure PushAllocationGroup(ANewCurrentAllocationGroup: Cardinal); procedure PopAllocationGroup; {Logs detail about currently allocated memory blocks for the specified range of allocation groups. if ALastAllocationGroupToLog is less than AFirstAllocationGroupToLog or it is zero, then all allocation groups are logged. This routine also checks the memory pool for consistency at the same time.} procedure LogAllocatedBlocksToFile(AFirstAllocationGroupToLog, ALastAllocationGroupToLog: Cardinal); implementation const borlndmm = 'borlndmm.dll'; procedure SetMMLogFileName; external borlndmm; function GetCurrentAllocationGroup; external borlndmm; procedure PushAllocationGroup; external borlndmm; procedure PopAllocationGroup; external borlndmm; procedure LogAllocatedBlocksToFile; external borlndmm; end.
unit fcGraphics; interface uses Windows, Graphics; function PaletteFromDIBColorTable(DIBHandle: THandle; ColorTable: Pointer; ColorCount: Integer): HPalette; procedure ByteSwapColors(var Colors; Count: Integer); implementation procedure ByteSwapColors(var Colors; Count: Integer); var // convert RGB to BGR and vice-versa. TRGBQuad <-> TPaletteEntry SysInfo: TSystemInfo; begin GetSystemInfo(SysInfo); asm MOV EDX, Colors MOV ECX, Count DEC ECX JS @@END LEA EAX, SysInfo CMP [EAX].TSystemInfo.wProcessorLevel, 3 JE @@386 @@1: MOV EAX, [EDX+ECX*4] BSWAP EAX SHR EAX,8 MOV [EDX+ECX*4],EAX DEC ECX JNS @@1 JMP @@END @@386: PUSH EBX @@2: XOR EBX,EBX MOV EAX, [EDX+ECX*4] MOV BH, AL MOV BL, AH SHR EAX,16 SHL EBX,8 MOV BL, AL MOV [EDX+ECX*4],EBX DEC ECX JNS @@2 POP EBX @@END: end; end; function SystemPaletteOverride(var Pal: TMaxLogPalette): Boolean; var DC: HDC; SysPalSize: Integer; begin Result := False; if SystemPalette16 <> 0 then begin DC := GetDC(0); try SysPalSize := GetDeviceCaps(DC, SIZEPALETTE); if SysPalSize >= 16 then begin { Ignore the disk image of the palette for 16 color bitmaps. Replace with the first and last 8 colors of the system palette } GetPaletteEntries(SystemPalette16, 0, 8, Pal.palPalEntry); GetPaletteEntries(SystemPalette16, 8, 8, Pal.palPalEntry[Pal.palNumEntries - 8]); Result := True; end finally ReleaseDC(0,DC); end; end; end; function PaletteFromDIBColorTable(DIBHandle: THandle; ColorTable: Pointer; ColorCount: Integer): HPalette; var DC: HDC; Save: THandle; Pal: TMaxLogPalette; begin Result := 0; Pal.palVersion := $300; if DIBHandle <> 0 then begin DC := CreateCompatibleDC(0); Save := SelectObject(DC, DIBHandle); Pal.palNumEntries := GetDIBColorTable(DC, 0, 256, Pal.palPalEntry); SelectObject(DC, Save); DeleteDC(DC); end else begin Pal.palNumEntries := ColorCount; Move(ColorTable^, Pal.palPalEntry, ColorCount * 4); end; if Pal.palNumEntries = 0 then Exit; if (Pal.palNumEntries <> 16) or not SystemPaletteOverride(Pal) then ByteSwapColors(Pal.palPalEntry, Pal.palNumEntries); Result := CreatePalette(PLogPalette(@Pal)^); end; end.
unit uMainFMX; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, IPPeerClient, IPPeerServer, FMX.Layouts, FMX.Memo, System.Tether.Manager, System.Tether.AppProfile, FMX.Edit, System.Actions, FMX.ActnList; type TForm2 = class(TForm) ttaProfile: TTetheringAppProfile; ttManager: TTetheringManager; lblID: TLabel; mmLog: TMemo; edtSended: TEdit; edtTime: TEdit; Button1: TButton; ActionList1: TActionList; ActionCerrar: TAction; procedure FormShow(Sender: TObject); procedure ttManagerPairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure ttManagerPairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); procedure ttaProfileAcceptResource(const Sender: TObject; const AProfileId: string; const AResource: TCustomRemoteItem; var AcceptResource: Boolean); procedure ttaProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); procedure Button1Click(Sender: TObject); procedure ttaProfileResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); procedure ActionCerrarExecute(Sender: TObject); private procedure _log(AMsg:string); public { Public declarations } end; var Form2: TForm2; implementation {$R *.fmx} procedure TForm2.ActionCerrarExecute(Sender: TObject); begin ShowMessage('Cerrando...'); Self.Close; end; procedure TForm2.Button1Click(Sender: TObject); var pInfo:TTetheringProfileInfo; rRes:TRemoteResource; begin pInfo := ttManager.RemoteProfiles[0]; rRes := ttaProfile.GetRemoteResourceValue(pInfo, 'SharedRes1'); ttaProfile.SubscribeToRemoteItem(pInfo, rRes); end; procedure TForm2.FormShow(Sender: TObject); begin lblID.Text := ttManager.Identifier; Self.Caption := ttManager.Identifier; // autoconectar ttManager.AutoConnect(); end; procedure TForm2.ttaProfileAcceptResource(const Sender: TObject; const AProfileId: string; const AResource: TCustomRemoteItem; var AcceptResource: Boolean); begin AcceptResource := true; end; procedure TForm2.ttaProfileResourceReceived(const Sender: TObject; const AResource: TRemoteResource); begin edtSended.Text := AResource.Value.AsString; end; procedure TForm2.ttaProfileResourceUpdated(const Sender: TObject; const AResource: TRemoteResource); begin edtTime.Text := AResource.Value.AsString; end; procedure TForm2.ttManagerPairedFromLocal(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin _Log('PairedFromLocal; ' + AManagerInfo.ManagerIdentifier); end; procedure TForm2.ttManagerPairedToRemote(const Sender: TObject; const AManagerInfo: TTetheringManagerInfo); begin _Log('PairedToRemote; ' + AManagerInfo.ManagerIdentifier); end; procedure TForm2._log(AMsg: string); begin mmLog.Lines.Add(AMsg); end; end.
unit l3Msg; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Msg - описание сообщений библиотеки L3} { Начат: 29.01.99 14:27 } { $Id: l3Msg.pas,v 1.13 2007/12/05 12:35:11 lulin Exp $ } // $Log: l3Msg.pas,v $ // Revision 1.13 2007/12/05 12:35:11 lulin // - вычищен условный код, составлявший разницу ветки и Head'а. // // Revision 1.12 2006/01/18 10:38:23 lulin // - bug fix: не компилировалось тестовое приложение. // // Revision 1.11 2005/10/13 06:00:26 lulin // - cleanup. // // Revision 1.10 2000/12/15 15:19:01 law // - вставлены директивы Log. // {$Include l3Define.inc } interface uses l3Types ; type {Базовый тип сообщений, содержащих только код сообщения} Ml3Base = object public // public fields Msg : Cardinal; end;//Ml3Base {Тип сообщения для изменения признака модификации содержимого объекта. cм: (V) MemGetModify} MemSetModify = object(Ml3Base) public // public fields Modified : CardinalBool; end;//MemSetModify {Базовый тип сообщений, не содержащих WParam} Ml3NoWParam = object(Ml3Base) private // internal fields NoWParam : Cardinal; end;//Ml3NoWParam {Базовый тип сообщений, не содержащих LParam} Ml3NoLParam = object(Ml3NoWParam) private // internal fields NoLParam : Long; end;//Ml3NoLParam {Далее следуют сообщения не содержащие LParam} {Тип сообщения для чтения информации о модификации содержимого объекта. cм: (^) MemSetModify} MemGetModify = object(Ml3NoLParam) public // public fields Modified : LongBool; end;//MemGetModify TEMSetReadOnly = object(Ml3Base) ReadOnly : CardinalBool; UnusedL : Long; Result : LongBool; end;//TEMSetReadOnly implementation end.
unit uTv; interface type TStatus = (tsAdicionar, tsEditar); type TTv = class private FStatusTela: TStatus; FId: Integer; FName: String; procedure SetName(const Value: String); public property StatusTela: TStatus read FStatusTela write FStatusTela; property IdTV: Integer read FId write FId; property NomeTV: String read FName write SetName; constructor Create; destructor Destroy; override; class function New: TTv; end; implementation uses System.SysUtils; { Tv } constructor TTv.Create; begin end; destructor TTv.Destroy; begin inherited; end; class function TTv.New: TTv; begin Result := TTv.Create; end; procedure TTv.SetName(const Value: String); begin if Value = '' then raise Exception.Create('Nome da TV e invalido'); FName := UpperCase(Value); end; end.
unit dr_server; {$mode objfpc}{$H+} interface uses Classes, SysUtils, dr_api, dr_script, synapseServer, hexsqlite, hextools, md5, fileinfo; type TDeepRedServer = class (TComponent) private _brookServer : THTTPServer; _scriptServer : TPascalScriptHelper; _synapseServer : TTCP_NetworkServer; _sqliteClient : THexSQLiteClient; _running : boolean; _errorStr : string; _motd : string; function DisplayError : PChar; protected procedure WriteLog(evType : TEventType; const msg : string); virtual; abstract; public constructor Create(brookfile : string; dbfile : string); destructor Destroy; override; procedure AddBinding(const address : ansistring); procedure ClearBindings; function StartServer : boolean; function StopServer : boolean; procedure OnNetworkEvent(const netState : TNetworkState); procedure OnError(ASender: TObject; AException: Exception); property Running : boolean read _running; property Error : PChar read DisplayError; end; resourcestring rs_ACK = 'ACK'; rs_NAK = 'NAK'; rs_MOTD = 'MOTD'; rs_WHOAMI = 'WHOAMI'; rs_VERSION = 'VERSION'; rs_HELP = 'HELP'; rs_STATUS = 'STATUS'; rs_KTHXBAI = 'KTHXBAI'; function MD5HashFromString(const inStr : string) : PChar; function MD5HashFromFile(const inFile : string) : PChar; implementation //============================================================================== // Miscellaneous //============================================================================== function MD5HashFromString(const inStr : string) : PChar; begin Result := PChar(MD5Print(MD5String(inStr))); end; function MD5HashFromFile(const inFile : string) : PChar; begin Result := PChar(MD5Print(MD5File(inFile))); end; //============================================================================== // TDeepRedServer //============================================================================== function TDeepRedServer.DisplayError : PChar; begin Result := PChar(_errorStr); end; procedure TDeepRedServer.OnNetworkEvent(const netState : TNetworkState); var i,j,k : cardinal; size : cardinal; f : TFileStream; p : pointer; str : ansistring; FileVerInfo: TFileVersionInfo; begin with netState do begin if not tcp then exit; //for future evolutions of synapseserver case msgType of CONNECT_MSG : begin end; DISCONNECT_MSG : begin end; SENDSTRING_MSG : begin if StringMatch(rs_HELP,msg,PERFECT_MATCH,i) then begin _synapseServer.Server_SendMessage(@id,'-- Available commands : '); _synapseServer.Server_SendMessage(@id,'-- HELP/WHOAMI/STATUS/VERSION/MOTD/KTHXBAI'); exit; end; if StringMatch(rs_WHOAMI,msg,PERFECT_MATCH,i) then begin _synapseServer.Server_SendMessage(@id,'-- You are peer '+ peerIp+' on port '+ SysUtils.IntToStr(peerPort)); exit; end; if StringMatch(rs_STATUS,msg,PERFECT_MATCH,i) then begin _synapseServer.Server_SendMessage(@id,'-- XSWAG server running | '+ SysUtils.IntToStr(_synapseServer.ClientCount) +'/'+ SysUtils.IntToStr(_synapseServer.MaxConnectedClients)); exit; end; if StringMatch(rs_VERSION,msg,PERFECT_MATCH,i) then begin FileVerInfo := TFileVersionInfo.Create(nil); try FileVerInfo.ReadFileInfo; _synapseServer.Server_SendMessage(@id,FileVerInfo.VersionStrings.Values['ProductVersion']); finally FileVerInfo.Free; end; exit; end; if StringMatch(rs_MOTD,msg,PERFECT_MATCH,i) then begin _synapseServer.Server_SendMessage(@id,_motd); exit; end; if StringMatch(rs_KTHXBAI,msg,PERFECT_MATCH,i) then begin _synapseServer.Server_SendMessage(@id,'BAI!'); _synapseServer.Server_Kick(@id); exit; end; _synapseServer.Server_Kick(@id); end; end; end; end; procedure TDeepRedServer.OnError(ASender: TObject; AException: Exception); begin Self.WriteLog(etError, AException.Message); end; constructor TDeepRedServer.Create(brookfile : string; dbfile : string); begin _running := false; _errorStr := ''; _motd := ''; //_sqliteClient := THexSQLiteClient.Create; //if not(_sqliteClient.OpenSQLiteDB(dbfile)) then _errorStr := _sqliteClient.Error; //_synapseServer := TTCP_NetworkServer.Create(timeout,port,maxConnections); //_synapseServer.OnNetworkEvent := @OnNetworkEvent; //BrookSettings.Configuration := brookfile; try _errorStr := 'Error while loading '+BROOKLIBNAME; LoadBrookLib('/usr/local/lib64/libsagui.so.2.4.0'); _brookServer := THTTPServer.Create(nil); //_brookServer.OnError:= @OnError; except WriteLog(etError, _errorStr); halt(1); end; with _brookServer do begin Port:= 8080; ConnectionLimit := 100; Threaded := True; NoFavicon := True; end; _brookServer.Open; if not _brookServer.Active then begin WriteLog(etError, 'HTTP Server not active.'); halt(1); end; end; destructor TDeepRedServer.Destroy; begin //_sqliteClient.CloseSQLiteDB; //_sqliteClient.Free; //_synapseServer.Terminate; try _brookServer.Close; _brookServer.Free; UnloadBrookLib; finally end; end; procedure TDeepRedServer.AddBinding(const address : ansistring); begin //_synapseServer.AddNewBinding(address); end; procedure TDeepRedServer.ClearBindings; begin //_synapseServer.ClearBindings; end; function TDeepRedServer.StartServer : boolean; begin Result := true; (*if not(_synapseServer.Server_Activate) then begin _errorStr := 'DeepRed server already up!'; Result := false; end; *) end; function TDeepRedServer.StopServer : boolean; begin Result := true; (*if not(_synapseServer.Server_Deactivate) then begin _errorStr := 'DeepRed server already down!'; Result := false; end; *) end; end.
unit sql; interface uses SysUtils, Classes, Windows, ActiveX, Dialogs, Forms, Data.DB, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZStoredProcedure; var PConnect: TZConnection; PQuery: TZQuery; DataSource: TDataSource; function ConfigPostgresSetting(InData: bool): bool; function SqlRead: bool; function SqlInsert: bool; function SqlUpdate(InId: integer): bool; function SqlDelete(InId: integer): bool; implementation uses main, settings; function ConfigPostgresSetting(InData: bool): bool; begin if InData then begin PConnect := TZConnection.Create(nil); PQuery := TZQuery.Create(nil); try PConnect.LibraryLocation := CurrentDir + '\'+ PgSqlConfigArray[3]; PConnect.Protocol := 'postgresql-9'; PConnect.HostName := PgSqlConfigArray[1]; PConnect.Port := strtoint(PgSqlConfigArray[6]); PConnect.User := PgSqlConfigArray[4]; PConnect.Password := PgSqlConfigArray[5]; PConnect.Database := PgSqlConfigArray[2]; PConnect.Connect; PQuery.Connection := PConnect; DataSource := TDataSource.Create(nil); DataSource.DataSet := PQuery; except on E: Exception do Showmessage('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end else begin FreeAndNil(DataSource); FreeAndNil(PQuery); FreeAndNil(PConnect); end; end; function SqlRead: bool; begin try PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('SELECT id, grade, standard, strength_class, c_min, c_max, mn_min'); PQuery.SQL.Add(',mn_max, si_min, si_max, diameter_min, diameter_max, limit_min, limit_max'); PQuery.SQL.Add(', cast(case t1.type'); PQuery.SQL.Add('when ''yield_point'' then ''предел текучести'''); PQuery.SQL.Add('when ''rupture_strength'' then ''временное сопротивление'' end as varchar(50)) as type'); PQuery.SQL.Add(',(SELECT COUNT(*) FROM technological_sample AS t2'); PQuery.SQL.Add('WHERE t2.id <= t1.id) AS numeric FROM technological_sample AS t1'); PQuery.SQL.Add('order by id desc'); PQuery.Open; except on E: Exception do Showmessage('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; function SqlInsert: bool; begin PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('INSERT INTO technological_sample'); PQuery.SQL.Add('(grade, standard, strength_class, c_min, c_max, mn_min'); PQuery.SQL.Add(',mn_max, si_min, si_max, diameter_min, diameter_max, limit_min'); PQuery.SQL.Add(', limit_max, type)'); PQuery.SQL.Add('VALUES('''+trim(form1.e_grade.Text)+''''); PQuery.SQL.Add(', '''+trim(form1.e_standard.Text)+''''); PQuery.SQL.Add(', '''+trim(form1.e_strength_class.Text)+''''); PQuery.SQL.Add(', '+trim(form1.e_c_min.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_c_max.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_mn_min.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_mn_max.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_si_min.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_si_max.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_diameter_min.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_diameter_max.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_limit_min.Text)+''); PQuery.SQL.Add(', '+trim(form1.e_limit_max.Text)+''); if form1.rb_yield_point.Checked then PQuery.SQL.Add(', ''yield_point'')'); if form1.rb_rupture_strength.Checked then PQuery.SQL.Add(', ''rupture_strength'')'); PQuery.ExecSQL; SqlRead; end; function SqlUpdate(InId: integer): bool; begin PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('UPDATE technological_sample SET'); PQuery.SQL.Add('grade='''+trim(form1.e_grade.Text)+''''); PQuery.SQL.Add(', standard='''+trim(form1.e_standard.Text)+''''); PQuery.SQL.Add(', strength_class='''+trim(form1.e_strength_class.Text)+''''); PQuery.SQL.Add(', c_min='+trim(form1.e_c_min.Text)+''); PQuery.SQL.Add(', c_max='+trim(form1.e_c_max.Text)+''); PQuery.SQL.Add(', mn_min='+trim(form1.e_mn_min.Text)+''); PQuery.SQL.Add(', mn_max='+trim(form1.e_mn_max.Text)+''); PQuery.SQL.Add(', si_min='+trim(form1.e_si_min.Text)+''); PQuery.SQL.Add(', si_max='+trim(form1.e_si_max.Text)+''); PQuery.SQL.Add(', diameter_min='+trim(form1.e_diameter_min.Text)+''); PQuery.SQL.Add(', diameter_max='+trim(form1.e_diameter_max.Text)+''); PQuery.SQL.Add(', limit_min='+trim(form1.e_limit_min.Text)+''); PQuery.SQL.Add(', limit_max='+trim(form1.e_limit_max.Text)+''); if form1.rb_yield_point.Checked then PQuery.SQL.Add(', type=''yield_point'''); if form1.rb_rupture_strength.Checked then PQuery.SQL.Add(', type=''rupture_strength'''); PQuery.SQL.Add('where id='+inttostr(InId)+''); PQuery.ExecSQL; SqlRead; end; function SqlDelete(InId: integer): bool; begin PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('DELETE FROM technological_sample'); PQuery.SQL.Add('where id='+inttostr(InId)+''); PQuery.ExecSQL; SqlRead; end; end.
PROGRAM Test; VAR radius: REAL; FUNCTION CircleArea(r : REAL): REAL; BEGIN CircleArea := 3.1415 * r * r; END; BEGIN radius := 5.0; radius := CircleArea(radius); END.
unit FmDocumentsEditor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.ImageList, Vcl.ImgList, Vcl.PlatformDefaultStyleActnCtrls, System.Actions, Vcl.ActnList, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls, Vcl.ComCtrls, GlobalData, JvComponentBase, JvDragDrop, GsDocument, DocumentEditor, Vcl.Menus, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxRibbonSkins, dxSkinsCore, dxSkinOffice2013LightGray, dxSkinVisualStudio2013Blue, dxSkinVS2010, dxSkinsdxRibbonPainter, dxRibbonCustomizationForm, dxSkinsdxBarPainter, dxBar, cxClasses, dxRibbon, dxRibbonForm, Winapi.ShlObj, cxShellCommon, dxBreadcrumbEdit, dxShellBreadcrumbEdit, cxTreeView, cxShellTreeView, cxContainer, cxEdit, cxListView, cxShellListView, Vcl.ExtCtrls, FmChapterEditor, VirtualTrees, System.UITypes, ActionHandler; type TDocumentsEditorForm = class(TdxRibbonForm) pcMain: TPageControl; amMain: TActionManager; tsDocumentList: TTabSheet; tsDocuments: TTabSheet; pcDocuments: TPageControl; OpenDialog: TOpenDialog; JvDragDrop: TJvDragDrop; StatusBar: TStatusBar; acGoBack: TAction; acEdit: TAction; acClear: TAction; PopupMenu: TPopupMenu; N1: TMenuItem; N2: TMenuItem; acCheckAll: TAction; acUncheckAll: TAction; acSaveAll: TAction; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; N6: TMenuItem; N7: TMenuItem; acOpen: TAction; acCopy: TAction; acCut: TAction; acPaste: TAction; acEditElement: TAction; acAddElement: TAction; acDeletePosition: TAction; acAddChapter: TAction; acAddSubChapter: TAction; acSmartEditor: TAction; acEditAttributes: TAction; acSaveCurrent: TAction; acUnionFiles: TAction; acDocParams: TAction; acSearch: TAction; tbDocuments: TdxRibbonTab; dxRibbon: TdxRibbon; dxBarManager: TdxBarManager; tbCurrent: TdxRibbonTab; btnOpen: TdxBarLargeButton; dxBarManagerBar1: TdxBar; btnSaveAll: TdxBarButton; btnClearAll: TdxBarButton; dxBarManagerBar2: TdxBar; btnEditDocument: TdxBarLargeButton; btnCheckAll: TdxBarButton; btnUncheckAll: TdxBarButton; btnUnionDocs: TdxBarLargeButton; btnDocParams: TdxBarLargeButton; dxBarManagerBar3: TdxBar; btnPaster: TdxBarLargeButton; btnCopy: TdxBarButton; btnCut: TdxBarButton; dxBarManagerBar4: TdxBar; btnEdit: TdxBarLargeButton; btnAttribEdit: TdxBarLargeButton; btnDeleteElement: TdxBarButton; btnAddChapter: TdxBarButton; btnAddSubChapter: TdxBarButton; btnAddElement: TdxBarLargeButton; dxBarManagerBar5: TdxBar; btnSearch: TdxBarLargeButton; dxBarManagerBar6: TdxBar; btnChangeView: TdxBarLargeButton; LargeImages: TcxImageList; SmallImages: TcxImageList; tbExplorer: TTabSheet; Panel1: TPanel; Splitter1: TSplitter; Panel2: TPanel; cxShellListView1: TcxShellListView; cxShellTreeView1: TcxShellTreeView; dxShellBreadcrumbEdit1: TdxShellBreadcrumbEdit; dxBarManagerBar7: TdxBar; acExplorer: TAction; btnExplorer: TdxBarLargeButton; btnSmartEditor: TdxBarButton; Выделение: TdxRibbonTab; dxBarManagerBar8: TdxBar; acSelectTables: TAction; btnSelectTables: TdxBarLargeButton; acSelectChapters: TAction; btnSelectChapters: TdxBarLargeButton; acSelectSharedTitles: TAction; btnSelectSharedTitles: TdxBarLargeButton; acClearSelection: TAction; btnClearSelection: TdxBarLargeButton; acConfig: TAction; btnEditChapters: TdxBarLargeButton; VST: TVirtualStringTree; btnSelectAllPositions: TdxBarLargeButton; acSelectAllPositions: TAction; btnSelectPositionsFilter: TdxBarLargeButton; acSelectPositionsFilter: TAction; btnSelectedActions: TdxBarLargeButton; acEditSelectedPositions: TAction; acExportToExcel: TAction; btnExportToExcel: TdxBarLargeButton; dxBarManagerBar11: TdxBar; btnSave: TdxBarLargeButton; acExpandAll: TAction; acCollapseAll: TAction; btnCollapseAll: TdxBarButton; btnExpandAll: TdxBarButton; dxBarManagerBar13: TdxBar; procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure lbDocumentList1DblClick(Sender: TObject); procedure acGoBackExecute(Sender: TObject); procedure acGoBackUpdate(Sender: TObject); procedure acEditUpdate(Sender: TObject); procedure acClearExecute(Sender: TObject); procedure acClearUpdate(Sender: TObject); procedure acSaveAllExecute(Sender: TObject); procedure acCheckAllExecute(Sender: TObject); procedure acUncheckAllExecute(Sender: TObject); procedure acOpenExecute(Sender: TObject); procedure acOpenUpdate(Sender: TObject); procedure acCopyExecute(Sender: TObject); procedure acCutExecute(Sender: TObject); procedure acPasteExecute(Sender: TObject); procedure acEditElementExecute(Sender: TObject); procedure acAddElementExecute(Sender: TObject); procedure acDeletePositionExecute(Sender: TObject); procedure acAddChapterExecute(Sender: TObject); procedure acAddSubChapterExecute(Sender: TObject); procedure acCopyUpdate(Sender: TObject); procedure acSmartEditorExecute(Sender: TObject); procedure acPasteUpdate(Sender: TObject); procedure acEditAttributesExecute(Sender: TObject); procedure acSaveCurrentExecute(Sender: TObject); procedure acUnionFilesExecute(Sender: TObject); procedure acDocParamsExecute(Sender: TObject); procedure acSearchExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cxShellListView1ExecuteItem(Sender: TObject; APIDL: PItemIDList; var AHandled: Boolean); procedure acExplorerExecute(Sender: TObject); procedure cxShellListView1DblClick(Sender: TObject); procedure acEditAttributesUpdate(Sender: TObject); procedure acClearSelectionExecute(Sender: TObject); procedure acClearSelectionUpdate(Sender: TObject); procedure acSelectTablesExecute(Sender: TObject); procedure acSelectChaptersExecute(Sender: TObject); procedure acSelectSharedTitlesExecute(Sender: TObject); procedure acConfigExecute(Sender: TObject); procedure acConfigUpdate(Sender: TObject); procedure VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: TImageIndex); procedure VSTNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); procedure VSTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure acEditExecute(Sender: TObject); procedure acSelectAllPositionsExecute(Sender: TObject); procedure acSelectPositionsFilterExecute(Sender: TObject); procedure acEditSelectedPositionsExecute(Sender: TObject); procedure acExportToExcelUpdate(Sender: TObject); procedure acExportToExcelExecute(Sender: TObject); procedure acSmartEditorUpdate(Sender: TObject); procedure acSaveCurrentUpdate(Sender: TObject); procedure VSTBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); procedure acExpandAllExecute(Sender: TObject); procedure acCollapseAllExecute(Sender: TObject); private procedure CreateEditor(D: TGsDocument); procedure ClearEditor; procedure SetChecked(Value: Boolean); procedure AddDocument(D: TGsDocument); procedure UpdateDocInfo(D: TGsDocument); procedure DoOnUpdateDocumens(Sender: TObject); public procedure LoadDocument(AFileName: string); function CurrentEditor: TfrmDocumentEditor; end; TDocumentEditorActionHandler = class(TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var DocumentsEditorForm: TDocumentsEditorForm; implementation uses MdiChilds.Reg, MdiChilds.DocList, MdiChilds.CustomDialog, Settings, MdiChilds.DocParams; type PVSTData = ^TVSTData; TVSTData = record Document: TGsDocument; FileName: string; Index: Integer; end; {$R *.dfm} procedure ColorBlend(const ACanvas: HDC; const ARect: TRect; const ABlendColor: TColor; const ABlendValue: Integer); var DC: HDC; Brush: HBRUSH; Bitmap: HBITMAP; BlendFunction: TBlendFunction; begin DC := CreateCompatibleDC(ACanvas); Bitmap := CreateCompatibleBitmap(ACanvas, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top); Brush := CreateSolidBrush(ColorToRGB(ABlendColor)); try SelectObject(DC, Bitmap); FillRect(DC, Rect(0, 0, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top), Brush); BlendFunction.BlendOp := AC_SRC_OVER; BlendFunction.BlendFlags := 0; BlendFunction.AlphaFormat := 0; BlendFunction.SourceConstantAlpha := ABlendValue; AlphaBlend(ACanvas, ARect.Left, ARect.Top, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top, DC, 0, 0, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top, BlendFunction); finally DeleteObject(Brush); DeleteObject(Bitmap); DeleteDC(DC); end; end; procedure TDocumentsEditorForm.acAddChapterExecute(Sender: TObject); begin with CurrentEditor do TryExecute(CreateChapter); end; procedure TDocumentsEditorForm.acAddElementExecute(Sender: TObject); begin with CurrentEditor do TryExecute(CreateElement); end; procedure TDocumentsEditorForm.acAddSubChapterExecute(Sender: TObject); begin with CurrentEditor do TryExecute(CreateSubChapter); end; procedure TDocumentsEditorForm.acCheckAllExecute(Sender: TObject); begin SetChecked(True); end; procedure TDocumentsEditorForm.acClearExecute(Sender: TObject); begin ClearEditor; GlobalData.Documents.Clear; // lbDocumentList.Clear; VST.Clear; end; procedure TDocumentsEditorForm.acClearSelectionExecute(Sender: TObject); begin CurrentEditor.VST.ClearSelection; end; procedure TDocumentsEditorForm.acClearSelectionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (CurrentEditor <> nil) and (pcMain.ActivePage = tsDocuments); end; procedure TDocumentsEditorForm.acClearUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (pcMain.ActivePage = tsDocumentList) and (VST.RootNodeCount > 0); end; procedure TDocumentsEditorForm.acCollapseAllExecute(Sender: TObject); begin CurrentEditor.VST.FullCollapse; CurrentEditor.VST.Expanded[VST.RootNode] := True; end; procedure TDocumentsEditorForm.acConfigExecute(Sender: TObject); var Fm: TFmChapterEdit; begin Fm := TFmChapterEdit.Create(CurrentEditor); try Fm.InitFromVST(CurrentEditor.VST); Fm.ShowModal; finally Fm.Free; end; end; procedure TDocumentsEditorForm.acConfigUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (CurrentEditor <> nil) and (CurrentEditor.VST.SelectedCount > 0); end; procedure TDocumentsEditorForm.acCopyExecute(Sender: TObject); begin with CurrentEditor do TryExecute(Copy); end; procedure TDocumentsEditorForm.acCopyUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (CurrentEditor <> nil) and (CurrentEditor.VST.SelectedCount > 0) and (pcMain.ActivePage = tsDocuments); end; procedure TDocumentsEditorForm.acCutExecute(Sender: TObject); begin with CurrentEditor do TryExecute(Cut); end; procedure TDocumentsEditorForm.acDeletePositionExecute(Sender: TObject); begin CurrentEditor.RemoveElement; end; procedure TDocumentsEditorForm.acDocParamsExecute(Sender: TObject); var F: TFmDocParams; Node: PVirtualNode; Data: PVSTData; begin // for I := 0 to lbDocumentList.Items.Count - 1 do // if lbDocumentList.Items[I].Checked then // Documents[I].Tag := 1; for Node in VST.CheckedNodes do begin Data := VST.GetNodeData(Node); Data.Document.Tag := 1; end; F := TFmDocParams.CreateForm(True) as TFmDocParams; try F.UserProc := DoOnUpdateDocumens; F.ShowModal; finally F.Free; end; end; procedure TDocumentsEditorForm.acEditElementExecute(Sender: TObject); begin with CurrentEditor do TryExecute(EditElement); end; procedure TDocumentsEditorForm.acEditExecute(Sender: TObject); var Data: PVSTData; Node: PVirtualNode; begin Node := VST.GetFirstSelected; if Node <> nil then begin Data := VST.GetNodeData(Node); pcDocuments.ActivePageIndex := Data.Index; pcMain.ActivePage := tsDocuments; dxRibbon.ActiveTab := tbCurrent; end; end; procedure TDocumentsEditorForm.acEditSelectedPositionsExecute(Sender: TObject); begin CurrentEditor.EditSelectedPositions; end; procedure TDocumentsEditorForm.acEditUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (pcMain.ActivePage = tsDocumentList) and (VST.SelectedCount > 0); end; procedure TDocumentsEditorForm.acExpandAllExecute(Sender: TObject); begin CurrentEditor.VST.FullExpand; end; procedure TDocumentsEditorForm.acExplorerExecute(Sender: TObject); begin pcMain.ActivePage := tbExplorer; end; procedure TDocumentsEditorForm.acExportToExcelExecute(Sender: TObject); begin GlobalData.ExportVirtualStringTreeToExcel(CurrentEditor.VST); end; procedure TDocumentsEditorForm.acExportToExcelUpdate(Sender: TObject); begin acExportToExcel.Enabled := (CurrentEditor <> nil) and (pcMain.ActivePage = tsDocuments); end; procedure TDocumentsEditorForm.acGoBackExecute(Sender: TObject); begin pcMain.ActivePage := tsDocumentList; dxRibbon.ActiveTab := tbDocuments; end; procedure TDocumentsEditorForm.acGoBackUpdate(Sender: TObject); begin acGoBack.Enabled := (pcMain.ActivePage = tsDocuments) or (pcMain.ActivePage = tbExplorer); end; procedure TDocumentsEditorForm.acOpenExecute(Sender: TObject); var I: Integer; h: Boolean; begin if pcMain.ActivePage = tbExplorer then Self.cxShellListView1ExecuteItem(cxShellListView1, nil, h) else begin if OpenDialog.Execute then begin StatusBar.Panels[0].Text := 'Идет загрузка...'; Application.ProcessMessages; for I := 0 to OpenDialog.Files.Count - 1 do LoadDocument(OpenDialog.Files[I]); StatusBar.Panels[0].Text := ''; end; end; end; procedure TDocumentsEditorForm.acOpenUpdate(Sender: TObject); begin acOpen.Enabled := (pcMain.ActivePage = tsDocumentList) or (pcMain.ActivePage = tbExplorer); end; procedure TDocumentsEditorForm.acPasteExecute(Sender: TObject); var Editor: TfrmDocumentEditor; begin Editor := CurrentEditor; if Editor <> nil then Editor.TryExecute(Editor.Paste); end; procedure TDocumentsEditorForm.acPasteUpdate(Sender: TObject); begin acPaste.Enabled := acCopy.Enabled and (GsDocument.Paste <> nil); end; procedure TDocumentsEditorForm.acSaveAllExecute(Sender: TObject); var SD: TSaveDialog; Node: PVirtualNode; Data: PVSTData; begin StatusBar.Panels[0].Text := 'Идет сохранение...'; Application.ProcessMessages; // for I := 0 to Documents.Count - 1 do // if lbDocumentList.Items[I].Checked then // begin // Documents[I].ResourceBulletin.Clear; // if Documents[I].FileName <> '' then // Documents[I].Save // else // begin // SD := TSaveDialog.Create(Application); // try // SD.Filter := 'XML | *.xml'; // SD.DefaultExt := 'xml'; // if SD.Execute then // Documents[I].SaveToFile(SD.FileName); // finally // SD.Free // end; // end; // end; for Node in VST.CheckedNodes do begin Data := VST.GetNodeData(Node); Data.Document.ResourceBulletin.Clear; if Data.Document.FileName <> '' then Data.Document.Save else begin SD := TSaveDialog.Create(Application); try SD.Filter := 'XML | *.xml'; SD.DefaultExt := 'xml'; if SD.Execute then Data.Document.SaveToFile(SD.FileName); finally SD.Free end; end; end; StatusBar.Panels[0].Text := ''; end; procedure TDocumentsEditorForm.acSaveCurrentExecute(Sender: TObject); var SD: TSaveDialog; begin CurrentEditor.Document.ResourceBulletin.Clear; if CurrentEditor.Document.FileName <> '' then CurrentEditor.Document.Save else begin SD := TSaveDialog.Create(Application); try SD.Filter := 'XML | *.xml'; SD.DefaultExt := 'xml'; if SD.Execute then CurrentEditor.Document.SaveToFile(SD.FileName); CurrentEditor.Document.FileName := SD.FileName; finally SD.Free end; end; end; procedure TDocumentsEditorForm.acSaveCurrentUpdate(Sender: TObject); begin acSaveCurrent.Enabled := (CurrentEditor <> nil) and (pcMain.ActivePage = tsDocuments); end; procedure TDocumentsEditorForm.acSearchExecute(Sender: TObject); begin CurrentEditor.acSearch.Execute; end; procedure TDocumentsEditorForm.acSelectAllPositionsExecute(Sender: TObject); begin CurrentEditor.SelectPositions; end; procedure TDocumentsEditorForm.acSelectChaptersExecute(Sender: TObject); begin CurrentEditor.SelectNodes(ctChapter); end; procedure TDocumentsEditorForm.acSelectPositionsFilterExecute(Sender: TObject); begin CurrentEditor.SelectPositionsFilter; end; procedure TDocumentsEditorForm.acSelectSharedTitlesExecute(Sender: TObject); begin CurrentEditor.SelectNodes(ctSharedTitle); end; procedure TDocumentsEditorForm.acSelectTablesExecute(Sender: TObject); begin CurrentEditor.SelectNodes(ctTable); end; procedure TDocumentsEditorForm.acSmartEditorExecute(Sender: TObject); begin CurrentEditor.SmartEditorEnabled := not CurrentEditor.SmartEditorEnabled; end; procedure TDocumentsEditorForm.acSmartEditorUpdate(Sender: TObject); begin acSmartEditor.Enabled := (CurrentEditor <> nil) and (pcMain.ActivePage = tsDocuments); end; procedure TDocumentsEditorForm.acEditAttributesExecute(Sender: TObject); begin with CurrentEditor do TryExecute(EditAttributes); end; procedure TDocumentsEditorForm.acEditAttributesUpdate(Sender: TObject); begin (Sender as TAction).Enabled := (pcMain.ActivePage = tsDocuments); end; procedure TDocumentsEditorForm.acUncheckAllExecute(Sender: TObject); begin SetChecked(False); end; procedure TDocumentsEditorForm.acUnionFilesExecute(Sender: TObject); var J: Integer; NewDocument: TGsDocument; NewItem: TGsAbstractItem; Node: PVirtualNode; Data: PVSTData; begin NewDocument := nil; try // BeginIndex := 0; // while not lbDocumentList.Items[BeginIndex].Checked do // Inc(BeginIndex); // // if BeginIndex > lbDocumentList.Items.Count then // Exit; Node := VST.GetFirstChecked; if Node <> nil then begin Data := VST.GetNodeData(Node); NewDocument := NewGsDocument; NewDocument.Assign(Data.Document); repeat // begin // if not lbDocumentList.Items[I].Checked then // Continue; Node := VST.GetNextChecked(Node); if Node = nil then Break; Data := VST.GetNodeData(Node); if Data.Document.DocumentType <> NewDocument.DocumentType then begin ShowMessage('Не совпадают типы документов. Объединение будет завершено.'); raise Exception.Create('Не совпадает тип документов.'); end; if Data.Document.DocumentType = dtPrice then begin for J := 0 to Data.Document.Workers.Count - 1 do begin NewItem := TGsAbstractItem.CreateCompatibleObject(Data.Document.Workers.Items[J]); NewItem.Assign(Data.Document.Workers.Items[J]); NewDocument.Workers.Add(NewItem); end; for J := 0 to Data.Document.Materials.Count - 1 do begin NewItem := TGsAbstractItem.CreateCompatibleObject(Data.Document.Materials.Items[J]); NewItem.Assign(Data.Document.Materials.Items[J]); NewDocument.Materials.Add(NewItem); end; for J := 0 to Data.Document.Mashines.Count - 1 do begin NewItem := TGsAbstractItem.CreateCompatibleObject(Data.Document.Mashines.Items[J]); NewItem.Assign(Data.Document.Mashines.Items[J]); NewDocument.Mashines.Add(NewItem); end; for J := 0 to Data.Document.Mechanics.Count - 1 do begin NewItem := TGsAbstractItem.CreateCompatibleObject(Data.Document.Mechanics.Items[J]); NewItem.Assign(Data.Document.Mechanics.Items[J]); NewDocument.Mechanics.Add(NewItem); end; end else begin NewDocument.Number := ''; if NewDocument.BaseDataType <> Data.Document.BaseDataType then begin ShowMessage('Документы должны быть одного формата. Объединение будет завершено'); raise Exception.Create('Отличается формат'); end; for J := 0 to Data.Document.Chapters.Count - 1 do begin NewItem := TGsAbstractItem.CreateCompatibleObject(Data.Document.Chapters.Items[J]); NewItem.Assign(Data.Document.Chapters.Items[J]); NewDocument.Chapters.Add(NewItem); end; end; until Node = nil; AddDocument(NewDocument); end; except NewDocument.Free; end; end; procedure TDocumentsEditorForm.AddDocument(D: TGsDocument); begin GlobalData.Documents.Add(D); UpdateDocInfo(D); CreateEditor(D); end; procedure TDocumentsEditorForm.ClearEditor; begin while pcDocuments.PageCount > 0 do pcDocuments.Pages[0].Free; end; procedure TDocumentsEditorForm.CreateEditor(D: TGsDocument); var Page: TTabSheet; Editor: TfrmDocumentEditor; Item: TMenuItem; I: Integer; begin Page := TTabSheet.Create(pcDocuments); Page.PageControl := pcDocuments; if D.FileName <> '' then Page.Caption := ExtractFileName(D.FileName) else Page.Caption := D.LocalName; Editor := TfrmDocumentEditor.Create(Page); Editor.Parent := Page; Editor.Align := alClient; Editor.Document := D; // Editor.PopupMenu.Images := Self.SmallImages; for I := 7 to amMain.ActionCount - 1 do begin Item := TMenuItem.Create(Editor.PopupMenu); Item.Action := amMain.Actions[I]; Editor.PopupMenu.Items.Add(Item); end; end; function TDocumentsEditorForm.CurrentEditor: TfrmDocumentEditor; begin Result := nil; if pcDocuments.PageCount > 0 then Result := pcDocuments.ActivePage.Components[0] as TfrmDocumentEditor; end; procedure TDocumentsEditorForm.cxShellListView1DblClick(Sender: TObject); var h: Boolean; begin cxShellListView1ExecuteItem(cxShellListView1, nil, h); end; procedure TDocumentsEditorForm.cxShellListView1ExecuteItem(Sender: TObject; APIDL: PItemIDList; var AHandled: Boolean); var I: Integer; J: Integer; Finded: Boolean; Loaded: Boolean; begin Loaded := False; for I := 0 to cxShellListView1.SelectedFilePaths.Count - 1 do begin Finded := False; for J := 0 to Documents.Count - 1 do begin if Documents[J].FileName = cxShellListView1.SelectedFilePaths[I] then begin Finded := True; Break; end; end; if not Finded then begin LoadDocument(cxShellListView1.SelectedFilePaths[I]); Loaded := True; end; end; if Loaded then pcMain.ActivePage := tsDocumentList; end; procedure TDocumentsEditorForm.DoOnUpdateDocumens(Sender: TObject); begin // //lbDocumentList.Clear; // for I := 0 to Documents.Count - 1 do // begin // UpdateDocInfo(Documents[I]); // if Documents[I].Tag <> 0 then // begin // TfrmDocumentEditor(pcDocuments.Pages[I].Components[0]).UpdateContent; // Documents[I].Tag := 0; // end; // end; // Application.ProcessMessages; end; procedure TDocumentsEditorForm.FormClose(Sender: TObject; var Action: TCloseAction); begin ClearEditor; // Application.MainForm.Enabled := True; // lbDocumentList.Clear; VST.Clear; // SetForegroundWindow(Application.MainFormHandle); Action := caFree; GlobalData.Documents.Clear; // if Settings.Properties.TryGetValue('remote', Value) then // Application.Terminate; end; procedure TDocumentsEditorForm.FormCreate(Sender: TObject); begin dxRibbon.ActiveTab := tbDocuments; end; procedure TDocumentsEditorForm.FormDestroy(Sender: TObject); begin GlobalData.Documents.Clear; end; procedure TDocumentsEditorForm.FormShow(Sender: TObject); begin // Application.MainForm.Enabled := False; pcMain.ActivePage := tsDocumentList; end; procedure TDocumentsEditorForm.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); var I: Integer; begin GlobalData.Documents.Clear; // lbDocumentList.Clear; VST.Clear; StatusBar.Panels[0].Text := 'Идет загрузка...'; Application.ProcessMessages; ClearEditor; for I := 0 to Value.Count - 1 do if AnsiUpperCase(ExtractFileExt(Value[I])) = '.XML' then LoadDocument(Value[I]); StatusBar.Panels[0].Text := ''; end; procedure TDocumentsEditorForm.lbDocumentList1DblClick(Sender: TObject); begin // if lbDocumentList.Selected <> nil then // begin // pcDocuments.ActivePageIndex := lbDocumentList.Selected.Index; // pcMain.ActivePage := tsDocuments; // dxRibbon.ActiveTab := tbCurrent; // end; end; procedure TDocumentsEditorForm.LoadDocument(AFileName: string); var D: TGsDocument; begin D := NewGsDocument; try D.LoadFromFile(AFileName); AddDocument(D); except on E: Exception do MdiChilds.CustomDialog.TFmProcess.MessageBoxError(E.Message); end; end; procedure TDocumentsEditorForm.SetChecked(Value: Boolean); var CS: VirtualTrees.TCheckState; begin // for I := 0 to lbDocumentList.Items.Count - 1 do // begin // lbDocumentList.Items[I].Checked := Value; // end; if Value then CS := csCheckedNormal else CS := csUncheckedNormal; VST.SetCheckStateForAll(CS, False); end; procedure TDocumentsEditorForm.UpdateDocInfo(D: TGsDocument); var // Item: TListItem; Node: PVirtualNode; Data: PVSTData; begin Node := VST.AddChild(nil); Data := VST.GetNodeData(Node); Data.Document := D; if D.FileName <> '' then Data.FileName := ExtractFileName(D.FileName) else Data.FileName := D.LocalName; Data.Index := Documents.Count - 1; // Item := lbDocumentList.Items.Add; // if D.FileName <> '' then // Item.Caption := ExtractFileName(D.FileName) // else // Item.Caption := D.LocalName; // Item.Checked := True; // Item.ImageIndex := 0; // case D.DocumentType of // dtPrice: // begin // Item.SubItems.Add('Ценник'); // end; // dtIndex: // Item.SubItems.Add('Индексы'); // dtBaseData: // begin // // Item.SubItems.Add('Нормативный'); // // case D.BaseDataType of // bdtMachine: // Item.SubItems.Add('Машины'); // bdtMaterial: // Item.SubItems.Add('Материалы'); // bdtERs: // Item.SubItems.Add('Расценки'); // bdtRows: // Item.SubItems.Add('Расценки*'); // bdtESNs: // Item.SubItems.Add('Нормы'); // bdtWorkerScale: // Item.SubItems.Add('Трудозатраты'); // bdtCargo: // Item.SubItems.Add('Перевозки'); // bdtProject: // Item.SubItems.Add('Проектный'); // end; // Item.SubItems.Add(D.TypeAndNumber); // end; // end; end; procedure TDocumentsEditorForm.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var Data: PVSTData; begin Data := Sender.GetNodeData(Node); CellText := ''; case Column of 0: CellText := Data.FileName; 1: begin case Data.Document.DocumentType of dtBaseData: CellText := 'Формат базы'; dtPrice: CellText := 'Ценник'; dtIndex: CellText := 'Индексы'; end; end; 2: begin if Data.Document.DocumentType = dtBaseData then case Data.Document.BaseDataType of bdtMachine: CellText := 'Машины'; bdtMaterial: CellText := 'Материалы'; bdtERs, bdtRows: CellText := 'Расценки'; bdtESNs: CellText := 'Нормы'; bdtWorkerScale: CellText := 'Трудозатраты'; bdtCargo: CellText := 'Перевозки'; bdtProject: CellText := 'Проектный'; end; end; 3: begin if Data.Document.DocumentType = dtBaseData then CellText := Data.Document.TypeAndNumber; end; end; end; procedure TDocumentsEditorForm.VSTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin Node.CheckType := ctCheckBox; Node.CheckState := csCheckedNormal; end; procedure TDocumentsEditorForm.VSTNodeDblClick(Sender: TBaseVirtualTree; const HitInfo: THitInfo); var Data: PVSTData; begin Data := Sender.GetNodeData(HitInfo.HitNode); pcDocuments.ActivePageIndex := Data.Index; pcMain.ActivePage := tsDocuments; dxRibbon.ActiveTab := tbCurrent; end; procedure TDocumentsEditorForm.VSTBeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); var BlendColor: TColor; BlendValue: Integer; begin BlendColor := $000000; if CellPaintMode = cpmPaint then begin case Column of 0: BlendColor := $00AA00; 1: BlendColor := $000800; 2: BlendColor := $000200; end; BlendValue := 15; if VirtualTrees.MMXAvailable then ColorBlend(TargetCanvas.Handle, CellRect, BlendColor, BlendValue) // else // AlphaBlend(0, TargetCanvas.Handle, CellRect, Point(0, 0), // bmConstantAlphaAndColor, BlendValue, ColorToRGB(BlendColor)); end; end; procedure TDocumentsEditorForm.VSTFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PVSTData; begin Data := VST.GetNodeData(Node); Data.Document := nil; Data.FileName := ''; Data.Index := -1; end; procedure TDocumentsEditorForm.VSTGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: TImageIndex); begin if Kind in [ikNormal, ikSelected] then begin if Column = 0 then begin ImageIndex := 10 end else ImageIndex := -1; end; end; procedure TDocumentsEditorForm.VSTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TVSTData); end; { TDocumentEditorActionHandler } procedure TDocumentEditorActionHandler.ExecuteAction; begin TDocumentsEditorForm.Create(Application).ShowModal; end; begin ActionHandlerManager.RegisterActionHandler('Визуальный редактор', hkDefault, TDocumentEditorActionHandler); end.
unit BackTiler; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buffer, WinUtils, VCLUtils; type TBackgroundTiler = class( TComponent ) protected fTile : TSpeedBitmap; procedure SetTile( aTile : TSpeedBitmap ); virtual; published property Tile : TSpeedBitmap read fTile write SetTile; public procedure AddControl( aControl : TWinControl ); virtual; end; procedure Register; implementation type PWndProcInfo = ^TWndProcInfo; TWndProcInfo = record Control : TBackgroundTiler; FormOrigin : TPoint; TileStart : TPoint; TileBitmap : TSpeedBitmap; HookedControl : TWinControl; Rect : TRect; Handle : HWND; WndProcData : integer; end; var fWindows : TList; function EraseWndProc( WinHandle : HWND; Msg : integer; wPar : WPARAM; lPar : LPARAM ) : LRESULT; stdcall; var i : integer; CtlOrigin : TPoint; Info : TWndProcInfo; begin try i := 0; while ( i < fWindows.Count ) and ( PWndProcInfo( fWindows.Items[i] ).Handle <> WinHandle ) do inc( i ); Info := PWndProcInfo( fWindows.Items[i] )^; with PWndProcInfo( fWindows.Items[i] )^ do case Msg of WM_ERASEBKGND : begin // Tile background TileBitmap.TileOnDC( wPar, TileStart.x, TileStart.y, Rect, cmSrcCopy ); Result := 1; end; WM_MOVE : begin Result := CallWindowProc( PrevWndProc( WndProcData ), WinHandle, Msg, wPar, lPar ); // Update TileStart CtlOrigin := HookedControl.ClientOrigin; with TileStart do begin x := FormOrigin.x - CtlOrigin.x; y := FormOrigin.y - CtlOrigin.y; end; end; else Result := CallWindowProc( PrevWndProc( WndProcData ), WinHandle, Msg, wPar, lPar ); end; except Result := 0; end; end; var fFormOrigin : TPoint; procedure AddControlHook( aControl : TBackgroundTiler; aHookedControl : TWinControl ); var Info : PWndProcInfo; CtlOrigin : TPoint; begin with fWindows do begin new( Info ); with Info^ do begin Control := aControl; TileBitmap := aControl.fTile; FormOrigin := fFormOrigin; CtlOrigin := aHookedControl.ClientOrigin; Rect := aHookedControl.ClientRect; with TileStart do begin x := FormOrigin.x - CtlOrigin.x; y := FormOrigin.y - CtlOrigin.y; end; HookedControl := aHookedControl; Handle := HookedControl.Handle; WndProcData := ChangeWndProc( Handle, @EraseWndProc ); end; fWindows.Add( Info ); end; end; // Hook all children of 'aParent' procedure HookControl( aControl : TBackgroundTiler; aParent: TWinControl ); var i : integer; begin try fFormOrigin := GetParentForm( aParent ).ClientOrigin; for i := 0 to aParent.ControlCount - 1 do if TWinControl( aParent.Controls[i] ).Visible then AddControlHook( aControl, aParent ); except end; end; procedure ClearControlHooks( aControl : TBackgroundTiler ); var i : integer; begin with fWindows do begin i := Count - 1; while i >= 0 do with PWndProcInfo( Items[i] )^ do begin if Control = aControl then begin RestoreWndProc( Handle, WndProcData ); dispose( Items[i] ); Delete( i ); end; dec( i ); end; end; end; // TBackgroundTiler procedure TBackgroundTiler.SetTile( aTile : TSpeedBitmap ); begin fTile := aTile; fTile.IgnorePalette := true; end; procedure TBackgroundTiler.AddControl( aControl : TWinControl ); begin fFormOrigin := GetParentForm( aControl ).ClientOrigin; AddControlHook( Self, aControl ); end; procedure Register; begin RegisterComponents( 'Merchise', [TBackgroundTiler] ); end; initialization fWindows := TList.Create; finalization fWindows.Free; end.
unit ProDoc; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ImgList, ActnList, Menus, Db, DBTables, Grids, DBGrids, ComCtrls, DBCtrls, ToolWin, StdCtrls, DBActns, Errores; type TInfo = function( PProve: PChar; lCancel, Vista: boolean ):boolean; StdCall; TFProDoc = class(TForm) MainMenu1: TMainMenu; Ventana1: TMenuItem; Cerrar1: TMenuItem; ActionList1: TActionList; Panel1: TPanel; DBGrid1: TDBGrid; DataSource1: TDataSource; Table1: TTable; CoolBar1: TCoolBar; ToolBar1: TToolBar; Cerrar: TAction; Imprimir: TAction; Ayuda: TAction; ToolButton1: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; Registros1: TMenuItem; Imprimir1: TMenuItem; Ayuda1: TMenuItem; Ayuda2: TMenuItem; Cancelados: TAction; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ToolButton9: TToolButton; Primero1: TMenuItem; Anterior1: TMenuItem; Siguiente1: TMenuItem; Ultimo1: TMenuItem; StatusBar1: TStatusBar; Panel2: TPanel; Saldo: TLabel; Total: TLabel; Documentos1: TMenuItem; DocumentosCancelados1: TMenuItem; AnalisisdeCuentaDocumentada1: TMenuItem; Analisis: TAction; Table1Numero: TAutoIncField; Table1Vencto: TDateTimeField; Table1Importe: TFloatField; Table1PesDol: TBooleanField; Table1Coeficiente: TFloatField; Table1Proveedor: TStringField; Table1CodiPag: TStringField; Table1OPago: TStringField; Table1Saldo: TFloatField; Table1Pago: TDateTimeField; Table1Cancelado: TStringField; Table1Codigo: TStringField; Table1CodPago: TStringField; Table1OPPago: TStringField; ToolButton2: TToolButton; ToolButton5: TToolButton; procedure CerrarExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DataSource1DataChange(Sender: TObject; Field: TField); procedure Primero1Click(Sender: TObject); procedure Anterior1Click(Sender: TObject); procedure Siguiente1Click(Sender: TObject); procedure Ultimo1Click(Sender: TObject); procedure AyudaExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure AnalisisExecute(Sender: TObject); procedure DocumentosCancelados1Click(Sender: TObject); procedure ImprimirExecute(Sender: TObject); private { Private declarations } lEsNegro: boolean; lCancelada: boolean; sProve: string; PInfo: TInfo; procedure EnHint(Sender: TObject); public { Public declarations } procedure SetCli( sCod, sNom: string; lCancel: boolean ); end; var FProDoc: TFProDoc; implementation uses DetDoc, Main, Informes; {$R *.DFM} procedure TFProDoc.CerrarExecute(Sender: TObject); begin Close; end; procedure TFProDoc.FormCreate(Sender: TObject); begin lEsNegro := false; Application.OnHint := EnHint; Table1.Open; end; procedure TFProDoc.DataSource1DataChange(Sender: TObject; Field: TField); var UpEnable, DnEnable: boolean; begin if DataSource1.DataSet.Active then begin UpEnable := not DataSource1.DataSet.bof; DnEnable := not DataSource1.DataSet.eof; Primero1.Enabled := UpEnable; Anterior1.Enabled := UpEnable; Siguiente1.Enabled := DnEnable; Ultimo1.Enabled := DnEnable; end else begin Primero1.Enabled := false; Anterior1.Enabled := false; Siguiente1.Enabled := false; Ultimo1.Enabled := false; end; end; procedure TFProDoc.Primero1Click(Sender: TObject); begin DataSource1.DataSet.First; end; procedure TFProDoc.Anterior1Click(Sender: TObject); begin DataSource1.DataSet.Prior; end; procedure TFProDoc.Siguiente1Click(Sender: TObject); begin DataSource1.DataSet.Next; end; procedure TFProDoc.Ultimo1Click(Sender: TObject); begin DataSource1.DataSet.Last; end; procedure TFProDoc.EnHint(Sender: TObject); begin StatusBar1.SimpleText := Application.Hint; end; procedure TFProDoc.AyudaExecute(Sender: TObject); begin Application.HelpCommand( HELP_CONTENTS, 0 ); end; procedure TFProDoc.FormClose(Sender: TObject; var Action: TCloseAction); begin Application.OnHint := nil; Action := caFree; FProDoc := nil; end; procedure TFProDoc.SetCli(sCod, sNom: string; lCancel: boolean ); var nSaldo: double; begin sProve := sCod; Table1.DisableControls; lCancelada := lCancel; if lCancel then begin Caption := 'Documentos Cancelados: ' + sNom; Table1.SetRange( [ 'S', sCod ], [ 'S', sCod ] ); Table1.first; nSaldo := 0; while not Table1.eof do begin nSaldo := nSaldo + ( Table1IMPORTE.value * Table1COEFICIENTE.value ); Table1.next; end; Total.Caption := format( '%12.2m', [ nSaldo ] ); end else begin Caption := 'Documentos de ' + sNom; Table1.SetRange( [ 'N', sCod ], [ 'N', sCod ] ); end; Table1.EnableControls; end; procedure TFProDoc.AnalisisExecute(Sender: TObject); begin FDetDoc := TFDetDoc.create( self ); try FDetDoc.SetFiltro( sProve, lEsNegro ); FDetDoc.ShowModal; finally FDetDoc.free; end; end; procedure TFProDoc.DocumentosCancelados1Click(Sender: TObject); begin // Caption := 'Documentos de ' + sNom; // Table1.SetRange( [ 'N', sCod ], [ 'N', sCod ] ); end; procedure TFProDoc.ImprimirExecute(Sender: TObject); begin VerInforme( 'DocAPagarProve.rtm', Table1 ); end; end.
unit tdMessageSend; interface uses System.Classes, System.RegularExpressions, Winapi.Windows, System.SysUtils, System.SyncObjs, Vcl.ComCtrls, Vcl.StdCtrls, ADC.Common; type TMessageSendParam = record ExeName: string; Process_Timeout: Integer; Process_ShowWindow: Boolean; UseCredentials: Boolean; User: string; Password: string; Message_Recipient: string; Message_Text: string; Message_Timeout: Integer; end; TMessageSendOutputProc = procedure (ASender: TThread; AOutput: string) of object; TMessageSendExceptionProc = procedure (ASender: TThread; AMessage: string) of object; type TMessageSendThread = class(TThread) private { Private declarations } FSyncObject: TCriticalSection; FhProcess: THandle; FExeName: string; FShowWindow: Boolean; FProcTimeout: Integer; FUseCredentials: Boolean; FUser: string; FPassword: string; FRecipient: string; FMessage: string; FMsgTimeout: Integer; FProcessOutput: AnsiString; FErrMessage: string; FCmdLine: string; FBatchFile: TFileName; FLog: TStringList; FOnProcessOutput: TMessageSendOutputProc; FOnException: TMessageSendExceptionProc; function ErrorToString(CommentStr: string; Error: Integer = 0): string; procedure PrepareCommandLine; procedure PrepareProcessOutput(ASecurityAttr: PSecurityAttributes; var InputRead, InputWrite, OutputRead, OutputWrite, ErrorWrite: THandle); function GetProcessOutputText(AOutputRead: THandle): string; function CreateBatchFile(const FileName, BatchCommand : string): TFileName; procedure SyncOutput; procedure SyncException; protected procedure Execute; override; procedure DoOutput(AOutput: AnsiString); procedure DoException(AMessage: string); public constructor Create(AParam: TMessageSendParam; ASyncObject: TCriticalSection); destructor Destroy; override; property hProcess: THandle read FhProcess; property OnProcessOutput: TMessageSendOutputProc read FOnProcessOutput write FOnProcessOutput; property OnException: TMessageSendExceptionProc read FOnException write FOnException; end; implementation { TPsExecThread } constructor TMessageSendThread.Create(AParam: TMessageSendParam; ASyncObject: TCriticalSection); begin inherited Create(True); FreeOnTerminate := True; FLog := TStringList.Create; FSyncObject := ASyncObject; FExeName := AParam.ExeName; FShowWindow := AParam.Process_ShowWindow; FUseCredentials := AParam.UseCredentials; FUser := AParam.User; FPassword := AParam.Password; FMessage := AParam.Message_Text; FRecipient := AParam.Message_Recipient; FMsgTimeout := AParam.Message_Timeout; case AParam.Process_Timeout > 0 of True : FProcTimeout := AParam.Process_Timeout * 60000; False: FProcTimeout := INFINITE; end; if FShowWindow then FProcTimeout := INFINITE; end; procedure TMessageSendThread.Execute; var OutputRead, OutputWrite: THandle; InputRead, InputWrite: THandle; ErrorWrite: THandle; StartInfo: TStartupInfo; ProcessInfo: TProcessInformation; waitResult: Cardinal; resSuccess: Boolean; SA: TSecurityAttributes; begin if FSyncObject <> nil then if not FSyncObject.TryEnter then begin FSyncObject := nil; Self.OnTerminate := nil; Exit; end; FLog.Add( #13#10 + 'Конфигурирование параметров безопасности...' ); DoOutput(FLog.Text); with SA do begin nLength := SizeOf(SECURITY_ATTRIBUTES); bInheritHandle := True; lpSecurityDescriptor := nil; end; FillChar(StartInfo, SizeOf(TStartupInfo), #0); FillChar(ProcessInfo, SizeOf(TProcessInformation), #0); try if not FShowWindow then PrepareProcessOutput( @SA, InputRead, InputWrite, OutputRead, OutputWrite, ErrorWrite ); with StartInfo do begin cb := SizeOf(TStartupInfo); dwFlags := STARTF_USESHOWWINDOW; case FShowWindow of True: begin wShowWindow := SW_SHOWNORMAL; end; False: begin dwFlags := dwFlags or STARTF_USESTDHANDLES; wShowWindow := SW_HIDE; hStdInput := InputRead; hStdOutput := OutputWrite; hStdError := ErrorWrite; end; end; end; FLog.Add( #13#10 + 'Отправка сообщения на ' + FRecipient + '...' ); DoOutput(FLog.Text); PrepareCommandLine; resSuccess := CreateProcess( nil, PChar(FCmdLine), @SA, @SA, not FShowWindow, CREATE_NEW_CONSOLE, nil, nil, StartInfo, ProcessInfo ); if not resSuccess then raise Exception.Create(ErrorToString('CreateProcess', GetLastError)); FhProcess := ProcessInfo.hProcess; waitResult := WaitForSingleObject(ProcessInfo.hProcess, FProcTimeout); case waitResult of WAIT_TIMEOUT : begin TerminateProcess(ProcessInfo.hProcess, 0); raise Exception.Create('Время ожидания завершения процесса истекло.'); end; WAIT_FAILED : begin TerminateProcess(ProcessInfo.hProcess, 0); raise Exception.Create(ErrorToString('WaitForSingleObject', GetLastError)); end; end; FLog.Add( #13#10 + 'Операция выполнена.' ); if not FShowWindow then DoOutput(GetProcessOutputText(OutputRead)) else DoOutput(FLog.Text); except on E: Exception do begin FLog.Add( #13#10 + E.Message ); DoOutput(FLog.Text); DoException(E.Message); end; end; FhProcess := 0; if FileExists(FBatchFile) then DeleteFile(FBatchFile); FBatchFile := ''; CloseHandle(OutputRead); CloseHandle(OutputWrite); CloseHandle(InputRead); CloseHandle(InputWrite); CloseHandle(ErrorWrite); CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); if FSyncObject <> nil then begin FSyncObject.Leave; FSyncObject := nil; end; end; function TMessageSendThread.GetProcessOutputText( AOutputRead: THandle): string; const BufferSize = 1048576; var Buffer: PAnsiChar; BytesRead: DWORD; res: Boolean; BytesCount: Integer; sOutput: AnsiString; begin Buffer := AllocMem(BufferSize); repeat BytesCount := 0; BytesRead := 0; res := ReadFile(AOutputRead, Buffer[0], BufferSize, BytesRead, nil); if (not res) or (BytesRead = 0) or (Terminated) then Break; Buffer[BytesRead] := #0; while BytesCount < BytesRead do begin sOutput := sOutput + Buffer[BytesCount]; BytesCount := BytesCount + 1; sOutput := sOutput + Buffer[BytesCount]; BytesCount := BytesCount + 1; { Если текущий #13 и следующий #13 или #10, то пропускаем их } { увеличивая счетчик прочтенных байт еще на 1 } if (Buffer[BytesCount] = #13) then if (Buffer[BytesCount + 1] = #10) or (Buffer[BytesCount + 1] = #13) then BytesCount := BytesCount + 1 end; until True; FreeMem(Buffer, BufferSize); Result := sOutput; end; procedure TMessageSendThread.PrepareCommandLine; begin FCmdLine := Format('"%s" /accepteula \\%s ', [FExeName, FRecipient]); if FUseCredentials then begin FCmdLine := FCmdLine + Format('-u %s -p %s ', [FUser, FPassword]); end; case FMsgTimeout = 0 of True : FCmdLine := FCmdLine + Format('msg * "%s"', [FMessage]); False: FCmdLine := FCmdLine + Format('msg /time:%d * "%s"', [FMsgTimeout, FMessage]); end; if FShowWindow then begin FBatchFile := CreateBatchFile('psexec.bat', FCmdLine); FCmdLine := Format('cmd /a /k "%s"', [FBatchFile]); end; end; procedure TMessageSendThread.PrepareProcessOutput(ASecurityAttr: PSecurityAttributes; var InputRead, InputWrite, OutputRead, OutputWrite, ErrorWrite: THandle); var OutputReadTmp: THandle; InputWriteTmp: THandle; res: Boolean; begin try res := CreatePipe(OutputReadTmp, OutputWrite, ASecurityAttr, 0); if not res then raise Exception.Create(ErrorToString('CreatePipe', GetLastError)); res := DuplicateHandle( GetCurrentProcess(), OutputWrite, GetCurrentProcess(), @ErrorWrite, 0, True, DUPLICATE_SAME_ACCESS ); if not res then raise Exception.Create(ErrorToString('DuplicateHandle', GetLastError)); res := CreatePipe(InputRead, InputWriteTmp, ASecurityAttr, 0); if not res then raise Exception.Create(ErrorToString('CreatePipe', GetLastError)); res := DuplicateHandle( GetCurrentProcess(), OutputReadTmp, GetCurrentProcess(), @OutputRead, 0, False, DUPLICATE_SAME_ACCESS ); if not res then raise Exception.Create(ErrorToString('DuplicateHandle', GetLastError)); res := DuplicateHandle( GetCurrentProcess(), InputWriteTmp, GetCurrentProcess(), @InputWrite, 0, False, DUPLICATE_SAME_ACCESS ); if not res then raise Exception.Create(ErrorToString('DuplicateHandle', GetLastError)); finally CloseHandle(OutputReadTmp); CloseHandle(InputWriteTmp); end; end; procedure TMessageSendThread.SyncException; begin if Assigned(FOnException) then FOnException(Self, FErrMessage); end; procedure TMessageSendThread.SyncOutput; begin if Assigned(FOnProcessOutput) then FOnProcessOutput(Self, FProcessOutput); end; function TMessageSendThread.CreateBatchFile(const FileName, BatchCommand : string): TFileName; var Stream: TFileStream; BatchFile: TFileName; BatchCmd: AnsiString; begin Result := ''; BatchFile := TempDirPath + FileName; BatchCmd := '@echo off' + #13#10 + 'chcp 1251 >nul' + #13#10 + BatchCommand + #13#10 + '@echo on'; Stream:= TFileStream.Create(BatchFile, fmCreate); try Stream.WriteBuffer(Pointer(BatchCmd)^, Length(BatchCmd)); Result := BatchFile; finally Stream.Free; end; end; destructor TMessageSendThread.Destroy; begin FLog.Free; inherited; end; procedure TMessageSendThread.DoException(AMessage: string); begin FErrMessage := AMessage; Synchronize(SyncException); end; procedure TMessageSendThread.DoOutput(AOutput: AnsiString); begin FProcessOutput := AOutput; Synchronize(SyncOutput); end; function TMessageSendThread.ErrorToString(CommentStr: string; Error: Integer = 0): string; const ErrorMessage: string = '%s [%d] - %s'; var Buffer: PChar; begin if Error = 0 then Error := GetLastError; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM, nil, Error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), @Buffer, 0, nil ); Result := Format(ErrorMessage, [CommentStr, Error, string(Buffer)]); end; end.
var a,b,c,x1,x2,y1,y2,x,y,g,t,xmin,xmax,ym:int64; function gcd(a,b:int64):int64; begin if b=0 then begin gcd:=a; x:=1; y:=0; exit; end; gcd:=gcd(b,a mod b); t:=x; x:=y; y:=t-a div b*y; end; begin read(a,b,c,x1,x2,y1,y2); if (a=0) and (b=0) then begin if c<>0 then writeln(0) else writeln((y2-y1+1)*(x2-x1+1)); halt; end; if a=0 then begin if (c mod b=0) and (-c div b>=y1) and (-c div b<=y2) then writeln(x2-x1+1) else writeln(0); halt; end; if b=0 then begin if (c mod a=0) and (-c div a>=x1) and (-c div a<=x2) then writeln(y2-y1+1) else writeln(0); halt; end; if a<0 then begin a:=-a; ym:=-x1; x1:=-x2; x2:=ym; end; if b<0 then begin b:=-b; ym:=-y1; y1:=-y2; y2:=ym; end; g:=gcd(a,b); if c mod g<>0 then begin writeln(0); halt; end; x:=x*-c div g; y:=y*-c div g; a:=a div g; b:=b div g; xmin:=(x1-x) div b*b+x; if x1>xmin then inc(xmin,b); xmax:=(x2-x) div b*b+x; if xmax>x2 then dec(xmax,b); if a*b>0 then begin ym:=x+(y-y2) div a*b; if y2<y-(y-y2) div a*a then inc(ym,b); end else begin ym:=x+(y-y1) div a*b; if y1>y-(y-y1) div a*a then inc(ym,b); end; if ym>xmin then xmin:=ym; if a*b>0 then begin ym:=x+(y-y1) div a*b; if y1>y-(y-y1) div a*a then dec(ym,b); end else begin ym:=x+(y-y2) div a*b; if y2<y-(y-y2) div a*a then dec(ym,b); end; if ym<xmax then xmax:=ym; ym:=(xmax-xmin) div b+1; if ym<0 then ym:=0; writeln(ym); end.
//============================================================================= // sgUserInterface.pas //============================================================================= // // Version 0.1 - Resposible for constructing User Interfaces in // SwinGame projects.. eventually. // // Change History: // // Version 3: // - 2010-01-19: Cooldave : Textboxes, Buttons, Checkboxes, Radiobuttons, Labels all fully functional. // Lists are almost completed. Can be created and used, and items can be added at runtime. // Need to add the ability to remove items from lists. // - 2009-12-18: Cooldave : Ability to create panels... no regions, just panels. // They can be drawn as rectangles and read from file. //============================================================================= {$I sgTrace.inc} unit sgUserInterface; //============================================================================= interface uses sgTypes; //============================================================================= type Panel = ^PanelData; Region = ^RegionData; GUILabel = ^GUILabelData; GUICheckbox = ^GUICheckboxData; GUIRadioGroup = ^GUIRadioGroupData; GUITextBox = ^GUITextBoxData; GUIList = ^GUIListData; GuiElementKind = ( gkLabel = 1, gkButton = 2, gkCheckBox = 4, gkRadioGroup = 8, gkTextBox = 16, gkList = 32, gkAnyKind = 63 // = (1 or 2 or 4 or 8 or 16 or 32) ); EventKind = ( ekClicked, ekTextEntryEnded, ekSelectionMade ); GUIEventCallback = procedure (r: Region; kind: EventKind); GUITextBoxData = packed record contentString: String; font: Font; lengthLimit: LongInt; region: Region; alignment: FontAlignment; end; GUILabelData = packed record contentString: String; font: Font; alignment: FontAlignment; end; /// Each list item has text and an image GUIListItem = packed record text: String; image: BitmapCell; parent: GUIList; end; GUIListData = packed record verticalScroll: Boolean; //The areas for the up/left down/right scrolling buttons scrollUp: Rectangle; scrollDown: Rectangle; scrollArea: Rectangle; columns: LongInt; rows: LongInt; rowHeight: LongInt; colWidth: LongInt; scrollSize: LongInt; placeholder: Array of Rectangle; activeItem: LongInt; startingAt: LongInt; font: Font; items: Array of GUIListItem; scrollButton: Bitmap; alignment: FontAlignment; end; GUIRadioGroupData = packed record groupID: string; buttons: Array of Region; activeButton: LongInt; end; GUICheckboxData = packed record state: boolean; end; RegionData = packed record stringID: String; kind: GUIElementKind; regionIdx: LongInt; elementIndex: LongInt; area: Rectangle; active: Boolean; parent: Panel; callbacks: Array of GUIEventCallback; end; PanelData = packed record name: String; filename: String; panelID: LongInt; area: Rectangle; visible: Boolean; active: Boolean; draggable: Boolean; // The panel's bitmaps panelBitmap: Bitmap; panelBitmapInactive: Bitmap; panelBitmapActive: Bitmap; // The regions within the Panel regions: Array of RegionData; regionIds: NamedIndexCollection; // The extra details for the different kinds of controls labels: Array of GUILabelData; checkBoxes: Array of GUICheckboxData; radioGroups: Array of GUIRadioGroupData; textBoxes: Array of GUITextBoxData; lists: Array of GUIListData; modal: Boolean; // A panel that is modal blocks events from panels shown earlier. // Event callback mechanisms DrawAsVectors: Boolean; end; FileDialogSelectType = ( fdFiles = 1, fdDirectories = 2, fdFilesAndDirectories = 3 // = (1 or 2) ); //--------------------------------------------------------------------------- // Alter GUI global values //--------------------------------------------------------------------------- procedure GUISetForegroundColor(c:Color); procedure GUISetBackgroundColor(c:Color); /// Returns true if any of the panels in the user interface have been clicked. /// /// @lib function GUIClicked(): Boolean; //--------------------------------------------------------------------------- // Panels //--------------------------------------------------------------------------- procedure ShowPanelDialog(p: Panel); /// Display the panel on screen at panel's co-ordinates. /// /// @lib /// /// @class Panel /// @method Show procedure ShowPanel(p: Panel); /// Hide the panel, stop drawing it. Panels which are not being draw can not be interacted with by the user. /// /// @lib /// /// @class Panel /// @method Hide procedure HidePanel(p: Panel); /// Toggles whether the panel is being shown or not. /// /// @lib /// /// @class Panel /// @method ToggleVisible procedure ToggleShowPanel(p: Panel); /// Draw the currently visible panels (For use in the main loop) /// /// @lib procedure DrawPanels(); /// Activate the passed in panel. If shown, the panel will be clickable. This is the default state of a panel. /// /// @lib /// /// @class Panel /// @method Activate procedure ActivatePanel(p: Panel); /// Deactivate the panel. The panel will become unclickable, it will remain visible if it was already. /// /// @lib /// /// @class Panel /// @method Deactivate procedure DeactivatePanel(p: Panel); /// Activates the panel if deactivated, and deactivates if activated. /// /// @lib /// /// @class Panel /// @method ToggleActivate procedure ToggleActivatePanel(p: Panel); /// Returns whether panel is active /// /// @lib /// /// @class Panel /// @getter Active function PanelActive(pnl: panel): boolean; /// Returns true if panel is currently visible. /// /// @lib /// /// @class Panel /// @getter Visible function PanelVisible(p: Panel): boolean; /// Returns the last panel clicked. /// /// @lib function PanelClicked(): Panel; overload; /// Returns true when the panel was clicked. /// /// @lib PanelWasClicked /// /// @class Panel /// @getter Clicked function PanelClicked(pnl: Panel): Boolean; overload; /// Sets panel's draggability to the passed boolean /// /// @lib /// @sn panel:%s setDraggable:%s /// /// @class Panel /// @setter Draggable procedure PanelSetDraggable(p: panel; b:boolean); /// Returns whether or not the passed panel is currently draggable /// /// @lib /// @sn panelDraggable:%s /// /// @class Panel /// @getter Draggable function PanelDraggable(p: panel): boolean; /// Move panel along vector /// /// @lib /// /// @class Panel /// @method Move procedure MovePanel(p: Panel; mvmt: Vector); /// Returns the panel at the point passed in. Returns nil if there is no panel. /// /// @lib function PanelAtPoint(pt: Point2D): Panel; /// Returns true if point is in any region within the panel /// /// @lib PointInRegionWithKind /// /// @class Panel /// @self 2 /// @Overload PointInRegion PointInRegionWithKind function PointInRegion(pt: Point2D; p: Panel; kind: GuiElementKind): Boolean; overload; /// Returns true if point is in any region within the panel /// /// @lib /// /// @class Panel /// @self 2 /// @method PointInRegion function PointInRegion(pt: Point2D; p: Panel): Boolean; /// Disposes of all panels /// /// @lib procedure ReleaseAllPanels(); /// Disposes of the panel by name, removing it from the index collection, setting its dragging to nil, and hiding it first to avoid crashes. /// /// @lib procedure ReleasePanel(name: String); /// Disposes of the panel by panel /// /// @lib /// /// @class Panel /// @method Free procedure FreePanel(var pnl: Panel); /// maps panel to name in Hash Table. /// /// @lib /// /// @class Panel /// @constructor /// @csn initWithName:%s forFilename:%s function MapPanel(name, filename: String): Panel; /// Loads panel from panel directory with filename /// /// @lib /// /// @class Panel /// @constructor /// @csn initFromPath:%s function LoadPanel(filename: String): Panel; /// Returns if panel is in Index Collection /// /// @lib function HasPanel(name: String): Boolean; /// Returns panel with the name name /// /// @lib function PanelNamed(name: String): Panel; /// Returns the name of the panel /// /// @lib /// /// @class Panel /// @getter Name function PanelName(pnl: Panel): String; /// Returns panel filename /// /// @lib /// /// @class Panel /// @getter FileName function PanelFilename(pnl: Panel): String; /// Returns if anything is currently being dragged /// /// @lib function IsDragging(): Boolean; overload; /// Returns if panel is currently being dragged /// /// @lib PanelIsDragging /// /// @class Panel /// @getter IsDragging function IsDragging(pnl: Panel): Boolean; overload; /// Returns panel y value /// /// @lib /// /// @class Panel /// @getter Y function PanelY(p: Panel): Single; /// Returns panel x value /// /// @lib /// /// @class Panel /// @getter X function PanelX(p: Panel): Single; /// Returns panel h value /// /// @lib /// /// @class Panel /// @getter Height function PanelHeight(p: Panel): LongInt; /// Returns panel width value /// /// @lib /// /// @class Panel /// @getter Width function PanelWidth(p: Panel): LongInt; //--------------------------------------------------------------------------- // Regions //--------------------------------------------------------------------------- /// Returns the ID of the last region clicked on by user. /// /// @lib function RegionClickedID(): String; /// Returns the last region clicked on by user. /// /// @lib function RegionClicked(): Region; /// Returns the ID of the last region clicked on by user. /// /// @lib /// /// @class Region /// @getter ID function RegionID(r: Region): String; /// Returns the Region with the ID passed from the panel passed /// /// @lib /// /// @class Panel /// @method RegionWithID function RegionWithID(pnl: Panel; ID: String): Region; overload; /// Returns the Region with the ID passed /// /// @lib GlobalRegionWithID function RegionWithID(ID: String): Region; overload; /// Returns the Region with the ID passed from the panel passed /// /// @lib /// /// @class Region /// @getter ParentPanel function RegionPanel(r: Region): Panel; /// Toggles the region active state /// /// @lib /// /// @class Region procedure ToggleRegionActive(forRegion: Region); /// Sets the region active to boolean /// /// @lib /// /// @class Region /// @setter RegionActive procedure SetRegionActive(forRegion: Region; b: boolean); /// Returns the Region Y value /// /// @lib /// /// @class Region /// @getter Y function RegionY(r: Region): Single; /// Returns the Region X value /// /// @lib /// /// @class Region /// @getter X function RegionX(r: Region): Single; /// Returns the Region height value /// /// @lib /// /// @class Region /// @getter Height function RegionHeight(r: Region): LongInt; /// Returns the Region Wdith value /// /// @lib /// /// @class Region /// @getter Width function RegionWidth(r: Region): LongInt; /// Returns the region from the panel at the point /// /// @lib function RegionAtPoint(p: Panel; const pt: Point2D): Region; /// Registers the callback with the panel, when an event related to this /// region occurs the procedure registered will be called. /// /// @lib /// @sn region:%s registerEventCallback:%s /// /// @class Region /// @method RegisterEventCallback procedure RegisterEventCallback(r: Region; callback: GUIEventCallback); //--------------------------------------------------------------------------- //Checkbox //--------------------------------------------------------------------------- /// Returns checkbox state of the checkbox with ID from string /// /// @lib /// /// @method CheckboxState function CheckboxState(s: String): Boolean; overload; /// Returns checkbox state of the checkbox with ID from string /// /// @lib /// /// @class Checkbox /// @getter State function CheckboxState(chk: GUICheckbox): Boolean; overload; /// Returns checkbox state of the checkbox with ID from string /// /// @lib CheckboxStateFromRegion /// /// @class Region /// @getter CheckboxState function CheckboxState(r: Region): Boolean; overload; /// Sets the checkbox state to val. /// /// @lib CheckboxSetStateFromRegion /// /// @class Region /// @setter CheckboxState procedure CheckboxSetState(r: region; val: Boolean); overload; /// Sets the checkbox state to val. /// /// @lib CheckboxSetState /// /// @class Checkbox /// @setter State procedure CheckboxSetState(chk: GUICheckbox; val: Boolean); overload; /// Toggles the state of a checkbox (ticked/unticked) /// /// @lib /// /// @class Checkbox /// @method ToggleCheckboxState procedure ToggleCheckboxState(c: GUICheckbox); /// Takes a region and returns the checkbox of that region /// /// @lib function CheckboxFromRegion(r: Region): GUICheckbox; //RadioGroup /// Takes panel and ID and returns the RadioGroup. /// /// @lib function RadioGroupFromId(pnl: Panel; id: String): GUIRadioGroup; /// Takes region and returns the RadioGroup. /// /// @lib function RadioGroupFromRegion(r: Region): GUIRadioGroup; /// Takes a radiogroup and returns the active button's index. /// /// @lib function ActiveRadioButtonIndex(RadioGroup: GUIRadioGroup): integer; function ActionRadioButton(grp: GUIRadioGroup): Region; overload; function ActionRadioButton(r: Region): Region; overload; procedure SelectRadioButton(r: Region); overload; procedure SelectRadioButton(rGroup: GUIRadioGroup; r: Region); overload; //TextBox /// returns font of textbox /// /// @lib /// /// @class Textbox /// @getter Font function TextBoxFont(tb: GUITextBox): Font; overload; /// returns font of region's textbox (If it has one) /// /// @lib TextBoxFontFromRegion /// /// @class Region /// @getter TextBoxFont function TextBoxFont(r: Region): Font; overload; /// Sets the textbox font /// /// @lib /// /// @class Textbox /// @setter Font procedure TextboxSetFont(Tb: GUITextbox; f: font); /// Gets the textbox text from region /// /// @lib TextboxTextFromId function TextBoxText(id: String): String; overload; /// Gets the textbox text from region /// /// @lib TextboxTextFromRegion /// /// @class Region /// @getter TextboxText function TextBoxText(r: Region): String; overload; /// Gets the textbox text /// /// @lib /// /// @class Textbox /// @getter Text function TextBoxText(tb: GUITextBox): String; overload; /// Sets the textbox text from region /// /// @lib TextboxSetTextFromRegion /// /// @class Region /// @setter TextboxText procedure TextboxSetText(r: Region; s: string); overload; /// Sets the textbox text from region /// /// @lib TextboxSetText /// /// @class Textbox /// @setter Text procedure TextboxSetText(tb: GUITextBox; s: string); overload; /// Sets the textbox text from region /// /// @lib TextboxSetTextToInt /// /// @class Textbox /// @setter Text procedure TextboxSetText(tb: GUITextBox; i: LongInt); overload; /// Sets the textbox text from region /// /// @lib TextboxSetTextToSingle /// /// @class Textbox /// @setter Text procedure TextboxSetText(tb: GUITextBox; single: Single); overload; /// Sets the textbox text from region /// /// @lib TextboxSetTextToSingleFromRegion /// /// @class Region /// @setter TextboxText procedure TextboxSetText(r: Region; single: Single); overload; /// Sets the textbox text from region /// /// @lib TextboxSetTextToIntFromRegion /// /// @class Region /// @setter TextboxText procedure TextboxSetText(r: Region; i: LongInt); overload; /// Sets the textbox text from region /// /// @lib TextboxTextFromRegion /// /// @class Region /// @getter TextboxText function TextBoxFromRegion(r: Region): GUITextBox; /// Sets the active textbox from region /// /// @lib GUISetActiveTextboxFromRegion procedure GUISetActiveTextbox(r: Region); overload; /// Sets the active textbox /// /// @lib procedure GUISetActiveTextbox(t: GUITextBox); overload; /// Deactivates the active textbox /// /// @lib procedure DeactivateTextBox(); /// Returns the index of the active textbox's region. /// /// @lib function ActiveTextIndex(): LongInt; /// Checks if TextEntry finished, returns true/false /// /// @lib function GUITextEntryComplete(): boolean; /// Returns the textbox in which text was changed/added into most recently. /// /// @lib function GUITextBoxOfTextEntered(): GUITextbox; /// Returns the region of the textbox in which text was changed/added into most recently. /// /// @lib function RegionOfLastUpdatedTextBox(): Region; /// Returns the index of the region of the textbox in which text was changed/added into most recently. /// /// @lib function IndexOfLastUpdatedTextBox(): LongInt; /// UpdateInterface main loop, checks the draggable, checks the region clicked, updates the interface /// /// @lib procedure UpdateInterface(); /// Sets the GUI whether or not to use Vector Drawing /// /// @lib procedure DrawGUIAsVectors(b : boolean); /// Finishes reading text and stores in the active textbox /// /// @lib procedure FinishReadingText(); /// Returns the parent panel of the active textbox /// /// @lib function ActiveTextBoxParent() : Panel; /// Returns the alignment of the text in textbox passed in as region /// /// @lib function TextboxAlignment(r: Region): FontAlignment; /// Gets the textbox alignmnet of the textbox /// /// @lib /// /// @class Textbox /// @getter Alignmnet function TextboxAlignment(tb: GUITextbox): FontAlignment; /// Set the textbox alignment of the textbox /// /// @lib /// /// @class Textbox /// @setter Alignmnet procedure TextboxSetAlignment(tb: GUITextbox; align: FontAlignment); /// Set the textbox alignment of the textbox passed in /// /// @lib procedure TextboxSetAlignment(r: Region; align: FontAlignment); //--------------------------------------------------------------------------- //Lists //--------------------------------------------------------------------------- procedure ListRemoveActiveItem(r : region); overload; procedure ListRemoveActiveItem(s : string); overload; /// Set the active item in the list to the item at index idx /// /// @lib /// /// @class List /// @setter activeItem procedure ListSetActiveItemIndex(lst: GUIList; idx: LongInt); /// Returns the active item text of the List in panel, pnl- with ID, ID /// /// @lib /// /// @class List /// @getter activeItemText function ListActiveItemText(pnl: Panel; ID: String): String; /// Returns the active item text of the List in with ID /// /// @lib function ListActiveItemText(ID: String): String; /// Returns Returns the list of the region r /// /// @lib /// /// @class Region /// @getter List function ListFromRegion(r: Region): GUIList; overload; /// Returns the font of the list of the region /// /// @lib ListFontFromRegion /// /// @class Region /// @getter ListFont function ListFont(r: Region): Font; overload; /// Returns the font of the list /// /// @lib /// /// @class List /// @getter Font function ListFont(lst: GUIList): Font; overload; /// Sets the font of the list to font f /// /// @lib /// /// @class List /// @setter Font procedure ListSetFont(lst: GUITextbox; f: font); /// Returns the text of the item at index idx from the List of the Region /// /// @lib ListItemTextFromRegion /// /// @class Region /// @getter ListItemText function ListItemText(r: Region; idx: LongInt): String; overload; /// Returns the text of the item at index idx /// /// @lib /// /// @class List /// @getter ItemText function ListItemText(lst: GUIList; idx: LongInt): String; overload; /// Returns the text of the active item in the list of the region /// /// @lib ListActiveItemTextFromRegion /// /// @class Region /// @getter ListItemText function ListActiveItemText(r: Region): String; overload; /// Returns the number of items in the list of the region /// /// @lib ListItemCountFromRegion /// /// @class Region /// @getter ListItemCount function ListItemCount(r: Region): LongInt; overload; /// Returns the number of items in the list /// /// @lib ListItemCount /// /// @class List /// @getter ItemCount function ListItemCount(lst:GUIList): LongInt; overload; /// Returns active item's index from the list of the region /// /// @lib /// /// @class Region /// @getter ListActiveItemIndex function ListActiveItemIndex(r: Region): LongInt; overload; /// Returns active item's index from the list /// /// @lib /// /// @class List /// @getter ActiveItemIndex function ListActiveItemIndex(lst: GUIList): LongInt; /// Removes item at index idx from the list /// /// @lib /// /// @class List /// @method RemoveItem procedure ListRemoveItem(lst: GUIList; idx: LongInt); /// Removes all items from the list. /// /// @lib /// /// @class List /// @method ClearItems procedure ListClearItems(lst: GUIList); overload; /// Removes all items from the list of the region /// /// @lib /// /// @class Region /// @method ListClearItems procedure ListClearItems(r : Region); overload; /// Adds an item to the list by text /// /// @lib AddItemByText /// /// @class List /// @method AddItem procedure ListAddItem(lst: GUIList; text: String); overload; /// Adds an item to the list by bitmap /// /// @lib AddItemByBitmap /// /// @class List /// @method AddItem procedure ListAddItem(lst: GUIList; img:Bitmap); overload; /// Adds an item to the list by text /// /// @lib AddItem /// /// @class List /// @method AddItem procedure ListAddItem(lst: GUIList; img:Bitmap; text: String); overload; /// Adds an item to the list where the items shows a cell of a /// bitmap. /// /// @lib ListAddItemWithCell /// @sn list:%s addBitmapCell:%s /// /// @class List /// @overload AddItem AddItemWithCell /// @csn addBitmapCell:%s procedure ListAddItem(lst: GUIList; const img: BitmapCell); overload; /// Adds an item to the list where the items shows a cell of a /// bitmap and some text. /// /// @lib ListAddItemWithCellAndText /// @sn list:%s addBitmapCell:%s withText:%s /// /// @class List /// @overload AddItem AddItemWithCellAndText /// @csn addBitmapCell:%s withText:%s procedure ListAddItem(lst: GUIList; const img: BitmapCell; text: String); overload; /// Adds an item to the list where the items shows a cell of a /// bitmap and some text. /// /// @lib ListAddItemWithCellAndTextFromRegion /// @sn region:%s addBitmapCell:%s withText:%s /// /// @class Region /// @overload AddItem AddItemWithCellAndTextFromRegion /// @csn addBitmapCell:%s withText:%s procedure ListAddItem(r: Region; const img:BitmapCell; text: String); overload; /// Adds an item to the list where the items shows a cell of a /// bitmap. /// /// @lib ListAddItemWithCellFromRegion /// @sn region:%s addBitmapCell:%s /// /// @class Region /// @overload AddItem AddItemWithCellFromRegion /// @csn addBitmapCell:%s procedure ListAddItem(r : Region; const img: BitmapCell); overload; /// Adds an item to the list by text /// /// @lib AddItemByTextFromRegion /// /// @class Region /// @method ListAddItem procedure ListAddItem(r : Region; text: String); overload; function NewPanel(pnlName: String): Panel; /// Adds an item to the list by bitmap /// /// @lib AddItemByBitmapFromRegion /// /// @class Region /// @method ListAddItem procedure ListAddItem(r : Region; img:Bitmap); overload; /// Adds an item to the list /// /// @lib AddItemFromRegion /// /// @class Region /// @method ListAddItem procedure ListAddItem(r : Region; img:Bitmap; text: String); overload; /// Returns the index of the item with the bitmap, img /// /// @lib /// /// @class List /// @getter activeItem function ListBitmapIndex(lst: GUIList; img: Bitmap): LongInt; /// Returns the index of the item with the bitmap and cell. /// /// @lib /// /// @class List /// @getter activeItem function ListBitmapIndex(lst: GUIList; const img: BitmapCell): LongInt; /// Adds an item to the list by text /// /// @lib /// /// @class Region /// @getter activeItem function ListTextIndex(lst: GUIList; value: String): LongInt; /// Returns the starting point for the list /// /// @lib /// /// @class List /// @getter StartingAt function ListStartAt(lst: GUIList): LongInt; /// Returns the starting point for the list from region /// /// @lib ListStartingAtFromRegion /// /// @class Region /// @getter ListStartingAt function ListStartAt(r: Region): LongInt; /// Sets the starting point for the list /// /// @lib ListSetStartingAt /// /// @class List /// @setter StartingAt procedure ListSetStartAt(lst: GUIList; idx: LongInt); /// Sets the starting point for the list from region /// /// @lib ListSetStartingAtFromRegion /// /// @class Region /// @setter ListStartingAt procedure ListSetStartAt(r: Region; idx: LongInt); /// Returns the font alignment of a list from region /// /// @lib ListFontAlignmentFromRegion /// /// @class Region /// @getter ListFontAlignment function ListFontAlignment(r: Region): FontAlignment; /// Returns the font alignment of a list /// /// @lib ListFontAlignment /// /// @class List /// @getter FontAlignment function ListFontAlignment(lst: GUIList): FontAlignment; /// Returns the font alignment of a list from region /// /// @lib ListSetFontAlignmentFromRegion /// /// @class Region /// @setter ListFontAlignment procedure ListSetFontAlignment(r: Region; align: FontAlignment); /// Returns the font alignment of a list /// /// @lib ListSetFontAlignment /// /// @class List /// @setter FontAlignment procedure ListSetFontAlignment(lst: GUIList; align: FontAlignment); /// Returns the largest index that startingAt should be set to. /// /// @lib ListLargestStartIndex /// /// @class List /// @setter LargestStartIndex function ListLargestStartIndex(lst: GUIList): LongInt; /// Returns the largest index that startingAt should be set to. /// /// @lib ListLargestStartIndex /// /// @class List /// @method ScrollIncrement function ListScrollIncrement(lst: GUIList): LongInt; //Label function LabelFont(l: GUILabel): Font; overload; function LabelFont(r: Region): Font; overload; procedure LabelSetFont(l: GUILabel; s: String); function LabelText(lb: GUILabel): string; overload; function LabelText(r: Region): string; overload; procedure LabelSetText(id: String; newString: String); overload; procedure LabelSetText(lb: GUILabel; newString: String); overload; procedure LabelSetText(r: Region; newString: String); overload; procedure LabelSetText(pnl: Panel; id, newString: String); overload; function LabelFromRegion(r: Region): GUILabel; function LabelAlignment(r: Region): FontAlignment; function LabelAlignment(tb: GUILabel): FontAlignment; procedure LabelSetAlignment(tb: GUILabel; align: FontAlignment); procedure LabelSetAlignment(r: Region; align: FontAlignment); // Dialog Code procedure DialogSetPath(fullname: String); function IsSet(toCheck, checkFor: FileDialogSelectType): Boolean; overload; function DialogPath(): String; function DialogCancelled(): Boolean; function DialogComplete(): Boolean; procedure ShowSaveDialog(); overload; procedure ShowSaveDialog(select: FileDialogSelectType); overload; procedure ShowOpenDialog(); overload; procedure ShowOpenDialog(select: FileDialogSelectType); overload; procedure DoFreePanel(var pnl: Panel); procedure GUISetBackgroundColorInactive(c:color); procedure GUISetForegroundColorInactive(c:color); //Do not use procedure AddPanelToGUI(p: Panel); procedure AddRegionToPanelWithString(d: string; p: panel); //============================================================================= implementation uses SysUtils, StrUtils, Classes, Math, stringhash, sgUtils, sgNamedIndexCollection, // libsrc sgShared, sgResources, sgTrace, sgImages, sgGraphics, sgCore, sgGeometry, sgText, sgInput, sgAudio; //============================================================================= type GUIController = record panels: Array of Panel; // The panels that are loaded into the GUI visiblePanels: Array of Panel; // The panels that are currently visible (in reverse z order - back to front) globalGUIFont: Font; foregroundClr: Color; // The color of the foreground backgroundClr: Color; // The color of the background foregroundClrInactive: Color; backgroundClrInactive: Color; VectorDrawing: Boolean; lastClicked: Region; activeTextBox: Region; lastActiveTextBox: Region; doneReading: Boolean; lastTextRead: String; // The text that was in the most recently changed textbox before it was changed. panelIds: TStringHash; // Variables for dragging panels downRegistered: Boolean; panelDragging: Panel; // The panel clicked panelClicked: Panel; end; FileDialogData = packed record dialogPanel: Panel; // The panel used to show the dialog currentPath: String; // The path to the current directory being shown currentSelectedPath: String; // The path to the file selected by the user cancelled: Boolean; complete: Boolean; allowNew: Boolean; selectType: FileDialogSelectType; onlyFiles: Boolean; lastSelectedFile, lastSelectedPath: LongInt; // These represent the index if the selected file/path to enable double-like clicking end; var GUIC: GUIController; // The file dialog dialog: FileDialogData; // // Event management code // // This procedure calls the callbacks for the event // This is private to the unit procedure SendEvent(r: Region; kind: EventKind); var i: LongInt; pnl: Panel; begin if not assigned(r) then exit; pnl := r^.parent; if not assigned(pnl) then exit; for i := 0 to High(r^.callbacks) do begin try r^.callbacks[i](r, kind); except WriteLn(stderr, 'Error with event callback!'); end; end; end; procedure HandlePanelInput(pnl: Panel); forward; function GUITextEntryComplete(): boolean; begin result := GUIC.doneReading; end; function GUITextBoxOfTextEntered(): GUITextbox; begin result := nil; if not assigned(GUIC.lastActiveTextBox) then exit; result := @GUIC.lastActiveTextBox^.parent^.textBoxes[GUIC.lastActiveTextBox^.elementIndex]; end; function RegionOfLastUpdatedTextBox(): Region; begin result := nil; if not assigned(GUIC.lastActiveTextBox) then exit; result := GUIC.lastActiveTextBox; end; function IndexOfLastUpdatedTextBox(): LongInt; begin result := -1; if not assigned(GUIC.lastActiveTextBox) then exit; result := RegionOfLastUpdatedTextBox()^.elementIndex; end; function ActiveTextIndex(): LongInt; begin result := -1; if not assigned(GUIC.activeTextBox) then exit; result := GUIC.activeTextBox^.elementIndex; end; procedure DeactivateTextBox(); begin GUIC.activeTextBox := nil; end; function ActiveTextBoxParent() : Panel; begin result := GUIC.activeTextBox^.parent; end; function RegionRectangleOnscreen(r: Region): Rectangle; begin if not assigned(r) then begin result := RectangleFrom(0,0,0,0); exit; end; result := RectangleOffset(r^.area, RectangleTopLeft(r^.parent^.area)); end; function GUIClicked(): Boolean; begin result := GUIC.panelClicked <> nil; end; function ModalBefore(pnl: Panel): Boolean; var i: LongInt; begin result := false; for i := High(GUIC.visiblePanels) downto 0 do begin if GUIC.visiblePanels[i] = pnl then exit else if GUIC.visiblePanels[i]^.modal then begin result := true; exit; end; end; end; //--------------------------------------------------------------------------------------- // Drawing Loops //--------------------------------------------------------------------------------------- function BitmapToDraw(r: Region): Bitmap; begin result := nil; if not(assigned(r)) then exit; // Check if the panel or the region is inactive if (not r^.parent^.active) or (not r^.active) then begin result := r^.parent^.panelBitmapInactive; exit; end; // Check based upon the kind of the region case r^.kind of gkButton: begin if MouseDown(LeftButton) AND PointInRect(MousePosition(), RegionRectangleOnScreen(r)) then result := r^.parent^.panelBitmapActive else result := nil; // dont redraw the r^.parent^.panelBitmap; end; gkCheckBox: begin if CheckboxState(r) then result := r^.parent^.panelBitmapActive else result := nil; // dont redraw the end; gkRadioGroup: begin if r = ActionRadioButton(r) then result := r^.parent^.panelBitmapActive else result := nil; // dont redraw the end; end; end; //Helper functions used to determine the text rectangle for text boxes function TextboxTextArea(r: Rectangle): Rectangle; overload; begin result := InsetRectangle(r, 1); end; function TextboxTextArea(r: Region): Rectangle; overload; begin result := TextboxTextArea(RegionRectangleOnScreen(r)); end; function VectorForecolorToDraw(r: region): Color; begin result := GUIC.foregroundClr; if not(assigned(r)) then exit; // Check if the panel or the region is inactive if (not r^.parent^.active) or (not r^.active) then begin result := GUIC.foregroundClrInactive; exit; end; // Change the button on mouse down case r^.kind of gkButton: begin if MouseDown(LeftButton) AND PointInRect(MousePosition(), RegionRectangleOnScreen(r)) then result := guic.backgroundClr end; end; end; function VectorBackcolorToDraw(r: region): Color; begin result := GUIC.backgroundClr; if not(assigned(r)) then exit; // Check if the panel or the region is inactive if (not r^.parent^.active) or (not r^.active) then begin result := GUIC.backgroundClrInactive; exit; end; // Change the button on mouse down case r^.kind of gkButton: begin if MouseDown(LeftButton) AND PointInRect(MousePosition(), RegionRectangleOnScreen(r)) then result := guic.foregroundClr end; end; end; procedure DrawVectorCheckbox(forRegion: Region; const area: Rectangle); begin DrawRectangleOnScreen(VectorForecolorToDraw(forRegion), area); if CheckboxState(forRegion) then begin FillRectangleOnScreen(VectorForecolorToDraw(forRegion), InsetRectangle(area, 2)); end; end; procedure DrawVectorRadioButton(forRegion: Region; const area: Rectangle); begin DrawEllipseOnScreen(VectorForecolorToDraw(forRegion), area); if forRegion = ActionRadioButton(forRegion) then begin FillEllipseOnScreen(VectorForecolorToDraw(forRegion), InsetRectangle(area, 2)); end; end; procedure DrawTextbox(forRegion: Region; const area: Rectangle); begin if forRegion^.parent^.DrawAsVectors then DrawRectangleOnScreen(VectorForecolorToDraw(forRegion), area); if GUIC.activeTextBox <> forRegion then DrawTextLinesOnScreen(TextboxText(forRegion), VectorForecolorToDraw(forRegion), VectorBackcolorToDraw(forRegion), TextboxFont(forRegion), TextboxAlignment(forRegion), TextboxTextArea(area)); end; procedure DrawList(forRegion: Region; const area: Rectangle); var tempList: GUIList; i, itemIdx: LongInt; areaPt, imagePt: Point2D; itemArea, scrollArea: Rectangle; itemTextArea: Rectangle; placeHolderScreenRect: Rectangle; procedure _DrawUpDownArrow(const rect: Rectangle; up: Boolean); var tri: Triangle; innerRect, arrowArea: Rectangle; begin arrowArea := RectangleOffset(rect, areaPt); FillRectangleOnScreen(VectorForecolorToDraw(forRegion), arrowArea); innerRect := InsetRectangle(arrowArea, 2); if up then begin tri[0] := RectangleBottomLeft(innerRect); tri[1] := RectangleBottomRight(innerRect); tri[2] := RectangleCenterTop(innerRect); end else begin tri[0] := RectangleTopLeft(innerRect); tri[1] := RectangleTopRight(innerRect); tri[2] := RectangleCenterBottom(innerRect); end; FillTriangleOnScreen(VectorBackcolorToDraw(forRegion), tri); end; procedure _DrawLeftRightArrow(const rect: Rectangle; left: Boolean); var tri: Triangle; innerRect, arrowArea: Rectangle; begin arrowArea := RectangleOffset(rect, areaPt); FillRectangleOnScreen(VectorForecolorToDraw(forRegion), arrowArea); innerRect := InsetRectangle(arrowArea, 2); if left then begin tri[0] := RectangleCenterLeft(innerRect); tri[1] := RectangleBottomRight(innerRect); tri[2] := RectangleTopRight(innerRect); end else begin tri[0] := RectangleCenterRight(innerRect); tri[1] := RectangleTopLeft(innerRect); tri[2] := RectangleBottomLeft(innerRect); end; FillTriangleOnScreen(VectorBackcolorToDraw(forRegion), tri); end; procedure _ResizeItemArea(var area: Rectangle; var imgPt: Point2D; aligned: FontAlignment; const bmp: BitmapCell); begin case aligned of AlignCenter: begin imgPt.x := imgPt.x + (area.Width - BitmapWidth(bmp)) / 2; end; AlignLeft: begin area.Width := area.Width - BitmapWidth(bmp) - 1; // 1 pixel boundry for bitmap area.x := area.x + BitmapWidth(bmp); imgPt.x := imgPt.x + 1; end; AlignRight: begin area.Width := area.Width - BitmapWidth(bmp) - 1; imgPt.x := imgPt.x + area.width + 1; end; end; end; procedure _DrawScrollPosition(); var pct: Single; largestStartIdx: LongInt; begin largestStartIdx := ListLargestStartIndex(tempList); // if the number of items is >= the number shown then pct := 0 if largestStartIdx <= 0 then pct := 0 else begin pct := tempList^.startingAt / largestStartIdx; end; if tempList^.verticalScroll then begin if forRegion^.parent^.DrawAsVectors then FillRectangleOnScreen(VectorForecolorToDraw(forRegion), Round(scrollArea.x), Round(scrollArea.y + pct * (scrollArea.Height - tempList^.scrollSize)), tempList^.scrollSize, tempList^.scrollSize ) else DrawBitmapOnScreen(tempList^.ScrollButton, Round(scrollArea.x), Round(scrollArea.y + pct * (scrollArea.Height - tempList^.scrollSize))); end else begin if forRegion^.parent^.DrawAsVectors then FillRectangleOnScreen(VectorForecolorToDraw(forRegion), Round(scrollArea.x + pct * (scrollArea.Width - tempList^.scrollSize)), Round(scrollArea.y), tempList^.scrollSize, tempList^.scrollSize ) else DrawBitmapOnScreen(tempList^.ScrollButton, Round(scrollArea.x + pct * (scrollArea.Width - tempList^.scrollSize)), Round(scrollArea.y)); end; end; begin tempList := ListFromRegion(forRegion); if not assigned(tempList) then exit; if forRegion^.parent^.DrawAsVectors then DrawRectangleOnScreen(VectorForecolorToDraw(forRegion), area); PushClip(area); areaPt := RectangleTopLeft(area); // Draw the up and down buttons if forRegion^.parent^.DrawAsVectors then begin if tempList^.verticalScroll then begin _DrawUpDownArrow(tempList^.scrollUp, true); _DrawUpDownArrow(tempList^.scrollDown, false); end else begin _DrawLeftRightArrow(tempList^.scrollUp, true); _DrawLeftRightArrow(tempList^.scrollDown, false); end; end; // Draw the scroll area scrollArea := RectangleOffset(tempList^.scrollArea, areaPt); if forRegion^.parent^.DrawAsVectors then begin DrawRectangleOnScreen(VectorBackcolorToDraw(forRegion), scrollArea); DrawRectangleOnScreen(VectorForecolorToDraw(forRegion), scrollArea); end; // Draw the scroll position indicator PushClip(scrollArea); _DrawScrollPosition(); PopClip(); // pop the scroll area //Draw all of the placeholders for i := Low(tempList^.placeHolder) to High(tempList^.placeHolder) do begin itemTextArea := RectangleOffset(tempList^.placeHolder[i], areaPt); itemArea := RectangleOffset(tempList^.placeHolder[i], areaPt); placeHolderScreenRect := RectangleOffset(tempList^.placeHolder[i], RectangleTopLeft(forRegion^.area)); // Outline the item's area if forRegion^.parent^.DrawAsVectors then DrawRectangleOnScreen(VectorForecolorToDraw(forRegion), itemArea); // Find the index of the first item to be shown in the list // NOTE: place holders in col then row order 0, 1 -> 2, 3 -> 4, 5 (for 2 cols x 3 rows) if tempList^.verticalScroll then itemIdx := i + tempList^.startingAt else // 0, 1 => 0, 3 // 2, 3 => 1, 4 // 4, 5 => 2, 5 itemIdx := tempList^.startingAt + ((i mod tempList^.columns) * tempList^.rows) + (i div tempList^.columns); // Dont draw item details if out of range, but continue to draw outlines if (itemIdx < 0) OR (itemIdx > High(tempList^.items)) then continue; PushClip(itemArea); //Draw the placeholder background //Draw the text (adjusting position for width of list item bitmap) if assigned(tempList^.items[itemIdx].image.bmp) then begin // Determine the location of the list item's bitmap imagePt := RectangleTopLeft(itemArea); imagePt.y := imagePt.y + (itemArea.height - BitmapHeight(tempList^.items[itemidx].image)) / 2; _ResizeItemArea(itemTextArea, imagePt, ListFontAlignment(tempList), tempList^.items[itemIdx].image); end; // if selected draw the alternate background if (itemIdx = tempList^.activeItem) then begin if forRegion^.parent^.DrawAsVectors then begin // Fill and draw text in alternate color if vector based FillRectangleOnScreen(VectorForecolorToDraw(forRegion), itemArea); end else begin // Draw bitmap and text if bitmap based DrawBitmapPartOnscreen(forRegion^.parent^.panelBitmapActive, placeHolderScreenRect, RectangleTopLeft(itemArea)); end; end; // Draw the item's bitmap if assigned(tempList^.items[itemIdx].image.bmp) then begin DrawBitmapCellOnScreen(tempList^.items[itemIdx].image, imagePt); end; // Draw the text on top if (itemIdx <> tempList^.activeItem) then begin // Draw the text onto the screen as normal... DrawTextLinesOnScreen(ListItemText(tempList, itemIdx), VectorForecolorToDraw(forRegion), VectorBackcolorToDraw(forRegion), ListFont(tempList), ListFontAlignment(tempList), itemTextArea); end else // the item is the selected item... begin if forRegion^.parent^.DrawAsVectors then begin DrawTextLinesOnScreen(ListItemText(tempList, itemIdx), VectorBackcolorToDraw(forRegion), VectorForecolorToDraw(forRegion), ListFont(tempList), ListFontAlignment(tempList), itemTextArea); end else begin DrawTextLinesOnScreen(ListItemText(tempList, itemIdx), VectorForecolorToDraw(forRegion), VectorBackcolorToDraw(forRegion), ListFont(tempList), ListFontAlignment(tempList), itemTextArea); end; end; PopClip(); // item area end; PopClip(); // region end; procedure DrawLabelText(forRegion: Region; const area: Rectangle); begin DrawTextLinesOnScreen(LabelText(forRegion), VectorForecolorToDraw(forRegion), VectorBackcolorToDraw(forRegion), LabelFont(forRegion), LabelAlignment(forRegion), TextboxTextArea(area)); end; procedure DrawAsVectors(p: Panel); var j: integer; current: Panel; currentReg: Region; begin current := p; if current^.active then begin FillRectangleOnScreen(GUIC.backgroundClr, current^.area); DrawRectangleOnScreen(GUIC.foregroundClr, current^.area); end else begin FillRectangleOnScreen(GUIC.backgroundClrInactive, current^.area); DrawRectangleOnScreen(GUIC.foregroundClrInactive, current^.area); end; PushClip(current^.area); for j := High(current^.Regions) downto Low(current^.Regions) do begin currentReg := @p^.Regions[j]; case currentReg^.kind of gkButton: DrawRectangleOnScreen(VectorForecolorToDraw(currentReg), RegionRectangleOnscreen(currentReg)); gkLabel: DrawLabelText(currentReg, RegionRectangleOnscreen(currentReg)); gkCheckbox: DrawVectorCheckbox(currentReg, RegionRectangleOnScreen(currentReg)); gkRadioGroup: DrawVectorRadioButton(currentReg, RegionRectangleOnScreen(currentReg)); gkTextbox: DrawTextbox(currentReg, RegionRectangleOnScreen(currentReg)); gkList: DrawList(currentReg, RegionRectangleOnScreen(currentReg)); end; end; PopClip(); end; function PanelBitmapToDraw(p: Panel): bitmap; begin if not PanelActive(p) then begin result := p^.PanelBitmapInactive; exit; end; result := p^.PanelBitmap; end; procedure DrawAsBitmaps(p: Panel); var j: integer; currentReg: Region; begin DrawBitmapOnScreen(PanelBitmapToDraw(p), RectangleTopLeft(p^.area)); for j := Low(p^.Regions) to High(p^.Regions) do begin currentReg := @p^.Regions[j]; case p^.Regions[j].kind of gkLabel: DrawLabelText(currentReg, RegionRectangleOnscreen(currentReg)); gkTextbox: DrawTextbox(currentReg, RegionRectangleOnScreen(currentReg)); gkList: DrawList(currentReg, RegionRectangleOnScreen(currentReg)); else DrawBitmapPartOnScreen(BitmapToDraw(currentReg), currentReg^.area, RectangleTopLeft(RegionRectangleOnScreen(currentReg))); end; end; end; procedure DrawPanels(); var i: longint; begin for i := Low(GUIC.visiblePanels) to High(GUIC.visiblePanels) do begin if GUIC.visiblePanels[i]^.DrawAsVectors then begin DrawAsVectors(GUIC.visiblePanels[i]) end else begin DrawAsBitmaps(GUIC.visiblePanels[i]); end; end; end; //--------------------------------------------------------------------------------------- // Region Code //--------------------------------------------------------------------------------------- function RegionWidth(r: Region): LongInt; begin result := -1; if not(assigned(r)) then exit; result := r^.area.width; end; function RegionHeight(r: Region): LongInt; begin result := -1; if not(assigned(r)) then exit; result := r^.area.height; end; function RegionX(r: Region): Single; begin result := -1; if not(assigned(r)) then exit; result := r^.area.x; end; function RegionY(r: Region): Single; begin result := -1; if not(assigned(r)) then exit; result := r^.area.y; end; procedure SetRegionActive(forRegion: Region; b: boolean); begin if not assigned(forRegion) then exit; forRegion^.active := b; end; procedure ToggleRegionActive(forRegion: Region); begin if not assigned(forRegion) then exit; forRegion^.active := not forRegion^.active; end; function RegionWithID(pnl: Panel; ID: String): Region; overload; var idx: LongInt; begin result := nil; if not assigned(pnl) then exit; idx := IndexOf(pnl^.regionIds, ID); if idx >= 0 then begin result := @pnl^.regions[idx]; end; end; function RegionWithID(ID: String): Region; overload; var i: integer; begin result := nil; for i := Low(GUIC.panels) to High(GUIC.panels) do begin result := RegionWithID(GUIC.panels[i], ID); if assigned(result) then exit; end; end; function RegionID(r: Region): string; begin if assigned(r) then result := r^.stringID else result := ''; end; // Check which of the regions was clicked in this panel procedure HandlePanelInput(pnl: Panel); procedure _ScrollWithScrollArea(lst: GUIList; mouse: Point2D); var largestStartIdx: LongInt; pct: Single; begin GUIC.lastClicked := nil; largestStartIdx := ListLargestStartIndex(lst); if lst^.verticalScroll then pct := (mouse.y - lst^.scrollArea.y) / lst^.scrollArea.height else pct := (mouse.x - lst^.scrollArea.x) / lst^.scrollArea.width; lst^.startingAt := Round(pct * largestStartIdx / ListScrollIncrement(lst)) * ListScrollIncrement(lst); exit; end; procedure _ScrollUp(lst: GUIList); var inc: LongInt; begin inc := ListScrollIncrement(lst); if lst^.startingAt >= inc then lst^.startingAt := lst^.startingAt - inc; end; procedure _ScrollDown(lst: GUIList); var inc, largestStartIdx: LongInt; begin inc := ListScrollIncrement(lst); largestStartIdx := ListLargestStartIndex(lst); if lst^.startingAt + inc <= largestStartIdx then lst^.startingAt := lst^.startingAt + inc; end; procedure _PerformListClicked(lstRegion: Region; lst: GUIList; pointClicked: Point2D); var i: LongInt; begin if not assigned(lst) then exit; // WriteLn(PointToString(pointClicked)); // Write(lst^.startingAt); // itemCount := Length(lst^.items); // placeCount := lst^.rows * lst^.columns; // Check up and down scrolling... if PointInRect(pointClicked, lst^.scrollUp) then begin _ScrollUp(lst); // WriteLn(' -> ', lst^.startingAt); GUIC.lastClicked := nil; // click in scroller... exit; end else if PointInRect(pointClicked, lst^.scrollDown) then begin _ScrollDown(lst); // WriteLn(' -> ', lst^.startingAt); GUIC.lastClicked := nil; // click in scroller... exit; end else if PointInRect(pointClicked, lst^.scrollArea) then begin _ScrollWithScrollArea(lst, pointClicked); exit; end; // WriteLn(' -> ', lst^.startingAt); for i := Low(lst^.placeHolder) to High(lst^.placeHolder) do begin if PointInRect(pointClicked, lst^.placeHolder[i]) AND (lst^.startingAt + i < Length(lst^.items)) then begin lst^.activeItem := lst^.startingAt + i; SendEvent(lstRegion, ekSelectionMade); exit; end; end; end; procedure _PerformMouseDownOnList(lst: GUIList; mouse: Point2D); begin if PointInRect(mouse, lst^.scrollArea) then begin _ScrollWithScrollArea(lst, mouse); end; end; procedure _UpdateMouseDown(mouse: Point2D); var pointDownInRegion: Point2D; r: Region; begin if ReadingText() then FinishReadingText(); r := RegionAtPoint(pnl, mouse); if not assigned(r) then exit; // Adjust the mouse point into the region's coordinates (offset from top left of region) pointDownInRegion := PointAdd(mouse, InvertVector(RectangleTopLeft(r^.area))); // Perform kind based updating case r^.kind of gkList: _PerformMouseDownOnList(ListFromRegion(r), pointDownInRegion); end; end; procedure _UpdateScrollUp(mouse: Point2D); var r: Region; begin r := RegionAtPoint(pnl, mouse); if not assigned(r) then exit; // Perform kind based updating case r^.kind of gkList: _ScrollUp(ListFromRegion(r)); end; end; procedure _UpdateScrollDown(mouse: Point2D); var r: Region; begin r := RegionAtPoint(pnl, mouse); if not assigned(r) then exit; // Perform kind based updating case r^.kind of gkList: _ScrollDown(ListFromRegion(r)); end; end; procedure _UpdateMouseClicked(pointClicked: Point2D); var pointClickedInRegion: Point2D; r: Region; begin if ReadingText() then FinishReadingText(); r := RegionAtPoint(pnl, pointClicked); if not assigned(r) then exit; if not r^.active then exit; GUIC.lastClicked := r; // Adjust the mouse point into the region's coordinates (offset from top left of region) pointClickedInRegion := PointAdd(pointClicked, InvertVector(RectangleTopLeft(r^.area))); // Perform kind based updating case r^.kind of gkCheckBox: ToggleCheckboxState (CheckboxFromRegion(r) ); gkRadioGroup: SelectRadioButton (RadioGroupFromRegion(r), r ); gkTextBox: GUISetActiveTextbox (TextBoxFromRegion(r) ); gkList: _PerformListClicked (r, ListFromRegion(r), pointClickedInRegion); end; if assigned(GUIC.lastClicked) then SendEvent(GUIC.lastClicked, ekClicked); end; var pointClickedInPnl: Point2D; begin if pnl = nil then exit; if not PanelActive(pnl) then exit; // Adjust the mouse point into this panels area (offset from top left of pnl) pointClickedInPnl := PointAdd(MousePosition(), InvertVector(RectangleTopLeft(pnl^.area))); // Handle mouse interaction if MouseClicked(LeftButton) then _UpdateMouseClicked(pointClickedInPnl) else if MouseDown(LeftButton) then _UpdateMouseDown(pointClickedInPnl) else if MouseClicked(WheelUpButton) then _UpdateScrollUp(pointClickedInPnl) else if MouseClicked(WheelDownButton) then _UpdateScrollDown(pointClickedInPnl); end; function RegionClicked(): region; begin result := nil; if not assigned(GUIC.lastClicked) then exit; result := GUIC.lastClicked; end; function RegionClickedID(): String; begin result := ''; if not assigned(GUIC.lastClicked) then exit; result := RegionID(GUIC.lastClicked); end; function RegionPanel(r: Region): Panel; begin result := nil; if not assigned(r) then exit; result := r^.parent; end; function RegionAtPoint(p: Panel; const pt: Point2D): Region; var i: LongInt; current: Region; begin result := nil; if not assigned(p) then exit; for i := Low(p^.Regions) to High(p^.Regions) do begin // Get the region at the i index current := @p^.Regions[i]; //Check if it has been clicked if PointInRect(pt, current^.area) then begin result := current; exit; end; end; end; //--------------------------------------------------------------------------------------- // Get element from region //--------------------------------------------------------------------------------------- function RadioGroupFromRegion(r: Region): GUIRadioGroup; begin result := nil; if not assigned(r) then exit; if not assigned(r^.parent) then exit; if not (r^.kind = gkRadioGroup) then exit; if (r^.elementIndex < 0) or (r^.elementIndex > High(r^.parent^.radioGroups)) then exit; result := @r^.parent^.radioGroups[r^.elementIndex]; end; function RadioGroupFromId(pnl: Panel; id: String): GUIRadioGroup; var i: LongInt; begin result := nil; if not assigned(pnl) then exit; id := LowerCase(id); for i := 0 to High(pnl^.radioGroups) do begin if LowerCase(pnl^.radioGroups[i].groupID) = id then begin result := @pnl^.radioGroups[i]; exit; end; end; end; function LabelFromRegion(r: Region): GUILabel; overload; begin result := nil; if not assigned(r) then exit; if not assigned(r^.parent) then exit; if not (r^.kind = gkLabel) then exit; if (r^.elementIndex < 0) or (r^.elementIndex > High(r^.parent^.labels)) then exit; //Return a pointer to the label in the panel result := @r^.parent^.labels[r^.elementIndex] end; function TextBoxFromRegion(r: Region): GUITextBox; begin result := nil; if not assigned(r) then exit; if not assigned(r^.parent) then exit; if not (r^.kind = gkTextbox) then exit; if (r^.elementIndex < 0) or (r^.elementIndex > High(r^.parent^.textBoxes)) then exit; result := @r^.parent^.textBoxes[r^.elementIndex] end; function ListFromRegion(r: Region): GUIList; overload; begin result := nil; if not assigned(r) then exit; if not assigned(r^.parent) then exit; if not (r^.kind = gkList) then exit; if (r^.elementIndex < 0) or (r^.elementIndex > High(r^.parent^.lists)) then exit; result := @r^.parent^.lists[r^.elementIndex] end; function CheckboxFromRegion(r: Region): GUICheckbox; begin result := nil; if not assigned(r) then exit; if not assigned(r^.parent) then exit; if not (r^.kind = gkCheckBox) then exit; if (r^.elementIndex < 0) or (r^.elementIndex > High(r^.parent^.checkboxes)) then exit; result := @r^.parent^.checkboxes[r^.elementIndex]; end; //--------------------------------------------------------------------------------------- // RadioGroup Code //--------------------------------------------------------------------------------------- function ActiveRadioButtonIndex(RadioGroup: GUIRadioGroup): integer; begin result := -1; if not(assigned(RadioGroup)) then exit; result := RadioGroup^.activeButton; end; function ActionRadioButton(r: Region): Region; begin result := ActionRadioButton(RadioGroupFromRegion(r)); end; function ActionRadioButton(grp: GUIRadioGroup): Region; begin result := nil; if not assigned(grp) then exit; if (grp^.activeButton < 0) or (grp^.activeButton > High(grp^.buttons)) then exit; result := grp^.buttons[grp^.activeButton]; end; procedure SelectRadioButton(r: Region); overload; begin SelectRadioButton(RadioGroupFromRegion(r), r); end; procedure SelectRadioButton(rGroup: GUIRadioGroup; r: Region); overload; var i: integer; begin if not assigned(rGroup) then exit; if RadioGroupFromRegion(r) <> rGroup then exit; // Remove the selection ... rGroup^.activeButton := -1; // Find this button in the group and select it for i := Low(rGroup^.buttons) to High(rGroup^.buttons) do begin if rGroup^.buttons[i] = r then begin rGroup^.activeButton := i; exit; end; end; end; //--------------------------------------------------------------------------------------- // Label Code //--------------------------------------------------------------------------------------- procedure LabelSetText(id: String; newString: String); overload; begin LabelSetText(LabelFromRegion(RegionWithID(id)), newString); end; procedure LabelSetText(pnl: Panel; id, newString: String); overload; begin LabelSetText(LabelFromRegion(RegionWithID(pnl, id)), newString); end; procedure LabelSetText(r: Region; newString: String); overload; begin LabelSetText(LabelFromRegion(r), newString); end; procedure LabelSetText(lb: GUILabel; newString: String); begin if not assigned(lb) then exit; lb^.contentString := newString; end; procedure LabelSetFont(l: GUILabel; s: String); begin if not assigned(l) then exit; l^.font := FontNamed(s); end; function LabelFont(r: Region): Font; overload; begin result := LabelFont(LabelFromRegion(r)); end; function LabelFont(l: GUILabel): Font; begin result := nil; if not assigned(l) then exit; result := l^.font; end; function LabelAlignment(r: Region): FontAlignment; begin result := LabelAlignment(LabelFromRegion(r)); end; function LabelAlignment(tb: GUILabel): FontAlignment; begin result := AlignLeft; if not assigned(tb) then exit; result := tb^.alignment; end; procedure LabelSetAlignment(tb: GUILabel; align: FontAlignment); begin if not assigned(tb) then exit; tb^.alignment := align; end; procedure LabelSetAlignment(r: Region; align: FontAlignment); begin LabelSetAlignment(LabelFromRegion(r), align); end; function LabelText(lb: GUILabel): String; overload; begin if assigned(lb) then result := lb^.contentString else result := ''; end; function LabelText(r: Region): String; overload; begin result := LabelText(LabelFromRegion(r)); end; //--------------------------------------------------------------------------------------- // Textbox Code //--------------------------------------------------------------------------------------- procedure TextboxSetFont(Tb: GUITextbox; f: font); begin if not(assigned(tb)) OR not(assigned(f)) then exit; Tb^.font := f; end; function TextBoxFont(r: Region): Font; overload; begin result := TextBoxFont(TextBoxFromRegion(r)); end; function TextBoxFont(tb: GUITextBox): Font; overload; begin result := nil; if not assigned(tb) then exit; result := tb^.font; end; procedure TextboxSetText(r: Region; s: string); overload; begin TextboxSetText(TextBoxFromRegion(r), s); end; procedure TextboxSetText(r: Region; i: LongInt); overload; begin TextboxSetText(TextBoxFromRegion(r), IntToStr(i)); end; procedure TextboxSetText(r: Region; single: Single); overload; begin TextboxSetText(TextBoxFromRegion(r), FloatToStr(single)); end; procedure TextboxSetText(tb: GUITextBox; s: string); overload; begin if assigned(tb) then tb^.contentString := s; end; procedure TextboxSetText(tb: GUITextBox; i: LongInt); overload; begin TextboxSetText(tb, IntToStr(i)); end; procedure TextboxSetText(tb: GUITextBox; single: Single); overload; begin TextboxSetText(tb, FloatToStr(single)); end; function TextBoxText(id: String): String; overload; begin result := TextBoxText(RegionWithID(id)); end; function TextBoxText(r: Region): String; overload; begin result := TextBoxText(TextBoxFromRegion(r)); end; function TextBoxText(tb: GUITextBox): String; overload; begin result := ''; if not assigned(tb) then exit; result := tb^.contentString; end; function LastTextRead(): string; begin result := GUIC.lastTextRead; end; procedure FinishReadingText(); begin if not assigned(GUIC.activeTextBox) then exit; // Only perform an entry complete if this wasn't cancelled if not TextEntryCancelled() then begin // Read the old value of the text box GUIC.lastTextRead := TextBoxText(GUIC.activeTextBox); // assign the new value TextboxSetText(GUIC.activeTextBox, EndReadingText()); // Which was the last active textbox - so we know where data was entered GUIC.lastActiveTextBox := GUIC.activeTextBox; GUIC.doneReading := true; SendEvent(GUIC.activeTextBox, ekTextEntryEnded); end; GUIC.activeTextBox := nil; end; procedure GUISetActiveTextbox(r: Region); begin GUISetActiveTextbox(TextBoxFromRegion(r)); end; procedure GUISetActiveTextbox(t: GUITextbox); begin if not assigned(t) then exit; GUIC.activeTextBox := t^.region; if ReadingText() then FinishReadingText(); StartReadingTextWithText( t^.contentString, GUIC.foregroundClr, t^.lengthLimit, t^.Font, InsetRectangle(TextboxTextArea(t^.region), 1)); // Need to inset 1 further to match printing text lines end; function TextboxAlignment(r: Region): FontAlignment; begin result := TextboxAlignment(TextBoxFromRegion(r)); end; function TextboxAlignment(tb: GUITextbox): FontAlignment; begin result := AlignLeft; if not assigned(tb) then exit; result := tb^.alignment; end; procedure TextboxSetAlignment(tb: GUITextbox; align: FontAlignment); begin if not assigned(tb) then exit; tb^.alignment := align; end; procedure TextboxSetAlignment(r: Region; align: FontAlignment); begin TextboxSetAlignment(TextBoxFromRegion(r), align); end; //--------------------------------------------------------------------------------------- // List Code //--------------------------------------------------------------------------------------- function ListActiveItemText(ID: String): String; overload; begin result := ListActiveItemText(RegionWithID(id)); end; function ListActiveItemText(pnl: Panel; ID: String): String; overload; var r: Region; begin result := ''; if not assigned(pnl) then exit; r := RegionWithID(pnl, ID); Result := ListItemText(r, ListActiveItemIndex(r)); end; function ListActiveItemText(r:region):String; Overload; begin Result := ListItemText(r, ListActiveItemIndex(r)); end; procedure ListSetActiveItemIndex(lst: GUIList; idx: LongInt); begin if not assigned(lst) then exit; lst^.activeItem := idx; end; procedure ListSetFont(lst: GUITextbox; f: font); begin if not(assigned(lst)) OR not(assigned(f)) then exit; lst^.font := f; end; function ListFont(r: Region): Font; overload; begin result := ListFont(ListFromRegion(r)); end; function ListFont(lst: GUIList): Font; overload; begin result := nil; if not assigned(lst) then exit; result := lst^.font; end; function ListItemText(r: Region; idx: LongInt): String; overload; begin result := ListItemText(ListFromRegion(r), idx); end; function ListItemText(lst: GUIList; idx: LongInt): String; overload; begin result := ''; if not assigned(lst) then exit; if (idx < 0) or (idx > High(lst^.items)) then exit; result := lst^.items[idx].text; end; function ListItemCount(r: Region): LongInt; overload; begin result := ListItemCount(ListFromRegion(r)); end; function ListItemCount(lst:GUIList): LongInt; overload; begin result := 0; if not assigned(lst) then exit; result := Length(lst^.items); end; procedure ListAddItem(lst: GUIList; text: String); begin ListAddItem(lst, nil, text); end; procedure ListAddItem(lst: GUIList; img:Bitmap); begin ListAddItem(lst, img, ''); end; procedure ListAddItem(lst: GUIList; img:Bitmap; text: String); overload; begin ListAddItem(lst, BitmapCellOf(img, -1), text); end; procedure ListAddItem(lst: GUIList; const img: BitmapCell); overload; begin ListAddItem(lst, img, ''); end; procedure ListAddItem(lst: GUIList; const img:BitmapCell; text: String); overload; begin if not assigned(lst) then exit; SetLength(lst^.items, Length(lst^.items) + 1); lst^.items[High(lst^.items)].text := text; //Assign the text to the item lst^.items[High(lst^.items)].image := img; //Assign the image to the item end; procedure ListAddItem(r : Region; const img:BitmapCell); overload; begin ListAddItem(r,img,''); end; procedure ListAddItem(r : Region; const img:BitmapCell; text: String); overload; begin ListAddItem(ListFromRegion(r), img, text); end; procedure ListAddItem(r : Region; text: String); overload; begin ListAddItem(ListFromRegion(r), text); end; procedure ListAddItem(r : Region; img:Bitmap); overload; begin ListAddItem(ListFromRegion(r), img); end; procedure ListAddItem(r : Region; img:Bitmap; text: String); overload; begin ListAddItem(ListFromRegion(r),img, text); end; procedure ListClearItems(lst: GUIList); overload; begin if not assigned(lst) then exit; SetLength(lst^.items, 0); lst^.activeItem := -1; lst^.startingAt := 0; end; procedure ListClearItems(r : Region); overload; begin ListClearItems(ListFromRegion(r)); end; procedure ListRemoveActiveItem(r : region); overload; begin ListRemoveItem(ListFromRegion(r), ListActiveItemIndex(r)); end; procedure ListRemoveActiveItem(s : string); overload; begin ListRemoveActiveItem(RegionWithID(s)); end; procedure ListRemoveItem(lst: GUIList; idx: LongInt); var i: LongInt; begin if not assigned(lst) then exit; if (idx < 0) or (idx > High(lst^.items)) then exit; for i := idx to High(lst^.items) - 1 do begin lst^.items[i] := lst^.items[i + 1]; end; SetLength(lst^.items, Length(lst^.items) - 1); if (lst^.startingAt >= idx) and (idx <> 0) then lst^.startingAt := lst^.startingAt - 1; if lst^.activeItem >= idx then lst^.activeItem := lst^.activeItem - 1; end; function ListTextIndex(lst: GUIList; value: String): LongInt; var i: LongInt; begin result := -1; if not assigned(lst) then exit; for i := Low(lst^.items) to High(lst^.items) do begin //find the text... then exit if lst^.items[i].text = value then begin result := i; exit; end; end; end; function ListBitmapIndex(lst: GUIList; img: Bitmap): LongInt; begin result := ListBitmapIndex(lst, BitmapCellOf(img, -1)); end; function ListBitmapIndex(lst: GUIList; const img: BitmapCell): LongInt; var i: LongInt; begin result := -1; if not assigned(lst) then exit; for i := Low(lst^.items) to High(lst^.items) do begin //find the text... then exit if SameBitmapCell(lst^.items[i].image, img) then begin result := i; exit; end; end; end; function ListScrollIncrement(lst: GUIList): LongInt; begin result := 1; if not assigned(lst) then exit; if lst^.verticalScroll then result := lst^.columns else result := lst^.rows; if result <= 0 then result := 1; end; function ListActiveItemIndex(r: Region): LongInt; overload; begin result := ListActiveItemIndex(ListFromRegion(r)); end; function ListActiveItemIndex(lst: GUIList): LongInt; overload; begin result := -1; if not assigned(lst) then exit; result := lst^.activeItem; end; function ListStartAt(lst: GUIList): LongInt; begin result := 0; if not assigned(lst) then exit; result := lst^.startingAt; end; function ListStartAt(r: Region): LongInt; begin result := ListStartAt(ListFromRegion(r)); end; procedure ListSetStartAt(lst: GUIList; idx: LongInt); begin if not assigned(lst) then exit; if (idx < 0) then idx := 0 else if (idx > High(lst^.items)) then idx := (High(lst^.items) div ListScrollIncrement(lst)) * ListScrollIncrement(lst); lst^.startingAt := idx; end; procedure ListSetStartAt(r: Region; idx: LongInt); begin ListSetStartAt(ListFromRegion(r), idx); end; function ListFontAlignment(r: Region): FontAlignment; begin result := ListFontAlignment(ListFromRegion(r)); end; function ListFontAlignment(lst: GUIList): FontAlignment; begin result := AlignLeft; if not assigned(lst) then exit; result := lst^.alignment; end; procedure ListSetFontAlignment(r: Region; align: FontAlignment); begin ListSetFontAlignment(ListFromRegion(r), align); end; procedure ListSetFontAlignment(lst: GUIList; align: FontAlignment); begin if not assigned(lst) then exit; lst^.alignment := align; end; function ListLargestStartIndex(lst: GUIList): LongInt; var placeCount: LongInt; itemCount: LongInt; begin result := 0; if not assigned(lst) then exit; itemCount := Length(lst^.items); placeCount := lst^.rows * lst^.columns; result := itemCount - placeCount; // Round result := Ceiling(result / ListScrollIncrement(lst)) * ListScrollIncrement(lst); end; //--------------------------------------------------------------------------------------- // Checkbox Code Code //--------------------------------------------------------------------------------------- function CheckboxState(chk: GUICheckbox): Boolean; overload; begin if not assigned(chk) then begin result := false; exit; end; result := chk^.state; end; function CheckboxState(r: Region): Boolean; overload; begin result := CheckboxState(CheckboxFromRegion(r)); end; function CheckboxState(s: String): Boolean; overload; begin result := CheckboxState(CheckboxFromRegion(RegionWithID(s))); end; procedure CheckboxSetState(chk: GUICheckbox; val: Boolean); overload; begin if not assigned(chk) then exit; chk^.state := val; end; procedure CheckboxSetState(r: region; val: Boolean); overload; begin CheckboxSetState(CheckboxFromRegion(r), val); end; // function CheckboxState(ID: String): Boolean; // var // reg: Region; // begin // reg := GetRegionByID(ID); // result := reg^.parent^.checkboxes[reg^.elementIndex].state; // end; procedure ToggleCheckboxState(c: GUICheckbox); begin if not assigned(c) then exit; c^.state := not c^.state; end; //--------------------------------------------------------------------------------------- // Panel Code //--------------------------------------------------------------------------------------- function PanelDraggable(p: panel): boolean; begin if not assigned(p) then exit; Result := p^.draggable; end; procedure PanelSetDraggable(p: panel; b:boolean); begin if not assigned(p) then exit; p^.draggable := b; end; procedure PanelSetX(p: Panel; nX: LongInt); begin if not(assigned(p)) then exit; p^.area.X := nX; end; procedure PanelSetY(p: Panel; nY: LongInt); begin if not(assigned(p)) then exit; p^.area.Y := nY; end; function PanelWidth(p: Panel): LongInt; begin result := -1; if not(assigned(p)) then exit; result := p^.area.width; end; function PanelHeight(p: Panel): LongInt; begin result := -1; if not(assigned(p)) then exit; result := p^.area.height; end; function PanelX(p: Panel): Single; begin result := -1; if not(assigned(p)) then exit; result := p^.area.x; end; function PanelY(p: Panel): Single; begin result := -1; if not(assigned(p)) then exit; result := p^.area.y; end; function PanelVisible(p: Panel): boolean; begin result := false; if not(assigned(p)) then exit; result := p^.visible; end; procedure AddPanelToGUI(p: Panel); begin if assigned(p) then begin SetLength(GUIC.panels, Length(GUIC.panels) + 1); GUIC.panels[High(GUIC.panels)] := p; end; end; procedure ActivatePanel(p: Panel); begin if assigned(p) then p^.active := true; end; procedure DeactivatePanel(p: Panel); begin if assigned(p) then p^.active := false; end; procedure ToggleActivatePanel(p: Panel); begin if assigned(p) then p^.active := not p^.active; end; function InitPanel(name, filename:string): Panel; begin New(result); result^.name := name; result^.filename := filename; with result^ do begin panelID := -1; area := RectangleFrom(0,0,0,0); visible := false; active := true; // Panels are active by default - you need to deactivate them specially... draggable := false; DrawAsVectors := true; modal := false; panelBitmap := nil; panelBitmapActive := nil; panelBitmapInactive := nil; SetLength(regions, 0); SetLength(labels, 0); SetLength(checkBoxes, 0); SetLength(radioGroups, 0); SetLength(textBoxes, 0); SetLength(lists, 0); InitNamedIndexCollection(regionIds); //Setup the name <-> id mappings end; end; function NewPanel(pnlName: String): Panel; var pnl: Panel; obj: tResourceContainer; begin if GUIC.panelIds.containsKey(pnlName) then begin result := PanelNamed(pnlName); exit; end; pnl := InitPanel(pnlName, 'RuntimePanel'); obj := tResourceContainer.Create(pnl); if not GUIC.panelIds.setValue(pnlname, obj) then begin DoFreePanel(pnl); result := nil; end else begin AddPanelToGUI(pnl); result := pnl; end; end; procedure ShowPanelDialog(p: Panel); begin if assigned(p) then begin if p^.visible then //hide it... ToggleShowPanel(p); // show the panel last... ToggleShowPanel(p); // and make it modal p^.modal := true; end; end; procedure ShowPanel(p: Panel); begin if assigned(p) and (not p^.visible) then ToggleShowPanel(p); end; procedure HidePanel(p: Panel); begin if assigned(p) and (p^.visible) then ToggleShowPanel(p); end; procedure ToggleShowPanel(p: Panel); var i: LongInt; found: Boolean; begin if assigned(p) then begin p^.visible := not p^.visible; // set to non-modal by default p^.modal := false; if p^.visible then begin // Now visible so add to the visible panels SetLength(GUIC.visiblePanels, Length(GUIC.visiblePanels) + 1); GUIC.visiblePanels[High(GUIC.visiblePanels)] := p; end else begin // No longer visible - remove from visible panels found := false; // Search for panel and remove from visible panels for i := 0 to High(GUIC.visiblePanels) do begin if (not found) then begin if (p = GUIC.visiblePanels[i]) then found := true; end else // found - so copy over... GUIC.visiblePanels[i - 1] := GUIC.visiblePanels[i] end; SetLength(GUIC.visiblePanels, Length(GUIC.visiblePanels) - 1); end; end; end; function MousePointInPanel(pnl: Panel): Point2D; begin result.x := -1; result.y := -1; if not assigned(pnl) then exit; result := PointAdd(MousePosition(), InvertVector(RectangleTopLeft(pnl^.area))); end; function PanelClicked(): Panel; begin result := nil; if not ModalBefore(GUIC.panelClicked) then result := GUIC.panelClicked; // result := nil; // if not MouseClicked(Leftbutton) then exit; // // result := PanelAtPoint(MousePosition()); end; function PanelClicked(pnl: Panel): Boolean; begin if not(assigned(pnl)) then exit; if not(assigned(GUIC.panelClicked)) then exit; result := GUIC.panelClicked = pnl; end; //============================================================================= // Create Panels/GUI Elements/Regions etc. //============================================================================= function StringToKind(s: String): GUIElementKind; begin if Lowercase(s) = 'button' then result := gkButton else if Lowercase(s) = 'label' then result := gkLabel else if Lowercase(s) = 'textbox' then result := gkTextBox else if Lowercase(s) = 'checkbox' then result := gkCheckBox else if Lowercase(s) = 'radiogroup' then result := gkRadioGroup else if Lowercase(s) = 'list' then result := gkList else RaiseException(s + ' is an invalid kind for region.'); end; procedure CreateLabel(forRegion: Region; d: string; result: Panel); var newLbl: GUILabelData; begin //Format is // 1, 2, 3, 4, 5, 6, 7, 8, 9, // x, y, w, h, 5, id , font, align, text newLbl.font := FontNamed(Trim(ExtractDelimited(7, d, [',']))); newLbl.alignment := TextAlignmentFrom(Trim(ExtractDelimited(8, d, [',']))); newLbl.contentString := Trim(ExtractDelimited(9, d, [','])); SetLength(result^.Labels, Length(result^.Labels) + 1); result^.labels[High(result^.labels)] := newLbl; forRegion^.elementIndex := High(result^.labels); // The label index for the region -> so it knows which label end; procedure AddRegionToGroup(regToAdd: Region; groupToRecieve: GUIRadioGroup); begin SetLength(groupToRecieve^.buttons, Length(groupToRecieve^.buttons) + 1); groupToRecieve^.buttons[High(groupToRecieve^.buttons)] := regToAdd; end; procedure CreateRadioButton(forRegion: Region; data: String; result: Panel); var newRadioGroup: GUIRadioGroupData; i: LongInt; radioGroupID: string; begin radioGroupID := Trim(ExtractDelimited(7,data,[','])); for i := Low(result^.radioGroups) to High(result^.radioGroups) do begin if (radioGroupID = result^.radioGroups[i].GroupID) then begin AddRegionToGroup(forRegion, @result^.radioGroups[i]); forRegion^.elementIndex := i; exit; end; end; SetLength(newRadioGroup.buttons, 0); newRadioGroup.GroupID := radioGroupID; AddRegionToGroup(forRegion, @newRadioGroup); newRadioGroup.activeButton := 0; // add to panel, record element index. SetLength(result^.radioGroups, Length(result^.radioGroups) + 1); result^.radioGroups[High(result^.radioGroups)] := newRadioGroup; forRegion^.elementIndex := High(result^.radioGroups); end; procedure CreateCheckbox(forRegion: Region; data: string; result: Panel); begin SetLength(result^.Checkboxes, Length(result^.Checkboxes) + 1); result^.Checkboxes[High(result^.Checkboxes)].state := LowerCase(ExtractDelimited(7, data, [','])) = 'true'; forRegion^.elementIndex := High(result^.Checkboxes); end; procedure CreateTextbox(r: region; data: string; result: panel); var newTextbox: GUITextboxData; begin //Format is // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // x, y, w, h, 5, id , font, maxLen, align, text if CountDelimiter(data, ',') <> 9 then begin RaiseException('Error with textbox (' + data + ') should have 10 values (x, y, w, h, 5, id, font, maxLen, align, text)'); exit; end; newTextbox.font := FontNamed(Trim(ExtractDelimited(7, data, [',']))); newTextbox.lengthLimit := StrToInt(Trim(ExtractDelimited(8, data, [',']))); newTextBox.alignment := TextAlignmentFrom(Trim(ExtractDelimited(9, data, [',']))); newTextBox.contentString := Trim(ExtractDelimited(10, data, [','])); newTextBox.region := r; SetLength(result^.textBoxes, Length(result^.textBoxes) + 1); result^.textBoxes[High(result^.textBoxes)] := newTextbox; r^.ElementIndex := High(result^.textBoxes); end; procedure CreateList(r: Region; data: string; result: Panel); var newList: GUIListData; scrollSz, rhs, btm, height, width: LongInt; begin //Format is // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 14 // x, y, w, h, 5, ListID, Columns, Rows, ActiveItem, fontID, alignment, scrollSize, scrollKind, scrollbutton bitmap newList.columns := StrToInt(Trim(ExtractDelimited(7, data, [',']))); newList.rows := StrToInt(Trim(ExtractDelimited(8, data, [',']))); newList.activeItem := StrToInt(Trim(ExtractDelimited(9, data, [',']))); newList.font := FontNamed(Trim(ExtractDelimited(10, data, [',']))); newList.alignment := TextAlignmentFrom(Trim(ExtractDelimited(11, data, [',']))); newList.scrollSize := StrToInt(Trim(ExtractDelimited(12, data, [','])));; newList.verticalScroll := LowerCase(Trim(ExtractDelimited(13, data, [',']))) = 'v'; if Trim(ExtractDelimited(14, data, [','])) <> 'n' then begin //LoadBitmap(Trim(ExtractDelimited(13, data, [',']))); newList.scrollButton := LoadBitmap(Trim(ExtractDelimited(14, data, [',']))); //BitmapNamed(Trim(ExtractDelimited(13, data, [',']))); end else newList.scrollButton := nil; scrollSz := newList.scrollSize; // Start at the fist item in the list, or the activeItem if newList.activeItem = -1 then newList.startingAt := 0 else newList.startingAt := newList.activeItem; rhs := r^.area.width - scrollSz; btm := r^.area.height - scrollSz; height := r^.area.height; width := r^.area.width; // Calculate col and row sizes if newList.verticalScroll then begin newList.colWidth := rhs div newList.columns; newList.rowHeight := height div newList.rows; // Set scroll buttons newList.scrollUp := RectangleFrom( rhs, 0, scrollSz, scrollSz); newList.scrollDown := RectangleFrom( rhs, btm, scrollSz, scrollSz); newList.scrollArea := RectangleFrom( rhs, scrollSz, scrollSz, height - (2 * scrollSz)); end else begin newList.colWidth := r^.area.width div newList.columns; newList.rowHeight := btm div newList.rows; // Set scroll buttons newList.scrollUp := RectangleFrom( 0, btm, scrollSz, scrollSz); newList.scrollDown := RectangleFrom( rhs, btm, scrollSz, scrollSz); newList.scrollArea := RectangleFrom( scrollSz, btm, width - (2 * scrollSz), scrollSz); end; SetLength(newList.placeHolder, (newList.columns * newList.rows)); SetLength(newList.items, 0); SetLength(result^.lists, Length(result^.lists) + 1); result^.lists[High(result^.lists)] := newList; r^.elementIndex := High(result^.lists); end; type RegionDataArray = Array of RegionData; // Rewires points to regions in the panel, assumes that the // newRegions is larger than or equal to the number of old regions in the panel procedure RewireRegions(p: Panel; newRegions: RegionDataArray); var i, j, elemIdx: LongInt; begin // for all of the regions for i := 0 to High(p^.regions) do begin //Copy the old region data to the new region data newRegions[i] := p^.regions[i]; //Get the element index elemIdx := p^.regions[i].elementIndex; // if a textbox or a radio group, remap pointers case p^.regions[i].kind of gkTextbox: p^.textBoxes[elemIdx].region := @newRegions[i]; gkRadioGroup: begin for j := 0 to High(p^.radioGroups[elemIdx].buttons) do begin //searching for the button that points to the old regions if p^.radioGroups[elemIdx].buttons[j] = @p^.regions[i] then begin p^.radioGroups[elemIdx].buttons[j] := @newRegions[i]; break; // exit inner loop end; end; end; end; // end case end;// end for // move the new regions in (copies pointer) p^.regions := newRegions; end; procedure AddRegionToPanelWithString(d: string; p: panel); var regID: string; regX, regY: Single; regW, regH, addedIdx: integer; r: RegionData; newRegions: RegionDataArray; begin // Format is // x, y, w, h, kind, id regX := StrToFloat(Trim(ExtractDelimited(1, d, [',']))); regY := StrToFloat(Trim(ExtractDelimited(2, d, [',']))); regW := StrToInt(Trim(ExtractDelimited(3, d, [',']))); regH := StrToInt(Trim(ExtractDelimited(4, d, [',']))); r.kind := StringToKind(Trim(ExtractDelimited(5, d, [',']))); regID := Trim(ExtractDelimited(6, d, [','])); // this should be done when used... so that moving the panel effects this // // regX += p^.area.x; // regY += p^.area.y; addedIdx := AddName(p^.regionIds, regID); //Allocate the index if High(p^.Regions) < addedIdx then begin // Make more space and rewire region pointers SetLength(newRegions, addedIdx + 1); RewireRegions(p, newRegions); end; r.regionIdx := addedIdx; r.area := RectangleFrom(regX, regY, regW, regH); r.active := true; r.stringID := regID; r.elementIndex := -1; r.parent := p; SetLength(r.callbacks, 0); p^.Regions[addedIdx] := r; case r.kind of gkButton: ; gkLabel: CreateLabel(@p^.Regions[addedIdx],d,p); gkCheckbox: CreateCheckbox(@p^.Regions[addedIdx],d,p); gkRadioGroup: CreateRadioButton(@p^.Regions[addedIdx],d,p); gkTextbox: CreateTextbox(@p^.Regions[addedIdx],d,p); gkList: CreateList(@p^.Regions[addedIdx], d,p); end; end; function DoLoadPanel(filename, name: string): Panel; var pathToFile, line, id, data: string; panelFile: text; lineNo: integer; regionDataArr: Array of String; procedure StoreRegionData(data: String); begin SetLength(regionDataArr, Length(regionDataArr) + 1); regionDataArr[High(regionDataArr)] := data; end; procedure ProcessLine(); begin // Split line into id and data around : id := ExtractDelimited(1, line, [':']); // where id comes before... data := ExtractDelimited(2, line, [':']); // ...and data comes after. // Verify that id is a single char if Length(id) <> 1 then begin RaiseException('Error at line ' + IntToStr(lineNo) + ' in panel: ' + filename + '. Error with id: ' + id + '. This should be a single character.'); exit; // Fail end; // Process based on id case LowerCase(id)[1] of // in all cases the data variable is read 'x': result^.area.x := MyStrToInt(data, false); 'y': result^.area.y := MyStrToInt(data, false); 'w': result^.area.width := MyStrToInt(data, false); 'h': result^.area.height := MyStrToInt(data, false); 'b': begin LoadBitmap(Trim(data)); result^.panelBitmap := BitmapNamed(Trim(data)); end; 'a': begin LoadBitmap(Trim(data)); result^.panelBitmapActive := BitmapNamed(Trim(data)); end; 'i': begin LoadBitmap(Trim(data)); result^.panelBitmapInactive := BitmapNamed(Trim(data)); end; 'r': StoreRegionData(data); 'd': result^.draggable := (LowerCase(Trim(data)) = 'true'); 'v': result^.DrawAsVectors := (LowerCase(Trim(data)) = 'true'); else begin RaiseException('Error at line ' + IntToStr(lineNo) + ' in panel: ' + filename + '. Error with id: ' + id + '. This should be one of the characters defined in the template.'); exit; end; end; end; procedure CreateRegions(); var i: LongInt; begin SetLength(result^.regions, Length(regionDataArr)); for i := Low(regionDataArr) to High(regionDataArr) do begin AddRegionToPanelWithString(regionDataArr[i], result); end; end; procedure SetupListPlaceholders(); var tempListPtr: GUIList; workingCol, workingRow: LongInt; j, k: LongInt; begin for j := Low(result^.Regions) to High(result^.Regions) do begin //Get the region as a list (will be nil if not list...) tempListPtr := ListFromRegion(@result^.regions[j]); if assigned(tempListPtr) then begin workingCol := 0; workingRow := 0; for k := Low(tempListPtr^.placeHolder) to High(tempListPtr^.placeHolder) do begin tempListPtr^.placeHolder[k].x := (workingCol * tempListPtr^.colWidth); tempListPtr^.placeHolder[k].y := (workingRow * tempListPtr^.rowHeight); tempListPtr^.placeHolder[k].width := (tempListPtr^.colWidth); tempListPtr^.placeHolder[k].height := (tempListPtr^.rowHeight); workingCol += 1; if workingCol >= tempListPtr^.columns then begin workingCol := 0; workingRow += 1; end; end; end; end; end; begin pathToFile := filename; if not FileExists(pathToFile) then begin pathToFile := PathToResource(filename, PanelResource); if not FileExists(pathToFile) then begin RaiseException('Unable to locate panel ' + filename); exit; end; end; // Initialise the resulting panel result := InitPanel(name, filename); Assign(panelFile, pathToFile); Reset(panelFile); try SetLength(regionDataArr, 0); lineNo := -1; while not EOF(panelFile) do begin lineNo := lineNo + 1; ReadLn(panelFile, line); line := Trim(line); if Length(line) = 0 then continue; //skip empty lines if MidStr(line,1,2) = '//' then continue; //skip lines starting with // - the first character at index 0 is the length of the string. ProcessLine(); end; CreateRegions(); SetupListPlaceholders(); finally Close(panelFile); end; end; procedure GUISetForegroundColor(c:Color); begin GUIC.foregroundClr := c; end; procedure GUISetForegroundColorInactive(c:color); begin GUIC.foregroundClrInactive := c; end; procedure GUISetBackgroundColorInactive(c:color); begin GUIC.backgroundClrInactive := c; end; procedure GUISetBackgroundColor(c:Color); begin GUIC.backgroundClr := c; end; procedure DrawGUIAsVectors(b : boolean); begin GUIC.VectorDrawing := b; end; function PanelActive(pnl: Panel): Boolean; begin if assigned(pnl) then result := pnl^.active and not ModalBefore(pnl) else result := false; end; function IsSet(toCheck, checkFor: GuiElementKind): Boolean; overload; begin result := (LongInt(toCheck) and LongInt(checkFor)) = LongInt(checkFor); end; function PointInRegion(pt: Point2D; p: Panel; kind: GuiElementKind): Boolean; overload; var i: LongInt; curr: Region; begin result := false; if not assigned(p) then exit; for i := Low(p^.Regions) to High(p^.Regions) do begin curr := @p^.Regions[i]; if PointInRect(MousePointInPanel(p), curr^.area) and IsSet(kind, curr^.kind) then begin result := true; exit; end; end; end; function PointInRegion(pt: Point2D; p: Panel): Boolean; overload; begin result := PointInRegion(pt, p, gkAnyKind); end; function PanelAtPoint(pt: Point2D): Panel; var i: LongInt; curPanel: Panel; begin result := nil; for i := High(GUIC.visiblePanels) downto Low(GUIC.visiblePanels) do begin curPanel := GUIC.visiblePanels[i]; if PointInRect(pt, GUIC.visiblePanels[i]^.area) then begin result := curPanel; exit; end; end; end; procedure DragPanel(); begin if not IsDragging() then exit; if IsDragging() then begin MovePanel(GUIC.panelDragging, MouseMovement()); end; end; function IsDragging(): Boolean; begin result := assigned(GUIC.panelDragging) and GUIC.panelDragging^.draggable; end; function IsDragging(pnl: Panel): Boolean; begin result := false; if not(assigned(pnl)) then exit; if not(assigned(GUIC.panelDragging)) then exit; result := GUIC.panelDragging = pnl; end; procedure StartDragging(); var mp: Point2D; curPanel: Panel; begin mp := MousePosition(); curPanel := PanelAtPoint(mp); if not PointInRegion(mp, curPanel, GuiElementKind(LongInt(gkAnyKind) and not LongInt(gkLabel))) then begin GUIC.panelDragging := curPanel; end else begin GUIC.panelDragging := nil; end; end; procedure StopDragging(); begin GUIC.panelDragging := nil; GUIC.downRegistered := false; end; procedure MovePanel(p: Panel; mvmt: Vector); begin if not assigned(p) then exit; p^.area := RectangleOffset(p^.area, mvmt); end; // function DoLoadPanel(filename, name: String): Panel; // begin // {$IFDEF TRACE} // TraceEnter('sgUserInterface', 'DoLoadPanel', name + ' = ' + filename); // {$ENDIF} // // if not FileExists(filename) then // begin // filename := PathToResource(filename, PanelResource); // if not FileExists(filename) then // begin // RaiseException('Unable to locate panel ' + filename); // exit; // end; // end; // // New(result); // result^.effect := Mix_LoadWAV(PChar(filename)); // result^.filename := filename; // result^.name := name; // // if result^.effect = nil then // begin // Dispose(result); // RaiseException('Error loading panel: ' + MIX_GetError()); // exit; // end; // // {$IFDEF TRACE} // TraceExit('sgUserInterface', 'DoLoadPanel', HexStr(result)); // {$ENDIF} // end; function LoadPanel(filename: String): Panel; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'LoadPanel', filename); {$ENDIF} result := MapPanel(filename, filename); {$IFDEF TRACE} TraceExit('sgUserInterface', 'LoadPanel'); {$ENDIF} end; function MapPanel(name, filename: String): Panel; var obj: tResourceContainer; pnl: Panel; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'MapPanel', name + ' = ' + filename); {$ENDIF} if GUIC.panelIds.containsKey(name) then begin result := PanelNamed(name); exit; end; pnl := DoLoadPanel(filename, name); obj := tResourceContainer.Create(pnl); if not GUIC.panelIds.setValue(name, obj) then begin DoFreePanel(pnl); result := nil; end else begin AddPanelToGUI(pnl); result := pnl; end; {$IFDEF TRACE} TraceExit('sgUserInterface', 'MapPanel'); {$ENDIF} end; // private: // Called to actually free the resource procedure DoFreePanel(var pnl: Panel); var i, j: LongInt; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'DoFreePanel', 'pnl = ' + HexStr(pnl)); {$ENDIF} if assigned(pnl) then begin if GUIC.panelDragging = pnl then GUIC.panelDragging := nil; if dialog.dialogPanel = pnl then dialog.dialogPanel := nil; HidePanel(pnl); for i := Low(GUIC.panels) to High(GUIC.panels) do begin if GUIC.panels[i] = pnl then begin for j := i to (High(GUIC.panels) - 1) do begin GUIC.panels[j] := GUIC.panels[j + 1] end; SetLength(GUIC.panels, Length(GUIC.panels) - 1); break; end; end; CallFreeNotifier(pnl); FreeNamedIndexCollection(pnl^.regionIds); Dispose(pnl); end; pnl := nil; {$IFDEF TRACE} TraceExit('sgUserInterface', 'DoFreePanel'); {$ENDIF} end; procedure FreePanel(var pnl: Panel); begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'FreePanel', 'pnl = ' + HexStr(pnl)); {$ENDIF} if(assigned(pnl)) then begin ReleasePanel(pnl^.name); end; pnl := nil; {$IFDEF TRACE} TraceExit('sgUserInterface', 'FreePanel'); {$ENDIF} end; procedure ReleasePanel(name: String); var pnl: Panel; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'ReleasePanel', 'pnl = ' + name); {$ENDIF} pnl := PanelNamed(name); if (assigned(pnl)) then begin GUIC.panelIds.remove(name).Free(); DoFreePanel(pnl); end; {$IFDEF TRACE} TraceExit('sgUserInterface', 'ReleasePanel'); {$ENDIF} end; procedure ReleaseAllPanels(); begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'ReleaseAllPanels', ''); {$ENDIF} ReleaseAll(GUIC.panelIds, @ReleasePanel); {$IFDEF TRACE} TraceExit('sgUserInterface', 'ReleaseAllPanels'); {$ENDIF} end; function HasPanel(name: String): Boolean; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'HasPanel', name); {$ENDIF} result := GUIC.panelIds.containsKey(name); {$IFDEF TRACE} TraceExit('sgUserInterface', 'HasPanel', BoolToStr(result, true)); {$ENDIF} end; function PanelNamed(name: String): Panel; var tmp : TObject; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'PanelNamed', name); {$ENDIF} tmp := GUIC.panelIds.values[name]; if assigned(tmp) then result := Panel(tResourceContainer(tmp).Resource) else result := nil; {$IFDEF TRACE} TraceExit('sgUserInterface', 'PanelNamed', HexStr(result)); {$ENDIF} end; function PanelName(pnl: Panel): String; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'PanelName', HexStr(pnl)); {$ENDIF} if assigned(pnl) then result := pnl^.name else result := ''; {$IFDEF TRACE} TraceExit('sgUserInterface', 'PanelName', result); {$ENDIF} end; function PanelFilename(pnl: Panel): String; begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'PanelFilename', HexStr(pnl)); {$ENDIF} if assigned(pnl) then result := pnl^.filename else result := ''; {$IFDEF TRACE} TraceExit('sgUserInterface', 'PanelFilename', result); {$ENDIF} end; procedure UpdateDrag(); begin // if mouse is down and this is the first time we see it go down if MouseDown(LeftButton) and not GUIC.downRegistered then begin GUIC.downRegistered := true; if ReadingText() then FinishReadingText(); StartDragging(); end // if mouse is now up... and it was down before... else if MouseUp(LeftButton) and GUIC.downRegistered then begin StopDragging(); end; // If it is dragging then... if IsDragging() then DragPanel(); end; // Dialog code procedure InitialiseFileDialog(); begin with dialog do begin dialogPanel := PanelNamed('fdFileDialog'); lastSelectedFile := -1; lastSelectedPath := -1; cancelled := false; end; end; procedure ShowOpenDialog(select: FileDialogSelectType); overload; begin InitialiseFileDialog(); with dialog do begin LabelSetText(dialogPanel, 'OkLabel', 'Open'); LabelSetText(dialogPanel, 'FileEntryLabel', 'Open'); allowNew := false; selectType := select; ShowPanelDialog(dialogPanel); if length(currentPath) = 0 then DialogSetPath(GetUserDir()); end; end; procedure ShowOpenDialog(); overload; begin ShowOpenDialog(fdFilesAndDirectories); end; procedure ShowSaveDialog(select: FileDialogSelectType); overload; begin InitialiseFileDialog(); with dialog do begin LabelSetText(dialogPanel, 'OkLabel', 'Save'); LabelSetText(dialogPanel, 'FileEntryLabel', 'Save'); allowNew := true; selectType := select; ShowPanelDialog(dialogPanel); if length(currentPath) = 0 then DialogSetPath(GetUserDir()); end; end; procedure ShowSaveDialog(); overload; begin ShowSaveDialog(fdFilesAndDirectories); end; function DialogComplete(): Boolean; begin result := (dialog.complete) and (Not(dialog.cancelled)); end; function DialogCancelled(): Boolean; begin result := dialog.cancelled; end; function DialogPath(): String; begin if dialog.cancelled then result := '' else result := ExpandFileName(dialog.currentSelectedPath); end; procedure UpdateDialogPathText(); var selectedPath: String; pathTxt: Region; begin selectedPath := dialog.currentSelectedPath; pathTxt := RegionWithId(dialog.dialogPanel,'PathTextbox'); // WriteLn('tw: ', TextWidth(TextboxFont(pathTxt), selectedPath)); // WriteLn('rw: ', RegionWidth(pathTxt)); if TextWidth(TextboxFont(pathTxt), selectedPath) > RegionWidth(pathTxt) then TextboxSetAlignment(pathTxt, AlignRight) else TextboxSetAlignment(pathTxt, AlignLeft); TextboxSetText(pathTxt, selectedPath); end; function IsSet(toCheck, checkFor: FileDialogSelectType): Boolean; overload; begin result := (LongInt(toCheck) and LongInt(checkFor)) = LongInt(checkFor); end; procedure ShowErrorMessage(msg: String); begin LabelSetText(dialog.dialogPanel, 'ErrorLabel', msg); PlaySoundEffect(SoundEffectNamed('fdDialogError'), 0.5); end; procedure DialogSetPath(fullname: String); var tmpPath, path, filename: String; paths: Array [0..255] of PChar; procedure _PopulatePathList(); var pathList: GUIList; i, len: LongInt; begin pathList := ListFromRegion(RegionWithId(dialog.dialogPanel, 'PathList')); // Clear the list of all of its items ListClearItems(pathList); // Add the drive letter at the start if Length(ExtractFileDrive(path)) = 0 then ListAddItem(pathList, PathDelim) else ListAddItem(pathList, ExtractFileDrive(path)); // Set the details in the path list len := GetDirs(tmpPath, paths); //NOTE: need to use tmpPath as this strips separators from pass in string... // Loop through the directories adding them to the list for i := 0 to len - 1 do begin ListAddItem(pathList, paths[i]); end; // Ensure that the last path is visible in the list ListSetStartAt(pathList, ListLargestStartIndex(pathList)); end; procedure _PopulateFileList(); var filesList: GUIList; info : TSearchRec; begin filesList := ListFromRegion(RegionWithId(dialog.dialogPanel, 'FilesList')); // Clear the files in the filesList ListClearItems(filesList); //Loop through the directories if FindFirst (dialog.currentPath + '*', faAnyFile and faDirectory, info) = 0 then begin repeat with Info do begin if (attr and faDirectory) = faDirectory then begin // its a directory... always add it ListAddItem(filesList, BitmapNamed('fdFolder'), name); end else begin // Its a file ... add if not dir only if IsSet(dialog.selectType, fdFiles) then begin ListAddItem(filesList, BitmapNamed('fdFile'), name); end; end; end; until FindNext(info) <> 0; end; FindClose(info); end; procedure _SelectFileInList(); var filesList: GUIList; fileIdx: LongInt; begin filesList := ListFromRegion(RegionWithId(dialog.dialogPanel, 'FilesList')); if Length(filename) > 0 then begin fileIdx := ListTextIndex(filesList, filename); ListSetActiveItemIndex(filesList, fileIdx); ListSetStartAt(filesList, fileIdx); end; end; begin // expand the relative path to absolute if not ExtractFileAndPath(fullname, path, filename, dialog.allowNew) then begin ShowErrorMessage('Unable to find file or path.'); exit; end; // Get the path without the ending delimiter (if one exists...) tmpPath := ExcludeTrailingPathDelimiter(path); with dialog do begin currentPath := IncludeTrailingPathDelimiter(tmpPath); currentSelectedPath := path + filename; lastSelectedPath := -1; lastSelectedFile := -1; end; UpdateDialogPathText(); _PopulatePathList(); _PopulateFileList(); _SelectFileInList(); end; procedure DialogCheckComplete(); var path: String; begin path := DialogPath(); if (not dialog.allowNew) and (not FileExists(path)) then begin ShowErrorMessage('Select an existing file or path.'); exit; end; // The file exists, but is not a directory and files cannot be selected if (not IsSet(dialog.selectType, fdFiles)) and FileExists(path) and (not DirectoryExists(path)) then begin ShowErrorMessage('Please select a directory.'); exit; end; if (not IsSet(dialog.selectType, fdDirectories)) and DirectoryExists(path) then begin ShowErrorMessage('Please select a file.'); exit; end; Dialog.Complete := true; HidePanel(dialog.dialogPanel); end; procedure UpdateFileDialog(); var clicked: Region; procedure _PerformFileListClick(); var selectedText, selectedPath: String; selectedIdx: LongInt; begin // Get the idx of the item selected in the files list selectedIdx := ListActiveItemIndex(clicked); if (selectedIdx >= 0) and (selectedIdx < ListItemCount(clicked)) then begin selectedText := ListItemText(clicked, selectedIdx); selectedPath := dialog.currentPath + selectedText; end else exit; // if it is double click... if (dialog.lastSelectedFile = selectedIdx) then begin if DirectoryExists(selectedPath) then DialogSetPath(selectedPath) else DialogCheckComplete(); end else begin // Update the selected file for double click dialog.lastSelectedFile := selectedIdx; // Update the selected path and its label dialog.currentSelectedPath := selectedPath; UpdateDialogPathText(); end; end; procedure _PerformPathListClick(); var tmpPath, newPath: String; selectedIdx, i, len: LongInt; paths: Array [0..256] of PChar; begin // Get the idx of the item selected in the paths selectedIdx := ListActiveItemIndex(clicked); // if it is double click... if (dialog.lastSelectedPath = selectedIdx) and (selectedIdx >= 0) and (selectedIdx < ListItemCount(clicked)) then begin // Get the parts of the current path, and reconstruct up to (and including) selectedIdx tmpPath := dialog.currentPath; len := GetDirs(tmpPath, paths); //NOTE: need to use tmpPath as this strips separators from pass in string... newPath := ExtractFileDrive(dialog.currentPath) + PathDelim; for i := 0 to Min(selectedIdx - 1, len) do begin //Need to exclude trailing path delimiter as some paths will include this at the end... newPath := newPath + ExcludeTrailingPathDelimiter(paths[i]) + PathDelim; end; DialogSetPath(newPath); end else dialog.lastSelectedPath := selectedIdx; end; procedure _PerformCancelClick(); begin HidePanel(dialog.dialogPanel); dialog.cancelled := true; end; procedure _PerformOkClick(); begin DialogCheckComplete(); end; procedure _PerformChangePath(); var newPath: String; begin newPath := TextboxText(RegionWithID(dialog.dialogPanel, 'PathTextbox')); DialogSetPath(newPath); end; begin if PanelClicked() = dialog.dialogPanel then begin clicked := RegionClicked(); if clicked = RegionWithID(dialog.dialogPanel, 'FilesList') then _PerformFileListClick() else if clicked = RegionWithID(dialog.dialogPanel, 'PathList') then _PerformPathListClick() else if clicked = RegionWithID(dialog.dialogPanel, 'CancelButton') then _PerformCancelClick() else if clicked = RegionWithID(dialog.dialogPanel, 'OkButton') then _PerformOkClick(); end; if GUITextEntryComplete() and (RegionOfLastUpdatedTextBox() = RegionWithID(dialog.dialogPanel, 'PathTextbox')) then begin _PerformChangePath(); end; end; procedure UpdateInterface(); procedure _UpdateTextEntry(); var pnl: Panel; r: Region; txtCount, inc, idx: LongInt; txt: GUITextBox; begin //Enable tabbing between text boxes if assigned(GUIC.activeTextBox) and KeyTyped(vk_tab) then begin r := GUIC.activeTextBox; pnl := r^.parent; txtCount := Length(pnl^.textBoxes); if KeyDown(vk_lshift) or KeyDown(vk_rshift) then inc := -1 else inc := +1; // Only tab if more than one textbox if txtCount > 1 then begin FinishReadingText(); idx := (r^.elementIndex + inc) mod txtCount; if idx < 0 then idx := idx + txtCount; txt := @pnl^.textBoxes[idx]; GUISetActiveTextbox(txt); end; end; end; var pnl: Panel; begin dialog.Complete := false; GUIC.doneReading := false; GUIC.lastClicked := nil; UpdateDrag(); if AnyKeyPressed() then _UpdateTextEntry(); pnl := PanelAtPoint(MousePosition()); if MouseClicked(Leftbutton) then GUIC.panelClicked := pnl else GUIC.panelClicked := nil; if PanelActive(pnl) then begin HandlePanelInput(pnl); end; if assigned(GUIC.activeTextbox) and not ReadingText() then FinishReadingText(); if PanelVisible(dialog.dialogPanel) then UpdateFileDialog(); end; procedure RegisterEventCallback(r: Region; callback: GUIEventCallback); begin if not assigned(r) then exit; with r^ do begin SetLength(callbacks, Length(callbacks) + 1); callbacks[High(callbacks)] := callback; end; end; //============================================================================= initialization begin {$IFDEF TRACE} TraceEnter('sgUserInterface', 'Initialise', ''); {$ENDIF} InitialiseSwinGame(); SetLength(GUIC.panels, 0); SetLength(GUIC.visiblePanels, 0); GUIC.globalGUIFont := nil; // Color set on loading window GUIC.VectorDrawing := false; GUIC.lastClicked := nil; GUIC.activeTextBox := nil; GUIC.lastActiveTextBox := nil; GUIC.doneReading := false; GUIC.lastTextRead := ''; GUIC.downRegistered := false; GUIC.panelDragging := nil; GUIC.panelIds := TStringHash.Create(False, 1024); with dialog do begin dialogPanel := nil; currentPath := ''; // The path to the current directory being shown currentSelectedPath := ''; // The path to the file selected by the user cancelled := false; allowNew := false; selectType := fdFilesAndDirectories; onlyFiles := false; lastSelectedFile := -1; lastSelectedPath := -1; complete := false; end; {$IFDEF TRACE} TraceExit('sgUserInterface', 'Initialise'); {$ENDIF} 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.5 10/26/2004 11:08:04 PM JPMugaas Updated refs. Rev 1.4 2004.02.03 5:43:54 PM czhower Name changes Rev 1.3 2/1/2004 3:33:46 AM JPMugaas Reenabled. SHould work in DotNET. Rev 1.2 1/21/2004 3:11:12 PM JPMugaas InitComponent Rev 1.1 2003.10.12 4:03:58 PM czhower compile todos Rev 1.0 11/13/2002 07:55:32 AM JPMugaas 2000-Dec-22 Kudzu -Changed from a TTimer to a sleeping thread to eliminate the reference to ExtCtrls. This was the only unit in all of Indy that used this unit and caused the pkg to rely on extra pkgs. -Changed Enabled to Active to be more consistent -Active now also defaults to false to be more consistent 2000-MAY-10 Hadi Hariri -Added new feature to Force Check of status 2000-Apr-23 Hadi Hariri -Converted to Indy 2000-Mar-01 Johannes Berg <johannes@sipsolutions.com> - new property HistoryFilename - new property MaxHistoryEntries - new property HistoryEnabled 2000-Jan-13 MTL -Moved to new Palette Scheme (Winshoes Misc) } unit IdIPWatch; { Simple component determines Online status, returns current IP address, and (optionally) keeps history on IP's issued. Original Author: Dave Nosker - AfterWave Technologies (allbyte@jetlink.net) } interface {$i IdCompilerDefines.inc} uses Classes, IdComponent, IdThread; const IP_WATCH_HIST_MAX = 25; IP_WATCH_HIST_FILENAME = 'iphist.dat'; {Do not Localize} IP_WATCH_INTERVAL = 1000; type TIdIPWatchThread = class(TIdThread) protected FInterval: Integer; FSender: TObject; FTimerEvent: TNotifyEvent; // procedure Run; override; procedure TimerEvent; end; TIdIPWatch = class(TIdComponent) protected FActive: Boolean; FCurrentIP: string; FHistoryEnabled: Boolean; FHistoryFilename: string; FIPHistoryList: TStringList; FIsOnline: Boolean; FLocalIPHuntBusy: Boolean; FMaxHistoryEntries: Integer; FOnLineCount: Integer; FOnStatusChanged: TNotifyEvent; FPreviousIP: string; FThread: TIdIPWatchThread; FWatchInterval: Cardinal; // procedure AddToIPHistoryList(Value: string); procedure CheckStatus(Sender: TObject); procedure SetActive(Value: Boolean); procedure SetMaxHistoryEntries(Value: Integer); procedure SetWatchInterval(Value: Cardinal); procedure InitComponent; override; public {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor Create(AOwner: TComponent); reintroduce; overload; {$ENDIF} destructor Destroy; override; function ForceCheck: Boolean; procedure LoadHistory; function LocalIP: string; procedure SaveHistory; // property CurrentIP: string read FCurrentIP; property IPHistoryList: TStringList read FIPHistoryList; property IsOnline: Boolean read FIsOnline; property PreviousIP: string read FPreviousIP; published property Active: Boolean read FActive write SetActive; property HistoryEnabled: Boolean read FHistoryEnabled write FHistoryEnabled default True; property HistoryFilename: string read FHistoryFilename write FHistoryFilename; property MaxHistoryEntries: Integer read FMaxHistoryEntries write SetMaxHistoryEntries default IP_WATCH_HIST_MAX; property OnStatusChanged: TNotifyEvent read FOnStatusChanged write FOnStatusChanged; property WatchInterval: Cardinal read FWatchInterval write SetWatchInterval default IP_WATCH_INTERVAL; end; implementation uses {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.Threading, System.IO, {$ENDIF} {$ENDIF} {$IFDEF USE_VCL_POSIX} Posix.SysSelect, Posix.SysTime, {$ENDIF} IdGlobal, IdStack, SysUtils; { TIdIPWatch } procedure TIdIPWatch.AddToIPHistoryList(Value: string); begin if (Value = '') or (Value = '127.0.0.1') then {Do not Localize} begin Exit; end; // Make sure the last entry does not allready contain the new one... if FIPHistoryList.Count > 0 then begin if FIPHistoryList[FIPHistoryList.Count-1] = Value then begin Exit; end; end; FIPHistoryList.Add(Value); if FIPHistoryList.Count > MaxHistoryEntries then begin FIPHistoryList.Delete(0); end; end; procedure TIdIPWatch.CheckStatus(Sender: TObject); var WasOnLine: Boolean; OldIP: string; begin try if FLocalIPHuntBusy then begin Exit; end; WasOnLine := FIsOnline; OldIP := FCurrentIP; FCurrentIP := LocalIP; FIsOnline := (FCurrentIP <> '127.0.0.1') and (FCurrentIP <> ''); {Do not Localize} if (WasOnline) and (not FIsOnline) then begin if (OldIP <> '127.0.0.1') and (OldIP <> '') then {Do not Localize} begin FPreviousIP := OldIP; end; AddToIPHistoryList(FPreviousIP); end; if (not WasOnline) and (FIsOnline) then begin if FOnlineCount = 0 then begin FOnlineCount := 1; end; if FOnlineCount = 1 then begin if FPreviousIP = FCurrentIP then begin // Del last history item... if FIPHistoryList.Count > 0 then begin FIPHistoryList.Delete(FIPHistoryList.Count-1); end; // Change the Previous IP# to the remaining last item on the list // OR to blank if none on list. if FIPHistoryList.Count > 0 then begin FPreviousIP := FIPHistoryList[FIPHistoryList.Count-1]; end else begin FPreviousIP := ''; {Do not Localize} end; end; end; FOnlineCount := 2; end; if ((WasOnline) and (not FIsOnline)) or ((not WasOnline) and (FIsOnline)) then begin if (not IsDesignTime) and Assigned(FOnStatusChanged) then begin FOnStatusChanged(Self); end; end; except end; end; {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor TIdIPWatch.Create(AOwner: TComponent); begin inherited Create(AOwner); end; {$ENDIF} procedure TIdIPWatch.InitComponent; begin inherited; FIPHistoryList := TStringList.Create; FIsOnLine := False; FOnLineCount := 0; FWatchInterval := IP_WATCH_INTERVAL; FActive := False; FPreviousIP := ''; {Do not Localize} FLocalIPHuntBusy := False; FHistoryEnabled:= True; FHistoryFilename:= IP_WATCH_HIST_FILENAME; FMaxHistoryEntries:= IP_WATCH_HIST_MAX; end; destructor TIdIPWatch.Destroy; begin if FIsOnLine then begin AddToIPHistoryList(FCurrentIP); end; Active := False; SaveHistory; FIPHistoryList.Free; inherited; end; function TIdIPWatch.ForceCheck: Boolean; begin // Forces a check and doesn't wait for the timer to fire. {Do not Localize} // It will return true if online. CheckStatus(nil); Result := FIsOnline; end; procedure TIdIPWatch.LoadHistory; begin if not IsDesignTime then begin FIPHistoryList.Clear; if FileExists(FHistoryFilename) and FHistoryEnabled then begin FIPHistoryList.LoadFromFile(FHistoryFileName); if FIPHistoryList.Count > 0 then begin FPreviousIP := FIPHistoryList[FIPHistoryList.Count-1]; end; end; end; end; function TIdIPWatch.LocalIP: string; begin FLocalIpHuntBusy := True; try Result := GStack.LocalAddress; finally FLocalIPHuntBusy := False; end; end; procedure TIdIPWatch.SaveHistory; begin if (not IsDesignTime) and FHistoryEnabled then begin FIPHistoryList.SaveToFile(FHistoryFilename); end; end; procedure TIdIPWatch.SetActive(Value: Boolean); begin if Value <> FActive then begin if not IsDesignTime then begin if Value then begin FThread := TIdIPWatchThread.Create(True); with FThread do begin FSender := Self; FTimerEvent := CheckStatus; FInterval := FWatchInterval; Start; end; end else begin if FThread <> nil then begin FThread.TerminateAndWaitFor; FreeAndNil(FThread); end; end; end; FActive := Value; end; end; procedure TIdIPWatch.SetMaxHistoryEntries(Value: Integer); begin FMaxHistoryEntries:= Value; while FIPHistoryList.Count > MaxHistoryEntries do // delete the oldest... FIPHistoryList.Delete(0); end; procedure TIdIPWatch.SetWatchInterval(Value: Cardinal); begin if Value <> FWatchInterval then begin FWatchInterval := Value; end; // might be necessary even if its the same, for example // when loading (not 100% sure though) if Assigned(FThread) then begin FThread.FInterval := FWatchInterval; end; end; { TIdIPWatchThread } procedure TIdIPWatchThread.Run; var LInterval: Integer; begin LInterval := FInterval; while LInterval > 0 do begin if LInterval > 500 then begin IndySleep(500); LInterval := LInterval - 500; end else begin IndySleep(LInterval); LInterval := 0; end; if Terminated then begin Exit; end; Synchronize(TimerEvent); end; end; procedure TIdIPWatchThread.TimerEvent; begin FTimerEvent(FSender); end; end.
unit GX_ClassHacks; interface // Return the class reference that is identified by the class name "ClassName" // and which is implemented in the binary PE module (e.g. DLL / package) // ImplementationModule. // // GetClassType may return nil if ClassName could not be found in ImplementationModule. function GetClassReference(const ClassName: string; const ImplementationModule: string): TClass; implementation uses Windows, SysUtils; function GetClassReference(const ClassName: string; const ImplementationModule: string): TClass; type PPointer = ^Pointer; TImageDosHeader = packed record e_magic: Word; e_cblp: Word; e_cp: Word; e_crlc: Word; e_cparhdr: Word; e_minalloc: Word; e_maxalloc: Word; e_ss: Word; e_sp: Word; e_csum: Word; e_ip: Word; e_cs: Word; e_lfarlc: Word; e_ovno: Word; e_res: array[0..3] of Word; e_oemid: Word; e_oeminfo: Word; e_res2: array[0..9] of Word; e_lfanew: Longint; end; PImageDosHeader = ^TImageDosHeader; var NtHeader: PImageNtHeaders; SectionHeader: PImageSectionHeader; function GetSectionHeader(const ASectionName: string): Boolean; var i: Integer; begin SectionHeader := PImageSectionHeader(NtHeader); Inc(PImageNtHeaders(SectionHeader)); Result := False; for i := 0 to NtHeader.FileHeader.NumberOfSections - 1 do //FI:W528 begin if StrLIComp(PChar(@SectionHeader^.Name), PChar(ASectionName), IMAGE_SIZEOF_SHORT_NAME) = 0 then begin Result := True; Break; end; Inc(SectionHeader); end; end; function InRangeOrNil(const APointer, PLowerBound, PUpperBound: Pointer): Boolean; begin Result := (APointer = nil) or ((Integer(PLowerBound) <= Integer(APointer)) and (Integer(APointer) <= Integer(PUpperBound))); end; var DosHeader: PImageDosHeader; PCodeBegin: PAnsiChar; PCodeEnd: PAnsiChar; PCodeScanner: PAnsiChar; P: PAnsiChar; FoundClassName: PShortString; ScannedModule: HMODULE; begin Result := nil; // The following scanner is based on code posted by Ludovic Dubois // // From: "Ludovic Dubois" <ldubois@prettyobjects.com> // Newsgroups: borland.public.delphi.opentoolsapi // Subject: [Hack] Classes Hack! // Date: Sat, 7 Nov 1998 15:40:48 -0500 // Message-ID: <722b75$mer7@forums.borland.com> // // Note: this code is **not** safe for general purpose use, since there // are MANY hidden assumptions which in this use-case incidentally // happen to be all valid. // // All changes with respect to the semantics of the posted // code are fully intentional. // ScannedModule := GetModuleHandle(PChar(ImplementationModule)); if ScannedModule = 0 then Exit; // Get PE DOS header DosHeader := PImageDosHeader(ScannedModule); if not DosHeader.e_magic = IMAGE_DOS_SIGNATURE then Exit; // Get NT header NtHeader := PImageNtHeaders(Longint(DosHeader) + DosHeader.e_lfanew); if IsBadReadPtr(NtHeader, SizeOf(IMAGE_NT_HEADERS)) or (NtHeader.Signature <> IMAGE_NT_SIGNATURE) or (NtHeader.FileHeader.SizeOfOptionalHeader <> SizeOf(NtHeader.OptionalHeader)) then begin Exit; end; // Find the code section if not GetSectionHeader('CODE') then Exit; // Compute beginning and end of the code section PCodeBegin := PAnsiChar(ScannedModule + SectionHeader.VirtualAddress); PCodeEnd := PCodeBegin + (SectionHeader.SizeOfRawData - 3); PCodeScanner := PCodeBegin; while PCodeScanner < PCodeEnd do begin P := PPointer(PCodeScanner)^; // Search for a(ny) class, employing some heuristics if (P = (PCodeScanner - vmtSelfPtr)) and InRangeOrNil(PPointer(P + vmtClassName)^, P, PCodeEnd) and InRangeOrNil(PPointer(P + vmtDynamicTable)^, P, PCodeEnd) and InRangeOrNil(PPointer(P + vmtMethodTable)^, P, PCodeEnd) and InRangeOrNil(PPointer(P + vmtFieldTable)^, P, PCodeEnd) and InRangeOrNil(PPointer(P + vmtInitTable)^, PCodeBegin, PCodeEnd) and InRangeOrNil(PPointer(P + vmtAutoTable)^, PCodeBegin, PCodeEnd) and InRangeOrNil(PPointer(P + vmtIntfTable)^, PCodeBegin, PCodeEnd) then begin FoundClassName := PShortString(PPointer(P + vmtClassName)^); if IsValidIdent(string(FoundClassName^)) and (string(FoundClassName^) = ClassName) then begin Result := TClass(P); Break; end; Inc(PCodeScanner, 4); end else Inc(PCodeScanner); end; end; end.
unit RESTRequest4D.Request.Headers; interface uses RESTRequest4D.Request.Headers.Intf, REST.Client, REST.Types, System.Classes; type TRequestHeaders = class(TInterfacedObject, IRequestHeaders) private FHeaders: TStrings; FRESTRequest: TRESTRequest; function Clear: IRequestHeaders; function Add(const AName, AValue: string; const AOptions: TRESTRequestParameterOptions = []): IRequestHeaders; public constructor Create(const ARESTRequest: TRESTRequest); destructor Destroy; override; end; implementation uses System.SysUtils; { TRequestHeaders } function TRequestHeaders.Add(const AName, AValue: string; const AOptions: TRESTRequestParameterOptions): IRequestHeaders; begin Result := Self; if (not AName.Trim.IsEmpty) and (not AValue.Trim.IsEmpty) then begin if (FHeaders.IndexOf(AName) < 0) then FHeaders.Add(AName); FRESTRequest.Params.AddHeader(AName, AValue); FRESTRequest.Params.ParameterByName(AName).Options := AOptions; end; end; function TRequestHeaders.Clear: IRequestHeaders; var I: Integer; begin Result := Self; for I := 0 to Pred(FHeaders.Count) do FRESTRequest.Params.Delete(FRESTRequest.Params.ParameterByName(FHeaders[I])); end; constructor TRequestHeaders.Create(const ARESTRequest: TRESTRequest); begin FHeaders := TStringList.Create; FRESTRequest := ARESTRequest; end; destructor TRequestHeaders.Destroy; begin FHeaders.Free; inherited; end; end.
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.MemoryCache Description : Cache objects with expiration control Author : Kike Pérez Version : 1.0 Created : 14/07/2019 Modified : 17/05/2021 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.MemoryCache; {$i QuickLib.inc} interface uses System.SysUtils, System.Generics.Collections, System.DateUtils, System.TypInfo, RTTI, Quick.Commons, Quick.Value, Quick.Threads, Quick.Cache.Intf, Quick.MemoryCache.Types, Quick.MemoryCache.Serializer.Json, Quick.MemoryCache.Compressor.GZip; type TCacheFlushedEvent = reference to procedure(aRemovedEntries : Integer); TBeginPurgerJobEvent = reference to procedure; TEndPurgerJobEvent = reference to procedure(aPurgedEntries : Integer); TPurgerJobErrorEvent = reference to procedure(const aErrorMsg : string); IMemoryCache<T> = interface ['{57927AD7-C993-4C3C-B552-43A39F99E73A}'] function GetCompression: Boolean; procedure SetCompression(const Value: Boolean); function GetCachedObjects: Integer; function GetCacheSize: Integer; procedure SetOnBeginPurgerJob(const Value: TBeginPurgerJobEvent); procedure SetOnCacheFlushed(const Value: TCacheFlushedEvent); procedure SetOnEndPurgerJob(const Value: TEndPurgerJobEvent); procedure SetOnPurgerJobError(const Value: TPurgerJobErrorEvent); property Compression : Boolean read GetCompression write SetCompression; property CachedObjects : Integer read GetCachedObjects; property CacheSize : Integer read GetCacheSize; property OnCacheFlushed : TCacheFlushedEvent write SetOnCacheFlushed; property OnBeginPurgerJob : TBeginPurgerJobEvent write SetOnBeginPurgerJob; property OnEndPurgerJob : TEndPurgerJobEvent write SetOnEndPurgerJob; property OnPurgeJobError : TPurgerJobErrorEvent write SetOnPurgerJobError; procedure SetValue(const aKey : string; aValue : T; aExpirationMillisecons : Integer = 0); overload; procedure SetValue(const aKey : string; aValue : T; aExpirationDate : TDateTime); overload; function GetValue(const aKey : string) : T; function TryGetValue(const aKey : string; out aValue : T) : Boolean; procedure RemoveValue(const aKey : string); procedure Refresh(const aKey: string; aExpirationMilliseconds : Integer); procedure Flush; end; IMemoryCache = interface(ICache) ['{F109AE78-43D7-4983-B8ED-52A41533EEED}'] function GetCompression: Boolean; procedure SetCompression(const Value: Boolean); function GetCachedObjects: Integer; function GetCacheSize: Integer; procedure SetOnBeginPurgerJob(const Value: TBeginPurgerJobEvent); procedure SetOnCacheFlushed(const Value: TCacheFlushedEvent); procedure SetOnEndPurgerJob(const Value: TEndPurgerJobEvent); procedure SetOnPurgerJobError(const Value: TPurgerJobErrorEvent); property Compression : Boolean read GetCompression write SetCompression; property CachedObjects : Integer read GetCachedObjects; property CacheSize : Integer read GetCacheSize; property OnCacheFlushed : TCacheFlushedEvent write SetOnCacheFlushed; property OnBeginPurgerJob : TBeginPurgerJobEvent write SetOnBeginPurgerJob; property OnEndPurgerJob : TEndPurgerJobEvent write SetOnEndPurgerJob; property OnPurgeJobError : TPurgerJobErrorEvent write SetOnPurgerJobError; 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 Refresh(const aKey: string; aExpirationMilliseconds : Integer); procedure Flush; end; TCacheEntry = class(TInterfacedObject,ICacheEntry) private fCreationDate : TDateTime; fExpiration : Cardinal; fExpirationDate : TDateTime; fCompression : Boolean; fCompressor : ICacheCompressor; fData : string; fIsCompressed : Boolean; function GetCreationDate: TDateTime; function GetData: string; function GetExpiration: Cardinal; procedure SetCreationDate(const Value: TDateTime); procedure SetData(const Value: string); procedure SetExpiration(aMilliseconds : Cardinal); function GetExpirationDate: TDateTime; procedure SetExpirationDate(const Value: TDateTime); public constructor Create(aCompression : Boolean; aCacheCompressor : ICacheCompressor); property CreationDate : TDateTime read GetCreationDate write SetCreationDate; property Expiration : Cardinal read GetExpiration write SetExpiration; property ExpirationDate : TDateTime read GetExpirationDate write SetExpirationDate; property Data : string read GetData write SetData; function Size : Integer; function IsExpired : Boolean; end; TMemoryCacheBase = class(TInterfacedObject) private fPurgerInterval : Integer; fMaxSize : Integer; fCachedObjects : Integer; fCacheSize : Integer; fCompression : Boolean; fLock : TMultiReadExclusiveWriteSynchronizer; fCacheJobs : TScheduledTasks; fOnCacheFlushed : TCacheFlushedEvent; fOnPurgerJobError : TPurgerJobErrorEvent; fOnBeginPurgerJob : TBeginPurgerJobEvent; fOnEndPurgerJob : TEndPurgerJobEvent; procedure CreatePurgerJobs; procedure RemoveExpiredCacheEntries; virtual; procedure SetPurgerInterval(const Value: Integer); protected fItems : TDictionary<string,ICacheEntry>; fSerializer : ICacheSerializer; fCompressor : ICacheCompressor; function GetCachedObjects: Integer; function GetCacheSize: Integer; procedure SetOnBeginPurgerJob(const Value: TBeginPurgerJobEvent); procedure SetOnCacheFlushed(const Value: TCacheFlushedEvent); procedure SetOnEndPurgerJob(const Value: TEndPurgerJobEvent); procedure SetOnPurgerJobError(const Value: TPurgerJobErrorEvent); function GetCompression: Boolean; procedure SetCompression(const Value: Boolean); public constructor Create(aPurgerInterval : Integer = 20; aCacheSerializer : ICacheSerializer = nil; aCacheCompressor : ICacheCompressor = nil); virtual; destructor Destroy; override; property MaxSize : Integer read fMaxSize write fMaxSize; property PurgerInterval : Integer read fPurgerInterval; property Compression : Boolean read GetCompression write SetCompression; property CachedObjects : Integer read GetCachedObjects; property CacheSize : Integer read GetCacheSize; property OnCacheFlushed : TCacheFlushedEvent read fOnCacheFlushed write SetOnCacheFlushed; property OnBeginPurgerJob : TBeginPurgerJobEvent read fOnBeginPurgerJob write SetOnBeginPurgerJob; property OnEndPurgerJob : TEndPurgerJobEvent read fOnEndPurgerJob write SetOnEndPurgerJob; property OnPurgeJobError : TPurgerJobErrorEvent read fOnPurgerJobError write SetOnPurgerJobError; procedure RemoveValue(const aKey : string); virtual; procedure Refresh(const aKey: string; aExpirationMilliseconds : Integer); procedure Flush; virtual; end; TMemoryCache<T> = class(TMemoryCacheBase,IMemoryCache<T>) private procedure SetValue(const aKey : string; aValue : T; aExpirationMilliseconds : Integer; aExpirationDate : TDateTime); overload; public constructor Create(aPurgerInterval : Integer = 20; aCacheSerializer : ICacheSerializer = nil; aCacheCompressor : ICacheCompressor = nil); override; procedure SetValue(const aKey : string; aValue : T; aExpirationMillisecons : Integer = 0); overload; procedure SetValue(const aKey : string; aValue : T; aExpirationDate : TDateTime); overload; function GetValue(const aKey : string) : T; function TryGetValue(const aKey : string; out oValue : T) : Boolean; procedure RemoveValue(const aKey : string); override; end; TMemoryCache = class(TMemoryCacheBase,IMemoryCache) private procedure SetValue(const aKey: string; aValue: TObject; aExpirationMilliseconds : Integer; aExpirationDate : TDateTime); overload; procedure SetValue(const aKey, aValue: string; aExpirationMilliseconds : Integer; aExpirationDate : TDateTime); overload; public 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 : TObject; aExpirationMilliseconds : Integer = 0); overload; procedure SetValue(const aKey : string; aValue : TObject; 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; out aValue : string) : Boolean; overload; function TryGetValue(const aKey : string; aValue : TObject) : Boolean; overload; function TryGetValue<T>(const aKey : string; out oValue : T) : Boolean; overload; function TryGetValue(const aKey : string; out aValue : TArray<string>) : Boolean; overload; function TryGetValue(const aKey : string; out aValue : TArray<TObject>) : Boolean; overload; end; EMemoryCacheConfigError = class(Exception); EMemoryCacheSetError = class(Exception); EMemoryCacheGetError = class(Exception); EMemoryCacheFlushError = class(Exception); implementation { TMemoryCacheBase } constructor TMemoryCacheBase.Create(aPurgerInterval : Integer = 20; aCacheSerializer : ICacheSerializer = nil; aCacheCompressor : ICacheCompressor = nil); begin fCompression := True; SetPurgerInterval(aPurgerInterval); fCachedObjects := 0; fCacheSize := 0; fLock := TMultiReadExclusiveWriteSynchronizer.Create; if aCacheSerializer <> nil then fSerializer := aCacheSerializer else fSerializer := TCacheJsonSerializer.Create; if aCacheCompressor <> nil then fCompressor := aCacheCompressor else fCompressor := TCacheCompressorGZip.Create; fItems := TDictionary<string,ICacheEntry>.Create; fCacheJobs := TScheduledTasks.Create; CreatePurgerJobs; fCacheJobs.Start; end; procedure TMemoryCacheBase.CreatePurgerJobs; begin fCacheJobs.AddTask('RemoveExpired',procedure (task : ITask) begin RemoveExpiredCacheEntries; end ).OnException(procedure(task : ITask; aException : Exception) begin if Assigned(fOnPurgerJobError) then fOnPurgerJobError(aException.Message); end ).StartInSeconds(fPurgerInterval).RepeatEvery(fPurgerInterval,TTimeMeasure.tmSeconds); end; destructor TMemoryCacheBase.Destroy; begin fItems.Free; fLock.Free; fCacheJobs.Stop; fCacheJobs.Free; inherited; end; procedure TMemoryCacheBase.Flush; begin fLock.BeginWrite; try fItems.Clear; if Assigned(fOnCacheFlushed) then fOnCacheFlushed(fCachedObjects); fCachedObjects := 0; fCacheSize := 0; finally fLock.EndWrite; end; end; procedure TMemoryCacheBase.Refresh(const aKey: string; aExpirationMilliseconds : Integer); var cacheitem : ICacheEntry; begin if fItems.TryGetValue(aKey,cacheitem) then begin cacheitem.CreationDate := Now; cacheitem.Expiration := aExpirationMilliseconds; end; end; procedure TMemoryCacheBase.RemoveExpiredCacheEntries; var pair : TPair<string,ICacheEntry>; removedentries : Integer; begin if Assigned(fOnBeginPurgerJob) then fOnBeginPurgerJob; removedentries := 0; fLock.BeginRead; try for pair in fItems do begin if pair.Value.IsExpired then begin fLock.BeginWrite; try //decrease cacheitem size to cachesize AtomicDecrement(fCacheSize,pair.Value.Size); //remove cacheitem from cache fItems.Remove(pair.Key); //decrease cachedobjects AtomicDecrement(fCachedObjects,1); Inc(removedentries); finally fLock.EndWrite; end; end; end; finally fLock.EndRead; if Assigned(fOnEndPurgerJob) then fOnEndPurgerJob(removedentries); end; end; procedure TMemoryCacheBase.RemoveValue(const aKey: string); var cacheitem : ICacheEntry; begin if fItems.TryGetValue(aKey,cacheitem) then begin //decrease cacheitem size to cachesize AtomicDecrement(fCacheSize,cacheitem.Size); //remove cacheitem from cache fItems.Remove(aKey); //decrease cachedobjects AtomicDecrement(fCachedObjects,1); end; end; function TMemoryCacheBase.GetCachedObjects: Integer; begin Result := fCachedObjects; end; function TMemoryCacheBase.GetCacheSize: Integer; begin Result := fCacheSize; end; function TMemoryCacheBase.GetCompression: Boolean; begin Result := fCompression; end; procedure TMemoryCacheBase.SetCompression(const Value: Boolean); begin fCompression := Value; end; procedure TMemoryCacheBase.SetOnBeginPurgerJob(const Value: TBeginPurgerJobEvent); begin fOnBeginPurgerJob := Value; end; procedure TMemoryCacheBase.SetOnCacheFlushed(const Value: TCacheFlushedEvent); begin fOnCacheFlushed := Value; end; procedure TMemoryCacheBase.SetOnEndPurgerJob(const Value: TEndPurgerJobEvent); begin fOnEndPurgerJob := Value; end; procedure TMemoryCacheBase.SetOnPurgerJobError(const Value: TPurgerJobErrorEvent); begin fOnPurgerJobError := Value; end; procedure TMemoryCacheBase.SetPurgerInterval(const Value: Integer); begin if Value > 5 then begin fPurgerInterval := Value; end else raise EMemoryCacheConfigError.Create('Purger Interval must be greater than 5 seconds'); end; { TCacheItem } constructor TCacheEntry.Create(aCompression : Boolean; aCacheCompressor : ICacheCompressor); begin fIsCompressed := False; fCompression := aCompression; fCompressor := aCacheCompressor; end; function TCacheEntry.GetCreationDate: TDateTime; begin Result := fCreationDate; end; function TCacheEntry.GetData: string; begin if fIsCompressed then Result := fCompressor.Decompress(fData) else Result := fData; end; function TCacheEntry.GetExpiration: Cardinal; begin Result := fExpiration; end; function TCacheEntry.GetExpirationDate: TDateTime; begin Result := fExpirationDate; end; procedure TCacheEntry.SetCreationDate(const Value: TDateTime); begin fCreationDate := Value; end; procedure TCacheEntry.SetExpiration(aMilliseconds: Cardinal); begin fExpiration := aMilliseconds; fExpirationDate := IncMilliSecond(fCreationDate,fExpiration); end; procedure TCacheEntry.SetExpirationDate(const Value: TDateTime); begin fExpiration := MilliSecondOf(Value); fExpirationDate := Value; end; function TCacheEntry.IsExpired: Boolean; begin if fExpiration = 0 then Result := False else Result := Now() > fExpirationDate; end; procedure TCacheEntry.SetData(const Value: string); begin fIsCompressed := False; //var a := value; //var b := value.Length; if fCompression then begin if ((Value.Length + 1) * 2) > 1024 then begin fData := fCompressor.Compress(Value); fIsCompressed := True; end else begin fData := Value; end; end else fData := Value; end; function TCacheEntry.Size: Integer; begin //Result := (fData.Length + 1) * SizeOf(Char); Result := (fData.Length + 1) * StringElementSize(fData); end; { TMemoryCache<T> } constructor TMemoryCache<T>.Create(aPurgerInterval: Integer; aCacheSerializer: ICacheSerializer; aCacheCompressor: ICacheCompressor); begin inherited Create(aPurgerInterval,aCacheSerializer,aCacheCompressor); end; function TMemoryCache<T>.GetValue(const aKey: string): T; begin TryGetValue(aKey,Result); end; procedure TMemoryCache<T>.RemoveValue(const aKey: string); begin inherited RemoveValue(aKey); end; procedure TMemoryCache<T>.SetValue(const aKey: string; aValue: T; aExpirationDate: TDateTime); begin SetValue(aKey,aValue,0,aExpirationDate); end; procedure TMemoryCache<T>.SetValue(const aKey: string; aValue: T; aExpirationMillisecons: Integer); begin SetValue(aKey,aValue,aExpirationMillisecons,0.0); end; procedure TMemoryCache<T>.SetValue(const aKey: string; aValue: T; aExpirationMilliseconds : Integer; aExpirationDate : TDateTime); var serialized : string; cacheitem : TCacheEntry; begin fLock.BeginWrite; try cacheitem := TCacheEntry.Create(fCompression,fCompressor); cacheitem.CreationDate := Now(); cacheitem.Expiration := aExpirationMilliseconds; if aExpirationDate > 0.0 then cacheitem.ExpirationDate := aExpirationDate; //add object to cache case PTypeInfo(TypeInfo(T))^.Kind of tkClass, tkPointer : begin //object type need to be serialized cacheitem.Data := fSerializer.Serialize(PObject(@aValue)^); end; tkString, tkWideString, tkUString, tkChar, tkWideChar : cacheitem.Data := string((@aValue)^); {$IFNDEF NEXTGEN} tkAnsiString : cacheitem.Data := string(AnsiString((@aValue)^)); {$ENDIF} else begin raise EMemoryCacheSetError.Create('Type not supported as cache'); end; end; RemoveValue(aKey); fItems.Add(aKey,cacheitem); //add cacheitem size to cachesize AtomicIncrement(fCacheSize,cacheitem.Size); //increment cacheobjects AtomicIncrement(fCachedObjects,1); finally fLock.EndWrite; end; end; function TMemoryCache<T>.TryGetValue(const aKey: string; out oValue: T): Boolean; var cacheitem : ICacheEntry; flexvalue : TFlexValue; obj : TObject; begin fLock.BeginRead; try Result := fItems.TryGetValue(aKey,cacheitem); //check if cacheitem already expired if Result and cacheitem.IsExpired then Exit(False); finally fLock.EndRead; end; if Result then begin flexvalue.AsString := cacheitem.Data; case PTypeInfo(TypeInfo(T))^.Kind of tkInteger : oValue := TValue.From(flexvalue.AsInteger).AsType<T>; tkInt64 : oValue := TValue.From(flexvalue.AsInt64).AsType<T>; tkFloat : begin if TypeInfo(T) = TypeInfo(TDateTime) then oValue := TValue.From(flexvalue.AsDateTime).AsType<T> else oValue := TValue.From(flexvalue.AsExtended).AsType<T>; end; tkString, tkUString : oValue := TValue.From(flexvalue.AsString).AsType<T>; {$IFDEF MSWINDOWS} tkAnsiString : oValue := TValue.From(flexvalue.AsAnsiString).AsType<T>; tkWideString : oValue := TValue.From(flexvalue.AsWideString).AsType<T>; {$ENDIF} tkEnumeration : begin if TypeInfo(T) = TypeInfo(Boolean) then oValue := TValue.From(flexvalue.AsBoolean).AsType<T> else oValue := TValue.From(flexvalue.AsInteger).AsType<T>; end; tkClass, tkPointer : begin obj := PTypeInfo(TypeInfo(T))^.TypeData.ClassType.Create; fSerializer.Deserialize(cacheitem.Data,obj); oValue := TValue.From(obj).AsType<T>; //oValue := T((@obj)^); end else raise EMemoryCacheGetError.Create('Error casting value from cache'); end; end; end; { TMemoryCache } function TMemoryCache.GetValue(const aKey: string): string; begin TryGetValue(aKey,Result); end; procedure TMemoryCache.SetValue(const aKey, aValue: string; aExpirationMilliseconds: Integer); begin SetValue(aKey,aValue,aExpirationMilliseconds,0.0); end; procedure TMemoryCache.SetValue(const aKey, aValue: string; aExpirationDate: TDateTime); begin SetValue(aKey,aValue,0,aExpirationDate); end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TObject; aExpirationMilliseconds: Integer); begin SetValue(aKey,aValue,aExpirationMilliseconds,0.0); end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TObject; aExpirationDate: TDateTime); begin SetValue(aKey,aValue,0,aExpirationDate); end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TObject; aExpirationMilliseconds : Integer; aExpirationDate : TDateTime); begin SetValue(aKey,fSerializer.Serialize(aValue),aExpirationMilliseconds,aExpirationDate); end; procedure TMemoryCache.SetValue(const aKey, aValue: string; aExpirationMilliseconds : Integer; aExpirationDate : TDateTime); var cacheitem : TCacheEntry; begin fLock.BeginWrite; try cacheitem := TCacheEntry.Create(fCompression,fCompressor); cacheitem.CreationDate := Now(); cacheitem.Expiration := aExpirationMilliseconds; if aExpirationDate > 0.0 then cacheitem.ExpirationDate := aExpirationDate; //add object to cache cacheitem.Data := aValue; RemoveValue(aKey); fItems.Add(aKey,cacheitem); //add cacheitem size to cachesize AtomicIncrement(fCacheSize,cacheitem.Size); //increment cacheobjects AtomicIncrement(fCachedObjects,1); finally fLock.EndWrite; end; end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TArray<string>; aExpirationDate: TDateTime); begin SetValue(aKey,fSerializer.Serialize(aValue),0,aExpirationDate); end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TArray<string>; aExpirationMilliseconds: Integer); begin SetValue(aKey,fSerializer.Serialize(aValue),aExpirationMilliseconds,0.0); end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TArray<TObject>; aExpirationDate: TDateTime); begin SetValue(aKey,fSerializer.Serialize(aValue),0,aExpirationDate); end; procedure TMemoryCache.SetValue(const aKey: string; aValue: TArray<TObject>; aExpirationMilliseconds: Integer); begin SetValue(aKey,fSerializer.Serialize(aValue),aExpirationMilliseconds,0.0); end; function TMemoryCache.TryGetValue(const aKey: string; aValue : TObject): Boolean; var cacheitem : ICacheEntry; begin fLock.BeginRead; try if aValue = nil then raise EMemoryCacheGetError.Create('Cannot passed a nil object as param'); Result := fItems.TryGetValue(aKey,cacheitem); //check if cacheitem already expired if (not Result) or (cacheitem.IsExpired) then Exit(False); finally fLock.EndRead; end; fSerializer.Deserialize(cacheitem.Data,aValue); end; function TMemoryCache.TryGetValue(const aKey: string; out aValue: string): Boolean; begin Result := TryGetValue<string>(aKey,aValue); end; function TMemoryCache.TryGetValue<T>(const aKey: string; out oValue: T): Boolean; var cacheitem : ICacheEntry; flexvalue : TFlexValue; obj : TObject; begin fLock.BeginRead; try Result := fItems.TryGetValue(aKey,cacheitem); //check if cacheitem already expired if Result and cacheitem.IsExpired then Exit(False); finally fLock.EndRead; end; if Result then begin flexvalue.AsString := cacheitem.Data; case PTypeInfo(TypeInfo(T))^.Kind of tkInteger : oValue := TValue.From(flexvalue.AsInteger).AsType<T>; tkInt64 : oValue := TValue.From(flexvalue.AsInt64).AsType<T>; tkFloat : begin if TypeInfo(T) = TypeInfo(TDateTime) then oValue := TValue.From(flexvalue.AsDateTime).AsType<T> else oValue := TValue.From(flexvalue.AsExtended).AsType<T>; end; tkString, tkUString : oValue := TValue.From(flexvalue.AsString).AsType<T>; {$IFDEF MSWINDOWS} tkAnsiString : oValue := TValue.From(flexvalue.AsAnsiString).AsType<T>; tkWideString : oValue := TValue.From(flexvalue.AsWideString).AsType<T>; {$ENDIF} tkEnumeration : begin if TypeInfo(T) = TypeInfo(Boolean) then oValue := TValue.From(flexvalue.AsBoolean).AsType<T> else oValue := TValue.From(flexvalue.AsInteger).AsType<T>; end; tkClass, tkPointer : begin obj := PTypeInfo(TypeInfo(T))^.TypeData.ClassType.Create; fSerializer.Deserialize(flexvalue.AsString,obj); oValue := TValue.From(obj).AsType<T>; end; else raise EMemoryCacheGetError.Create('Error casting value from cache'); end; end; end; function TMemoryCache.TryGetValue(const aKey: string; out aValue: TArray<string>): Boolean; var cacheitem : ICacheEntry; begin fLock.BeginRead; try Result := fItems.TryGetValue(aKey,cacheitem); //check if cacheitem already expired if Result and cacheitem.IsExpired then Exit(False); finally fLock.EndRead; end; if Result then fSerializer.Deserialize(cacheitem.Data,aValue); end; function TMemoryCache.TryGetValue(const aKey: string; out aValue: TArray<TObject>): Boolean; var cacheitem : ICacheEntry; begin fLock.BeginRead; try Result := fItems.TryGetValue(aKey,cacheitem); //check if cacheitem already expired if Result and cacheitem.IsExpired then Exit(False); finally fLock.EndRead; end; if Result then fSerializer.Deserialize(cacheitem.Data,aValue); end; end.
(* NewAnsi ANSI Emulation Units (C)opyright 2000, Mike Hodgson This source code can be freely used. Tested Environments: Borland Pascal 7.01 Virtual Pascal 2.10 Revisions: 1.02: Fixed CRLF sequence. *) unit ansi; interface Procedure FlushAnsi; Procedure AWrite (S : String); Procedure AWriteLn (S : String); var Ans_Fore : Byte; { saved ansi foreground colour } Ans_Back : Byte; { saved ansi background colour } Ans_SX : Byte; { saved X position } Ans_SY : Byte; { saved Y position } Ans_High : Boolean; { are colours high intensity? } Ans_Blink : Boolean; { are colours blinking? } FoundEscape : Boolean; { have we found #27 yet? } FoundBracket : Boolean; { have we found [ yet? } AnsiBuffer : ShortString; { buffer to store escape sequence } BufPos : LongInt; { where's the end of the buffer?? } Temp_X : Byte; { temporary X position storage } Temp_Y : Byte; { temporary Y position storage } implementation uses {$IFDEF VirtualPascal} Use32,SysUtils,{$ENDIF} crt; const { array of ansi colours } clIndex : Array[1..16] of byte = ($00,$04,$02,$06,$01,$05,$03,$07,$00,$04,$02,$06,$01,$05,$03,$07); {$IFNDEF VirtualPascal} Function StrToInt (S : String) : LongInt; Var Code : Integer; TempInt : LongInt; Begin Val(S,TempInt,Code); StrToInt := TempInt; End; {$ENDIF} Procedure FlushAnsi; Begin SetLength(AnsiBuffer, 0); Ans_Fore := 7; Ans_Back := 0; Ans_SX := 1; Ans_SY := 1; Ans_High := False; Ans_Blink := False; FoundEscape := False; FoundBracket := False; BufPos := 0; Temp_X := 0; Temp_Y := 0; End; Procedure ParseAnsi; { this does the actual parsing of a valid escape sequence #27 and [ are already stripped here. } var TempInt : LongInt; TempStr : String; Done : Boolean; begin SetLength(AnsiBuffer, BufPos); done := false; Case AnsiBuffer[BufPos] of 'J' : ClrScr; 'K' : ClrEol; 'm' : begin delete(ANSIBuffer,BufPos,1); Repeat if (pos(';',ANSIBuffer) <> 0) then begin TempStr := copy (ANSIBuffer,1,pos(';',ANSIBuffer)-1); delete (ANSIBuffer, 1, pos(';',ANSIBuffer)); end else begin TempStr := ANSIBuffer; done := true; end; Case StrToInt(TempStr) of 0 : begin Ans_High := False; Ans_Fore := 7; Ans_Back := 0; end; 1 : Ans_High := True; 2 : Ans_High := False; 5 : Ans_Blink := True; 30..47 : begin if ((StrToInt(TempStr) >29) and (StrToInt(TempStr) <38)) then Ans_Fore := clIndex[StrToInt(TempStr)-29] else if ((StrToInt(TempStr) >39) and (StrToInt(TempStr) <48)) then Ans_Back := clIndex[StrToInt(TempStr)-31]; end; end; if (Ans_High) then TextColor(Ans_Fore+8) else TextColor(Ans_Fore); TextBackground(Ans_Back); if (Ans_Blink) then TextAttr := TextAttr or 128; Until (Done = true) end; 'A' : if (Length(ANSIBuffer) = 1) then GotoXY(WhereX,WhereY+1) else begin delete(ANSIBuffer,BufPos,1); GotoXY(WhereX,WhereY - StrToInt(ANSIBuffer)); end; 'B' : if (Length(ANSIBuffer) = 1) then GotoXY(WhereX,WhereY-1) else begin delete(ANSIBuffer,BufPos,1); GotoXY(WhereX,WhereY + StrToInt(ANSIBuffer)); end; 'C' : if (Length(ANSIBuffer) = 1) then GotoXY(WhereX + 1,WhereY) else begin delete(ANSIBuffer,BufPos,1); GotoXY(WhereX + StrToInt(ANSIBuffer),WhereY); end; 'D' : if (Length(ANSIBuffer) = 1) then GotoXY(WhereX - 1,WhereY) else begin delete(ANSIBuffer,BufPos,1); GotoXY(WhereX - StrToInt(ANSIBuffer),WhereY); end; 's' : begin Ans_SX := WhereX; Ans_SY := WhereY; end; 'u' : GotoXY(Ans_SX,Ans_SY); 'H','F','f' : { not sure wether F or f is the correct code, different references show one or the other. It shouldn't hurt to support both. } begin {rp} if (Length(ANSIBuffer) = 1) then GotoXY(1,1) else {rp} begin {rp} delete(ANSIBuffer,BufPos,1); {rp} Temp_X := 255; {rp} Temp_Y := 255; {rp} TempStr := Copy(ANSIBuffer, 1, Pos(';', ANSIBuffer) - 1); {rp} if (TempStr <> '') then {rp} Temp_Y := StrToInt(TempStr); {rp} Delete(ANSIBuffer,1,pos(';', ANSIBuffer)); {rp} if (ANSIBuffer <> '') then {rp} Temp_X := StrToInt(ANSIBuffer); {rp} if (Temp_X <> 255) and (Temp_Y <> 255) then {rp} GotoXY(Temp_X, Temp_Y); {rp} end; {rp} end; {rp} end; {rp} end; {rp} Procedure FindAnsi (S : Char); { This pieces together a valid sequence and sends it to the parser! } var TempInt : LongInt; begin if (s = #27) then FoundEscape := True; if ((s = '[') and FoundEscape) then FoundBracket := True; if ((s <> '[') and (FoundBracket = True)) then begin BufPos := BufPos + 1; AnsiBuffer[BufPos] := s; if (pos(AnsiBuffer[BufPos],'HfFABCDnsuJKmh') <> 0) then begin ParseAnsi; { part of escape sequence, save it! } FoundEscape := False; FoundBracket := False; BufPos := 0; AnsiBuffer := ''; end; end else if ((s = '[') and (FoundEscape = False)) or ((s <>'[') and (s<>#27)) then Write (S); end; Procedure AWrite(s : string); var TempInt : LongInt; begin For TempInt := 1 to Length(s) do FindAnsi (s[TempInt]); end; Procedure AWriteLn (s : string); begin AWrite(s + #13+#10); end; begin FoundEscape := False; FoundBracket := False; BufPos := 0; end.
{$MODE OBJFPC} program ProblemSolver; const InputFile = 'VCPAIRS.INP'; OutputFile = 'VCPAIRS.OUT'; maxN = Round(1E5); type PNode = ^TNode; TNode = packed record value: Integer; freq: Integer; P, L, R: PNode; end; var fi, fo: TextFile; lab, color: array[1..maxN] of Integer; n, m: Integer; sentinel, pattern: TNode; nilT: PNode; ColorSet: array[1..maxN] of PNode; procedure Enter; var i: Integer; u, v, w: Integer; begin ReadLn(fi, n, m); for i := 1 to n do Read(fi, color[i]); ReadLn(fi); end; procedure Init; begin nilT := @sentinel; with pattern do begin P := nilT; L := nilT; R := nilT; end; sentinel := pattern; end; procedure SetL(x, y: PNode); inline; begin y^.P := x; x^.L := y; end; procedure SetR(x, y: PNode); inline; begin y^.P := x; x^.R := y; end; procedure SetC(x, y: PNode; InRight: Boolean); inline; begin if InRight then SetR(x, y) else SetL(x, y); end; procedure UpTree(x: PNode); var y, z: PNode; begin y := x^.P; z := y^.P; if x = y^.L then begin SetC(y, x^.R, False); SetC(x, y, True); end else begin SetC(y, x^.L, True); SetC(x, y, False); end; SetC(z, x, z^.R = y); end; procedure Splay(x: PNode); var y, z: PNode; begin repeat y := x^.P; if y = nilT then Break; z := y^.P; if z <> nilT then if (x = y^.L) = (y = z^.L) then UpTree(y) else UpTree(x); UpTree(x); until False; end; function Insert(var T: PNode; key, f: Integer): Int64; var x, last: PNode; begin repeat last := T; if T^.value = key then Break; if key < T^.value then T := T^.L else T := T^.R; until T = nilT; if T = nilT then begin Result := 0; New(x); x^ := pattern; x^.value := key; x^.freq := f; if key < last^.value then SetC(last, x, False) else SetC(last, x, True); Splay(x); T := x; end else begin Result := Int64(T^.freq) * f; Inc(T^.freq, f); Splay(T); end; end; function UnionSet(var r, s: PNode): Int64; procedure Visit(x: PNode); begin if x = nilT then Exit; Inc(Result, Insert(r, x^.value, x^.freq)); Visit(x^.L); Visit(x^.R); Dispose(x); end; begin Result := 0; Visit(s); s := nilT; end; function MakeSet(u: Integer): PNode; begin lab[u] := -1; New(Result); Result^ := pattern; with Result^ do begin value := color[u]; freq := 1; end; end; function FindSet(u: integer): Integer; begin if lab[u] < 0 then Exit(u); Result := FindSet(lab[u]); lab[u] := Result; end; function Union(r, s: Integer): Integer; var x: Integer; begin x := lab[r] + lab[s]; if lab[r] < lab[s] then begin lab[s] := r; lab[r] := x; Result := r; end else begin lab[r] := s; lab[s] := x; Result := s; end; end; procedure Solve; var i: Integer; r, s, x, u, v: Integer; ans: Int64; begin for i := 1 to n do ColorSet[i] := MakeSet(i); ans := 0; for i := 1 to m do begin ReadLn(fi, u, v); r := FindSet(u); s := FindSet(v); if r <> s then begin x := Union(r, s); if x = r then Inc(ans, UnionSet(ColorSet[r], ColorSet[s])) else Inc(ans, UnionSet(ColorSet[s], ColorSet[r])); end; WriteLn(fo, ans); end; end; procedure FreeSets; var i: Integer; procedure Visit(x: PNode); begin if x = nilT then Exit; Visit(x^.L); Visit(x^.R); Dispose(x); end; begin for i := 1 to n do if ColorSet[i] <> nilT then Visit(ColorSet[i]); end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, Outputfile); Rewrite(fo); try Enter; Init; Solve; FreeSets; finally CloseFile(fi); CloseFile(fo); end; end.
unit InfoESOATable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoESOARecord = record PEntId: String[8]; PTranDate: String[8]; PTranType: String[3]; PTranId: String[5]; PModCount: SmallInt; PAmt: Currency; PBalance: Currency; PComment: String[20]; PYrMo: String[6]; PUserId: String[10]; PTimeStamp: String[20]; End; TInfoESOAClass2 = class public PEntId: String[8]; PTranDate: String[8]; PTranType: String[3]; PTranId: String[5]; PModCount: SmallInt; PAmt: Currency; PBalance: Currency; PComment: String[20]; PYrMo: String[6]; PUserId: String[10]; PTimeStamp: String[20]; End; // function CtoRInfoESOA(AClass:TInfoESOAClass):TInfoESOARecord; // procedure RtoCInfoESOA(ARecord:TInfoESOARecord;AClass:TInfoESOAClass); TInfoESOABuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoESOARecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoESOA = (InfoESOAPrimaryKey); TInfoESOATable = class( TDBISAMTableAU ) private FDFEntId: TStringField; FDFTranDate: TStringField; FDFTranType: TStringField; FDFTranId: TStringField; FDFModCount: TSmallIntField; FDFAmt: TCurrencyField; FDFBalance: TCurrencyField; FDFComment: TStringField; FDFYrMo: TStringField; FDFUserId: TStringField; FDFTimeStamp: TStringField; procedure SetPEntId(const Value: String); function GetPEntId:String; procedure SetPTranDate(const Value: String); function GetPTranDate:String; procedure SetPTranType(const Value: String); function GetPTranType:String; procedure SetPTranId(const Value: String); function GetPTranId:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPAmt(const Value: Currency); function GetPAmt:Currency; procedure SetPBalance(const Value: Currency); function GetPBalance:Currency; procedure SetPComment(const Value: String); function GetPComment:String; procedure SetPYrMo(const Value: String); function GetPYrMo:String; procedure SetPUserId(const Value: String); function GetPUserId:String; procedure SetPTimeStamp(const Value: String); function GetPTimeStamp:String; procedure SetEnumIndex(Value: TEIInfoESOA); function GetEnumIndex: TEIInfoESOA; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoESOARecord; procedure StoreDataBuffer(ABuffer:TInfoESOARecord); property DFEntId: TStringField read FDFEntId; property DFTranDate: TStringField read FDFTranDate; property DFTranType: TStringField read FDFTranType; property DFTranId: TStringField read FDFTranId; property DFModCount: TSmallIntField read FDFModCount; property DFAmt: TCurrencyField read FDFAmt; property DFBalance: TCurrencyField read FDFBalance; property DFComment: TStringField read FDFComment; property DFYrMo: TStringField read FDFYrMo; property DFUserId: TStringField read FDFUserId; property DFTimeStamp: TStringField read FDFTimeStamp; property PEntId: String read GetPEntId write SetPEntId; property PTranDate: String read GetPTranDate write SetPTranDate; property PTranType: String read GetPTranType write SetPTranType; property PTranId: String read GetPTranId write SetPTranId; property PModCount: SmallInt read GetPModCount write SetPModCount; property PAmt: Currency read GetPAmt write SetPAmt; property PBalance: Currency read GetPBalance write SetPBalance; property PComment: String read GetPComment write SetPComment; property PYrMo: String read GetPYrMo write SetPYrMo; property PUserId: String read GetPUserId write SetPUserId; property PTimeStamp: String read GetPTimeStamp write SetPTimeStamp; published property Active write SetActive; property EnumIndex: TEIInfoESOA read GetEnumIndex write SetEnumIndex; end; { TInfoESOATable } TInfoESOAQuery = class( TDBISAMQueryAU ) private FDFEntId: TStringField; FDFTranDate: TStringField; FDFTranType: TStringField; FDFTranId: TStringField; FDFModCount: TSmallIntField; FDFAmt: TCurrencyField; FDFBalance: TCurrencyField; FDFComment: TStringField; FDFYrMo: TStringField; FDFUserId: TStringField; FDFTimeStamp: TStringField; procedure SetPEntId(const Value: String); function GetPEntId:String; procedure SetPTranDate(const Value: String); function GetPTranDate:String; procedure SetPTranType(const Value: String); function GetPTranType:String; procedure SetPTranId(const Value: String); function GetPTranId:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPAmt(const Value: Currency); function GetPAmt:Currency; procedure SetPBalance(const Value: Currency); function GetPBalance:Currency; procedure SetPComment(const Value: String); function GetPComment:String; procedure SetPYrMo(const Value: String); function GetPYrMo:String; procedure SetPUserId(const Value: String); function GetPUserId:String; procedure SetPTimeStamp(const Value: String); function GetPTimeStamp:String; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoESOARecord; procedure StoreDataBuffer(ABuffer:TInfoESOARecord); property DFEntId: TStringField read FDFEntId; property DFTranDate: TStringField read FDFTranDate; property DFTranType: TStringField read FDFTranType; property DFTranId: TStringField read FDFTranId; property DFModCount: TSmallIntField read FDFModCount; property DFAmt: TCurrencyField read FDFAmt; property DFBalance: TCurrencyField read FDFBalance; property DFComment: TStringField read FDFComment; property DFYrMo: TStringField read FDFYrMo; property DFUserId: TStringField read FDFUserId; property DFTimeStamp: TStringField read FDFTimeStamp; property PEntId: String read GetPEntId write SetPEntId; property PTranDate: String read GetPTranDate write SetPTranDate; property PTranType: String read GetPTranType write SetPTranType; property PTranId: String read GetPTranId write SetPTranId; property PModCount: SmallInt read GetPModCount write SetPModCount; property PAmt: Currency read GetPAmt write SetPAmt; property PBalance: Currency read GetPBalance write SetPBalance; property PComment: String read GetPComment write SetPComment; property PYrMo: String read GetPYrMo write SetPYrMo; property PUserId: String read GetPUserId write SetPUserId; property PTimeStamp: String read GetPTimeStamp write SetPTimeStamp; published property Active write SetActive; end; { TInfoESOATable } procedure Register; implementation procedure TInfoESOATable.CreateFields; begin FDFEntId := CreateField( 'EntId' ) as TStringField; FDFTranDate := CreateField( 'TranDate' ) as TStringField; FDFTranType := CreateField( 'TranType' ) as TStringField; FDFTranId := CreateField( 'TranId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFAmt := CreateField( 'Amt' ) as TCurrencyField; FDFBalance := CreateField( 'Balance' ) as TCurrencyField; FDFComment := CreateField( 'Comment' ) as TStringField; FDFYrMo := CreateField( 'YrMo' ) as TStringField; FDFUserId := CreateField( 'UserId' ) as TStringField; FDFTimeStamp := CreateField( 'TimeStamp' ) as TStringField; end; { TInfoESOATable.CreateFields } procedure TInfoESOATable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoESOATable.SetActive } procedure TInfoESOATable.SetPEntId(const Value: String); begin DFEntId.Value := Value; end; function TInfoESOATable.GetPEntId:String; begin result := DFEntId.Value; end; procedure TInfoESOATable.SetPTranDate(const Value: String); begin DFTranDate.Value := Value; end; function TInfoESOATable.GetPTranDate:String; begin result := DFTranDate.Value; end; procedure TInfoESOATable.SetPTranType(const Value: String); begin DFTranType.Value := Value; end; function TInfoESOATable.GetPTranType:String; begin result := DFTranType.Value; end; procedure TInfoESOATable.SetPTranId(const Value: String); begin DFTranId.Value := Value; end; function TInfoESOATable.GetPTranId:String; begin result := DFTranId.Value; end; procedure TInfoESOATable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoESOATable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoESOATable.SetPAmt(const Value: Currency); begin DFAmt.Value := Value; end; function TInfoESOATable.GetPAmt:Currency; begin result := DFAmt.Value; end; procedure TInfoESOATable.SetPBalance(const Value: Currency); begin DFBalance.Value := Value; end; function TInfoESOATable.GetPBalance:Currency; begin result := DFBalance.Value; end; procedure TInfoESOATable.SetPComment(const Value: String); begin DFComment.Value := Value; end; function TInfoESOATable.GetPComment:String; begin result := DFComment.Value; end; procedure TInfoESOATable.SetPYrMo(const Value: String); begin DFYrMo.Value := Value; end; function TInfoESOATable.GetPYrMo:String; begin result := DFYrMo.Value; end; procedure TInfoESOATable.SetPUserId(const Value: String); begin DFUserId.Value := Value; end; function TInfoESOATable.GetPUserId:String; begin result := DFUserId.Value; end; procedure TInfoESOATable.SetPTimeStamp(const Value: String); begin DFTimeStamp.Value := Value; end; function TInfoESOATable.GetPTimeStamp:String; begin result := DFTimeStamp.Value; end; procedure TInfoESOATable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('EntId, String, 8, N'); Add('TranDate, String, 8, N'); Add('TranType, String, 3, N'); Add('TranId, String, 5, N'); Add('ModCount, SmallInt, 0, N'); Add('Amt, Currency, 0, N'); Add('Balance, Currency, 0, N'); Add('Comment, String, 20, N'); Add('YrMo, String, 6, N'); Add('UserId, String, 10, N'); Add('TimeStamp, String, 20, N'); end; end; procedure TInfoESOATable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, EntId;TranDate;TranType;TranId, Y, Y, N, N'); end; end; procedure TInfoESOATable.SetEnumIndex(Value: TEIInfoESOA); begin case Value of InfoESOAPrimaryKey : IndexName := ''; end; end; function TInfoESOATable.GetDataBuffer:TInfoESOARecord; var buf: TInfoESOARecord; begin fillchar(buf, sizeof(buf), 0); buf.PEntId := DFEntId.Value; buf.PTranDate := DFTranDate.Value; buf.PTranType := DFTranType.Value; buf.PTranId := DFTranId.Value; buf.PModCount := DFModCount.Value; buf.PAmt := DFAmt.Value; buf.PBalance := DFBalance.Value; buf.PComment := DFComment.Value; buf.PYrMo := DFYrMo.Value; buf.PUserId := DFUserId.Value; buf.PTimeStamp := DFTimeStamp.Value; result := buf; end; procedure TInfoESOATable.StoreDataBuffer(ABuffer:TInfoESOARecord); begin DFEntId.Value := ABuffer.PEntId; DFTranDate.Value := ABuffer.PTranDate; DFTranType.Value := ABuffer.PTranType; DFTranId.Value := ABuffer.PTranId; DFModCount.Value := ABuffer.PModCount; DFAmt.Value := ABuffer.PAmt; DFBalance.Value := ABuffer.PBalance; DFComment.Value := ABuffer.PComment; DFYrMo.Value := ABuffer.PYrMo; DFUserId.Value := ABuffer.PUserId; DFTimeStamp.Value := ABuffer.PTimeStamp; end; function TInfoESOATable.GetEnumIndex: TEIInfoESOA; var iname : string; begin result := InfoESOAPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoESOAPrimaryKey; end; procedure TInfoESOAQuery.CreateFields; begin FDFEntId := CreateField( 'EntId' ) as TStringField; FDFTranDate := CreateField( 'TranDate' ) as TStringField; FDFTranType := CreateField( 'TranType' ) as TStringField; FDFTranId := CreateField( 'TranId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFAmt := CreateField( 'Amt' ) as TCurrencyField; FDFBalance := CreateField( 'Balance' ) as TCurrencyField; FDFComment := CreateField( 'Comment' ) as TStringField; FDFYrMo := CreateField( 'YrMo' ) as TStringField; FDFUserId := CreateField( 'UserId' ) as TStringField; FDFTimeStamp := CreateField( 'TimeStamp' ) as TStringField; end; { TInfoESOAQuery.CreateFields } procedure TInfoESOAQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoESOAQuery.SetActive } procedure TInfoESOAQuery.SetPEntId(const Value: String); begin DFEntId.Value := Value; end; function TInfoESOAQuery.GetPEntId:String; begin result := DFEntId.Value; end; procedure TInfoESOAQuery.SetPTranDate(const Value: String); begin DFTranDate.Value := Value; end; function TInfoESOAQuery.GetPTranDate:String; begin result := DFTranDate.Value; end; procedure TInfoESOAQuery.SetPTranType(const Value: String); begin DFTranType.Value := Value; end; function TInfoESOAQuery.GetPTranType:String; begin result := DFTranType.Value; end; procedure TInfoESOAQuery.SetPTranId(const Value: String); begin DFTranId.Value := Value; end; function TInfoESOAQuery.GetPTranId:String; begin result := DFTranId.Value; end; procedure TInfoESOAQuery.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoESOAQuery.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoESOAQuery.SetPAmt(const Value: Currency); begin DFAmt.Value := Value; end; function TInfoESOAQuery.GetPAmt:Currency; begin result := DFAmt.Value; end; procedure TInfoESOAQuery.SetPBalance(const Value: Currency); begin DFBalance.Value := Value; end; function TInfoESOAQuery.GetPBalance:Currency; begin result := DFBalance.Value; end; procedure TInfoESOAQuery.SetPComment(const Value: String); begin DFComment.Value := Value; end; function TInfoESOAQuery.GetPComment:String; begin result := DFComment.Value; end; procedure TInfoESOAQuery.SetPYrMo(const Value: String); begin DFYrMo.Value := Value; end; function TInfoESOAQuery.GetPYrMo:String; begin result := DFYrMo.Value; end; procedure TInfoESOAQuery.SetPUserId(const Value: String); begin DFUserId.Value := Value; end; function TInfoESOAQuery.GetPUserId:String; begin result := DFUserId.Value; end; procedure TInfoESOAQuery.SetPTimeStamp(const Value: String); begin DFTimeStamp.Value := Value; end; function TInfoESOAQuery.GetPTimeStamp:String; begin result := DFTimeStamp.Value; end; function TInfoESOAQuery.GetDataBuffer:TInfoESOARecord; var buf: TInfoESOARecord; begin fillchar(buf, sizeof(buf), 0); buf.PEntId := DFEntId.Value; buf.PTranDate := DFTranDate.Value; buf.PTranType := DFTranType.Value; buf.PTranId := DFTranId.Value; buf.PModCount := DFModCount.Value; buf.PAmt := DFAmt.Value; buf.PBalance := DFBalance.Value; buf.PComment := DFComment.Value; buf.PYrMo := DFYrMo.Value; buf.PUserId := DFUserId.Value; buf.PTimeStamp := DFTimeStamp.Value; result := buf; end; procedure TInfoESOAQuery.StoreDataBuffer(ABuffer:TInfoESOARecord); begin DFEntId.Value := ABuffer.PEntId; DFTranDate.Value := ABuffer.PTranDate; DFTranType.Value := ABuffer.PTranType; DFTranId.Value := ABuffer.PTranId; DFModCount.Value := ABuffer.PModCount; DFAmt.Value := ABuffer.PAmt; DFBalance.Value := ABuffer.PBalance; DFComment.Value := ABuffer.PComment; DFYrMo.Value := ABuffer.PYrMo; DFUserId.Value := ABuffer.PUserId; DFTimeStamp.Value := ABuffer.PTimeStamp; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoESOATable, TInfoESOAQuery, TInfoESOABuffer ] ); end; { Register } function TInfoESOABuffer.FieldNameToIndex(s:string):integer; const flist:array[1..11] of string = ('ENTID','TRANDATE','TRANTYPE','TRANID','MODCOUNT','AMT' ,'BALANCE','COMMENT','YRMO','USERID','TIMESTAMP' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 11) and (flist[x] <> s) do inc(x); if x <= 11 then result := x else result := 0; end; function TInfoESOABuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftSmallInt; 6 : result := ftCurrency; 7 : result := ftCurrency; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; end; end; function TInfoESOABuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PEntId; 2 : result := @Data.PTranDate; 3 : result := @Data.PTranType; 4 : result := @Data.PTranId; 5 : result := @Data.PModCount; 6 : result := @Data.PAmt; 7 : result := @Data.PBalance; 8 : result := @Data.PComment; 9 : result := @Data.PYrMo; 10 : result := @Data.PUserId; 11 : result := @Data.PTimeStamp; end; end; end.
unit uModel; interface type TPessoa = class private FEmail: string; FNome: String; procedure SetEmail(const Value: string); procedure SetNome(const Value: String); { private declarations } protected { protected declarations } public { public declarations } property Nome : String read FNome write SetNome; property Email : string read FEmail write SetEmail; end; TPessoaFisica = class(TPessoa) private FCPF: String; procedure SetCPF(const Value: String); { private declarations } protected { protected declarations } public { public declarations } property CPF : String read FCPF write SetCPF; end; implementation { TPessoa } procedure TPessoa.SetEmail(const Value: string); begin FEmail := Value; end; procedure TPessoa.SetNome(const Value: String); begin FNome := Value; end; { TPessoaFisica } procedure TPessoaFisica.SetCPF(const Value: String); begin FCPF := Value; end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCCONST.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} {$IFDEF Win32} {$R OVCCONST.R32} {$ELSE} {$R OVCCONST.R16} {$ENDIF} unit OvcConst; {-Command and resource constants} interface const {value used to offset string resource id's} BaseOffset = 32768; {***} const {$I OVCCONST.INC} {also used by resource compiler} type TovcCommandName = ( _ccNone, _ccBack, _ccBotOfPage, _ccBotRightCell, _ccCompleteDate, _ccCompleteTime, _ccCopy, _ccCtrlChar, _ccCut, _ccDec, _ccDel, _ccDelBol, _ccDelEol, _ccDelLine, _ccDelWord, _ccDown, _ccEnd, _ccExtendDown, _ccExtendEnd, _ccExtendHome, _ccExtendLeft, _ccExtendPgDn, _ccExtendPgUp, _ccExtendRight, _ccExtendUp, _ccExtBotOfPage, _ccExtFirstPage, _ccExtLastPage, _ccExtTopOfPage, _ccExtWordLeft, _ccExtWordRight, _ccFirstPage, _ccGotoMarker0, _ccGotoMarker1, _ccGotoMarker2, _ccGotoMarker3, _ccGotoMarker4, _ccGotoMarker5, _ccGotoMarker6, _ccGotoMarker7, _ccGotoMarker8, _ccGotoMarker9, _ccHome, _ccInc, _ccIns, _ccLastPage, _ccLeft, _ccNewLine, _ccNextPage, _ccPageLeft, _ccPageRight, _ccPaste, _ccPrevPage, _ccRedo, _ccRestore, _ccRight, _ccScrollDown, _ccScrollUp, _ccSetMarker0, _ccSetMarker1, _ccSetMarker2, _ccSetMarker3, _ccSetMarker4, _ccSetMarker5, _ccSetMarker6, _ccSetMarker7, _ccSetMarker8, _ccSetMarker9, _ccTab, _ccTableEdit, _ccTopLeftCell, _ccTopOfPage, _ccUndo, _ccUp, _ccWordLeft, _ccWordRight, _ccSelect, _ccAllSelect, _ccAllDeselect, _ccAllInvSelect, _ccActionItem, _ccTreeExpand, _ccTreeAllExpand, _ccMoveLeft, _ccMoveRight, _ccMoveUp, _ccMoveDown, _ccStartSelBlock, _ccEndSelBlock, _ccFastFindNext, _ccDelWordLeft, _ccDelWordRight, _ccTreeCollapse ); const {offset for resource id's} CommandResOfs = BaseOffset + 1000; {***} {command codes - corresponding text offset by CommandOfs, stored in rc file} {*** must be contiguous ***} ccFirstCmd = 0; {first defined command} ccNone = 0; {no command or not a known command} ccBack = 1; {backspace one character} ccBotOfPage = 2; {move caret to end of last page} ccBotRightCell = 3; {move to the bottom right hand cell in a table} ccCompleteDate = 4; {use default date for current date sub field} ccCompleteTime = 5; {use default time for current time sub field} ccCopy = 6; {copy highlighted text to clipboard} ccCtrlChar = 7; {accept control character} ccCut = 8; {copy highlighted text to clipboard and delete it} ccDec = 9; {decrement the current entry field value} ccDel = 10; {delete current character} ccDelBol = 11; {delete from caret to beginning of line} ccDelEol = 12; {delete from caret to end of line} ccDelLine = 13; {delete entire line} ccDelWord = 14; {delete word to right of caret} ccDown = 15; {cursor down} ccEnd = 16; {caret to end of line} ccExtendDown = 17; {extend selection down one line} ccExtendEnd = 18; {extend highlight to end of field} ccExtendHome = 19; {extend highlight to start of field} ccExtendLeft = 20; {extend highlight left one character} ccExtendPgDn = 21; {extend selection down one page} ccExtendPgUp = 22; {extend selection up one page} ccExtendRight = 23; {extend highlight right one character} ccExtendUp = 24; {extend selection up one line} ccExtBotOfPage = 25; {extend selection to bottom of page} ccExtFirstPage = 26; {extend selection to first page} ccExtLastPage = 27; {extend selection to last page} ccExtTopOfPage = 28; {extend selection to top of page} ccExtWordLeft = 29; {extend highlight left one word} ccExtWordRight = 30; {extend highlight right one word} ccFirstPage = 31; {first page in table} ccGotoMarker0 = 32; {editor & viewer, go to a position marker} ccGotoMarker1 = 33; {editor & viewer, go to a position marker} ccGotoMarker2 = 34; {editor & viewer, go to a position marker} ccGotoMarker3 = 35; {editor & viewer, go to a position marker} ccGotoMarker4 = 36; {editor & viewer, go to a position marker} ccGotoMarker5 = 37; {editor & viewer, go to a position marker} ccGotoMarker6 = 38; {editor & viewer, go to a position marker} ccGotoMarker7 = 39; {editor & viewer, go to a position marker} ccGotoMarker8 = 40; {editor & viewer, go to a position marker} ccGotoMarker9 = 41; {editor & viewer, go to a position marker} ccHome = 42; {caret to beginning of line} ccInc = 43; {increment the current entry field value} ccIns = 44; {toggle insert mode} ccLastPage = 45; {last page in table} ccLeft = 46; {caret left by one character} ccNewLine = 47; {editor, create a new line} ccNextPage = 48; {next page in table} ccPageLeft = 49; {move left a page in the table} ccPageRight = 50; {move right a page in the table} ccPaste = 51; {paste text from clipboard} ccPrevPage = 52; {previous page in table} ccRedo = 53; {re-do the last undone operation} ccRestore = 54; {restore default and continue} ccRight = 55; {caret right by one character} ccScrollDown = 56; {editor, scroll page up one line} ccScrollUp = 57; {editor, scroll page down one line} ccSetMarker0 = 58; {editor & viewer, set a position marker} ccSetMarker1 = 59; {editor & viewer, set a position marker} ccSetMarker2 = 60; {editor & viewer, set a position marker} ccSetMarker3 = 61; {editor & viewer, set a position marker} ccSetMarker4 = 62; {editor & viewer, set a position marker} ccSetMarker5 = 63; {editor & viewer, set a position marker} ccSetMarker6 = 64; {editor & viewer, set a position marker} ccSetMarker7 = 65; {editor & viewer, set a position marker} ccSetMarker8 = 66; {editor & viewer, set a position marker} ccSetMarker9 = 67; {editor & viewer, set a position marker} ccTab = 68; {editor, for tab entry} ccTableEdit = 69; {enter/exit table edit mode} ccTopLeftCell = 70; {move to the top left cell in a table} ccTopOfPage = 71; {move caret to beginning of first page} ccUndo = 72; {undo last operation} ccUp = 73; {cursor up} ccWordLeft = 74; {caret left one word} ccWordRight = 75; {caret right one word} ccSelect = 76; ccAllSelect = 77; ccAllDeselect = 78; ccAllInvSelect = 79; ccActionItem = 80; ccTreeExpand = 81; ccTreeAllExpand = 82; ccMoveLeft = 83; ccMoveRight = 84; ccMoveUp = 85; ccMoveDown = 86; ccStartSelBlock = 87; ccEndSelBlock = 88; ccFastFindNext = 89; ccDelWordLeft = 90; ccDelWordRight = 91; ccTreeCollapse = 92; ccLastCmd = 92; {***} {last interfaced command} ccMoveLeftInt = ccLastCmd + 1; ccMoveRightInt = ccLastCmd + 2; {internal} ccChar = 249; {regular character; generated internally} ccMouse = 250; {mouse selection; generated internally} ccMouseMove = 251; {mouse move; generated internally} ccAccept = 252; {accept next key; internal} ccDblClk = 253; {mouse double click; generated internally} ccSuppress = 254; {suppress next key; internal} ccPartial = 255; {partial command; internal} ccShortCut = 256; {user defined commands start here} ccUserFirst = 257; ccUser0 = ccUserFirst + 0; ccUser1 = ccUserFirst + 1; ccUser2 = ccUserFirst + 2; ccUser3 = ccUserFirst + 3; ccUser4 = ccUserFirst + 4; ccUser5 = ccUserFirst + 5; ccUser6 = ccUserFirst + 6; ccUser7 = ccUserFirst + 7; ccUser8 = ccUserFirst + 8; ccUser9 = ccUserFirst + 9; {... = ccUserFirst + 65535 - ccUserFirst} {data type base offset} const DataTypeOfs = BaseOffset + 1300; {***} {entry field data type sub codes} const fsubString = 0; {field subclass codes} fsubChar = 1; fsubBoolean = 2; fsubYesNo = 3; fsubLongInt = 4; fsubWord = 5; fsubInteger = 6; fsubByte = 7; fsubShortInt = 8; fsubReal = 9; fsubExtended = 10; fsubDouble = 11; fsubSingle = 12; fsubComp = 13; fsubDate = 14; fsubTime = 15; {constants for simple, picture, and numeric picture} {mask samples used in the property editors} const PictureMaskOfs = BaseOffset + 1700; {***} {simple field mask characters} stsmFirst = 34468; stsmLast = 34468 + 23; {numeric field picture masks} stnmFirst = 34493; stnmLast = 34493 + 17; {picture field picture masks} stpmFirst = 34518; stpmLast = 34518 + 23; const {viewer/editor line selection cursor} crLineCursor = BaseOffset - 100; {design-time tab selecting cursor id} crTabCursor = BaseOffset - 101; {constants for bitmap resources for db array editors} bmArrow = BaseOffset - 102; bmEdit = BaseOffset - 103; bmInsert = BaseOffset - 104; {row/column move cursors for the table} crRowMove = BaseOffset - 105; crColumnMove = BaseOffset - 106; {bitmap for dialog button control} bmDots = BaseOffset - 107; implementation end.
{ High frequency stop watch implemntation. Copyright (c) 2012 by Inoussa OUEDRAOGO This source code is distributed under the Library GNU General Public License with the following modification: - object files and libraries linked into an application may be distributed without source code. 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. **********************************************************************} {$IFDEF FPC} {$mode objfpc}{$H+} {$modeswitch advancedrecords} {$ENDIF} {$IFDEF MSWINDOWS} {$IFNDEF WINDOWS} {$DEFINE WINDOWS} {$ENDIF WINDOWS} {$ENDIF MSWINDOWS} unit stopwatch; interface uses SysUtils {$IFDEF LINUX} ,unixtype, linux {$ENDIF LINUX} ; type { TStopWatch } TStopWatch = record private const C_THOUSAND = 1000; C_MILLION = C_THOUSAND * C_THOUSAND; C_BILLION = C_THOUSAND * C_THOUSAND * C_THOUSAND; TicksPerNanoSecond = 100; TicksPerMilliSecond = 10000; TicksPerSecond = C_BILLION div 100; Type TBaseMesure = {$IFDEF WINDOWS} Int64; {$ENDIF WINDOWS} {$IFDEF LINUX} TTimeSpec; {$ENDIF LINUX} strict private class var FFrequency : Int64; class var FIsHighResolution : Boolean; strict private FElapsed : Int64; FRunning : Boolean; FStartPosition : TBaseMesure; strict private procedure CheckInitialization();inline; function GetElapsedMilliseconds: Int64; function GetElapsedTicks: Int64; public class function Create() : TStopWatch;static; class function StartNew() : TStopWatch;static; class property Frequency : Int64 read FFrequency; class property IsHighResolution : Boolean read FIsHighResolution; procedure Reset(); procedure Start(); procedure Stop(); property ElapsedMilliseconds : Int64 read GetElapsedMilliseconds; property ElapsedTicks : Int64 read GetElapsedTicks; property IsRunning : Boolean read FRunning; end; resourcestring sStopWatchNotInitialized = 'The StopWatch is not initialized.'; implementation {$IFDEF WINDOWS} uses Windows; {$ENDIF WINDOWS} { TStopWatch } class function TStopWatch.Create(): TStopWatch; {$IFDEF LINUX} var r : TBaseMesure; {$ENDIF LINUX} begin if (FFrequency = 0) then begin {$IFDEF WINDOWS} FIsHighResolution := QueryPerformanceFrequency(FFrequency); {$ENDIF WINDOWS} {$IFDEF LINUX} FIsHighResolution := (clock_getres(CLOCK_MONOTONIC,@r) = 0); FIsHighResolution := FIsHighResolution and (r.tv_nsec <> 0); if (r.tv_nsec <> 0) then FFrequency := C_BILLION div r.tv_nsec; {$ENDIF LINUX} end; FillChar(Result,SizeOf(Result),0); end; class function TStopWatch.StartNew() : TStopWatch; begin Result := TStopWatch.Create(); Result.Start(); end; procedure TStopWatch.CheckInitialization(); begin if (FFrequency = 0) then raise Exception.Create(sStopWatchNotInitialized); end; function TStopWatch.GetElapsedMilliseconds: Int64; begin {$IFDEF WINDOWS} Result := ElapsedTicks * TicksPerMilliSecond; {$ENDIF WINDOWS} {$IFDEF LINUX} Result := FElapsed div C_MILLION; {$ENDIF LINUX} end; function TStopWatch.GetElapsedTicks: Int64; begin CheckInitialization(); {$IFDEF WINDOWS} Result := (FElapsed * TicksPerSecond) div FFrequency; {$ENDIF WINDOWS} {$IFDEF LINUX} Result := FElapsed div TicksPerNanoSecond; {$ENDIF LINUX} end; procedure TStopWatch.Reset(); begin Stop(); FElapsed := 0; FillChar(FStartPosition,SizeOf(FStartPosition),0); end; procedure TStopWatch.Start(); begin if FRunning then exit; FRunning := True; {$IFDEF WINDOWS} QueryPerformanceCounter(FStartPosition); {$ENDIF WINDOWS} {$IFDEF LINUX} clock_gettime(CLOCK_MONOTONIC,@FStartPosition); {$ENDIF LINUX} end; procedure TStopWatch.Stop(); var locEnd : TBaseMesure; s, n : Int64; begin if not FRunning then exit; FRunning := False; {$IFDEF WINDOWS} QueryPerformanceCounter(locEnd); FElapsed := FElapsed + (UInt64(locEnd) - UInt64(FStartPosition)); {$ENDIF WINDOWS} {$IFDEF LINUX} clock_gettime(CLOCK_MONOTONIC,@locEnd); if (locEnd.tv_nsec < FStartPosition.tv_nsec) then begin s := locEnd.tv_sec - FStartPosition.tv_sec - 1; n := C_BILLION + locEnd.tv_nsec - FStartPosition.tv_nsec; end else begin s := locEnd.tv_sec - FStartPosition.tv_sec; n := locEnd.tv_nsec - FStartPosition.tv_nsec; end; FElapsed := FElapsed + (s * C_BILLION) + n; {$ENDIF LINUX} end; end.
unit SQLDBToolsUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, toolsunit, db, sqldb, ibconnection, mysql40conn, mysql41conn, mysql50conn, pqconnection,odbcconn,oracleconnection,sqlite3conn; type TSQLDBTypes = (mysql40,mysql41,mysql50,postgresql,interbase,odbc,oracle,sqlite3); const MySQLdbTypes = [mysql40,mysql41,mysql50]; DBTypesNames : Array [TSQLDBTypes] of String[19] = ('MYSQL40','MYSQL41','MYSQL50','POSTGRESQL','INTERBASE','ODBC','ORACLE','SQLITE3'); FieldtypeDefinitionsConst : Array [TFieldType] of String[15] = ( '', 'VARCHAR(10)', 'SMALLINT', 'INTEGER', '', '', 'FLOAT', '', 'DECIMAL(18,4)', 'DATE', 'TIMESTAMP', 'TIMESTAMP', '', '', '', 'BLOB', 'BLOB', 'BLOB', '', '', '', '', '', 'CHAR(10)', '', '', '', '', '', '', '', '', '', '', '', '', 'TIMESTAMP', '', '', '' ); type { TSQLDBConnector } TSQLDBConnector = class(TDBConnector) FConnection : TSQLConnection; FTransaction : TSQLTransaction; FQuery : TSQLQuery; private procedure CreateFConnection; procedure CreateFTransaction; Function CreateQuery : TSQLQuery; protected procedure CreateNDatasets; override; procedure CreateFieldDataset; override; procedure DropNDatasets; override; procedure DropFieldDataset; override; Function InternalGetNDataset(n : integer) : TDataset; override; Function InternalGetFieldDataset : TDataSet; override; procedure TryDropIfExist(ATableName : String); public destructor Destroy; override; constructor Create; override; property Connection : TSQLConnection read FConnection; property Transaction : TSQLTransaction read FTransaction; property Query : TSQLQuery read FQuery; end; var SQLDbType : TSQLDBTypes; FieldtypeDefinitions : Array [TFieldType] of String[15]; implementation { TSQLDBConnector } procedure TSQLDBConnector.CreateFConnection; var i : TSQLDBTypes; t : integer; begin for i := low(DBTypesNames) to high(DBTypesNames) do if UpperCase(dbconnectorparams) = DBTypesNames[i] then sqldbtype := i; FieldtypeDefinitions := FieldtypeDefinitionsConst; if SQLDbType = MYSQL40 then Fconnection := tMySQL40Connection.Create(nil); if SQLDbType = MYSQL41 then Fconnection := tMySQL41Connection.Create(nil); if SQLDbType in [mysql40,mysql41] then begin // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar // fields on insertion. So to test properly, we have to do the same for t := 0 to testValuesCount-1 do testStringValues[t] := TrimRight(testStringValues[t]); end; if SQLDbType = MYSQL50 then Fconnection := tMySQL50Connection.Create(nil); if SQLDbType in MySQLdbTypes then FieldtypeDefinitions[ftLargeint] := 'BIGINT'; if SQLDbType = sqlite3 then begin Fconnection := TSQLite3Connection.Create(nil); FieldtypeDefinitions[ftCurrency] := 'CURRENCY'; FieldtypeDefinitions[ftFixedChar] := ''; end; if SQLDbType = POSTGRESQL then begin Fconnection := tpqConnection.Create(nil); FieldtypeDefinitions[ftBlob] := 'TEXT'; FieldtypeDefinitions[ftMemo] := 'TEXT'; FieldtypeDefinitions[ftGraphic] := ''; FieldtypeDefinitions[ftCurrency] := 'MONEY'; end; if SQLDbType = INTERBASE then begin Fconnection := tIBConnection.Create(nil); FieldtypeDefinitions[ftLargeint] := 'BIGINT'; end; if SQLDbType = ODBC then Fconnection := tODBCConnection.Create(nil); if SQLDbType = ORACLE then Fconnection := TOracleConnection.Create(nil); if not assigned(Fconnection) then writeln('Invalid database-type, check if a valid database-type was provided in the file ''database.ini'''); with Fconnection do begin DatabaseName := dbname; UserName := dbuser; Password := dbpassword; HostName := dbhostname; open; end; end; procedure TSQLDBConnector.CreateFTransaction; begin Ftransaction := tsqltransaction.create(nil); with Ftransaction do database := Fconnection; end; Function TSQLDBConnector.CreateQuery : TSQLQuery; begin Result := TSQLQuery.create(nil); with Result do begin database := Fconnection; transaction := Ftransaction; end; end; procedure TSQLDBConnector.CreateNDatasets; var CountID : Integer; begin try Ftransaction.StartTransaction; TryDropIfExist('FPDEV'); Fconnection.ExecuteDirect('create table FPDEV ( ' + ' ID INT NOT NULL, ' + ' NAME VARCHAR(50), ' + ' PRIMARY KEY (ID) ' + ') '); FTransaction.CommitRetaining; for countID := 1 to MaxDataSet do Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' + 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')'); Ftransaction.Commit; except if Ftransaction.Active then Ftransaction.Rollback end; end; procedure TSQLDBConnector.CreateFieldDataset; var CountID : Integer; FType : TFieldType; Sql,sql1: String; begin try Ftransaction.StartTransaction; TryDropIfExist('FPDEV_FIELD'); Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,'; for FType := low(TFieldType)to high(TFieldType) do if FieldtypeDefinitions[FType]<>'' then sql := sql + 'F' + Fieldtypenames[FType] + ' ' +FieldtypeDefinitions[FType]+ ','; Sql := Sql + 'PRIMARY KEY (ID))'; FConnection.ExecuteDirect(Sql); FTransaction.CommitRetaining; for countID := 0 to testValuesCount-1 do begin Sql := 'insert into FPDEV_FIELD (ID'; Sql1 := 'values ('+IntToStr(countID); for FType := low(TFieldType)to high(TFieldType) do if FieldtypeDefinitions[FType]<>'' then begin sql := sql + ',F' + Fieldtypenames[FType]; if testValues[FType,CountID] <> '' then sql1 := sql1 + ',''' + StringReplace(testValues[FType,CountID],'''','''''',[rfReplaceAll]) + '''' else sql1 := sql1 + ',NULL'; end; Sql := sql + ')'; Sql1 := sql1+ ')'; Fconnection.ExecuteDirect(sql + ' ' + sql1); end; Ftransaction.Commit; except if Ftransaction.Active then Ftransaction.Rollback end; end; procedure TSQLDBConnector.DropNDatasets; begin if assigned(FTransaction) then begin try if Ftransaction.Active then Ftransaction.Rollback; Ftransaction.StartTransaction; Fconnection.ExecuteDirect('DROP TABLE FPDEV'); Ftransaction.Commit; Except if Ftransaction.Active then Ftransaction.Rollback end; end; end; procedure TSQLDBConnector.DropFieldDataset; begin if assigned(FTransaction) then begin try if Ftransaction.Active then Ftransaction.Rollback; Ftransaction.StartTransaction; Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD'); Ftransaction.Commit; Except if Ftransaction.Active then Ftransaction.Rollback end; end; end; function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset; begin Result := CreateQuery; with (Result as TSQLQuery) do begin sql.clear; sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1)); end; end; function TSQLDBConnector.InternalGetFieldDataset: TDataSet; begin Result := CreateQuery; with (Result as TSQLQuery) do begin sql.clear; sql.add('SELECT * FROM FPDEV_FIELD'); end; end; procedure TSQLDBConnector.TryDropIfExist(ATableName: String); begin // This makes live soo much easier, since it avoids the exception if the table already // exists. And while this exeption is in a try..except statement, the debugger // always shows the exception. Which is pretty annoying // It only works with Firebird 2, though. try if SQLDbType = INTERBASE then begin FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+ 'then execute statement ''drop table ' + ATAbleName + ';'';end'); FTransaction.CommitRetaining; end; except FTransaction.RollbackRetaining; end; end; destructor TSQLDBConnector.Destroy; begin if assigned(FTransaction) then begin try if Ftransaction.Active then Ftransaction.Rollback; Ftransaction.StartTransaction; Fconnection.ExecuteDirect('DROP TABLE FPDEV2'); Ftransaction.Commit; Except if Ftransaction.Active then Ftransaction.Rollback end; // try end; inherited Destroy; FreeAndNil(FQuery); FreeAndNil(FTransaction); FreeAndNil(FConnection); end; constructor TSQLDBConnector.Create; begin FConnection := nil; CreateFConnection; CreateFTransaction; FQuery := CreateQuery; FConnection.Transaction := FTransaction; Inherited; end; initialization RegisterClass(TSQLDBConnector); end.
unit DAO.Estados; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.Estados; type TEstadosDAO = class private FConexao: TConexao; public constructor Create; destructor Destroy; function Inserir(aEstados: TEstados): Boolean; function Alterar(aEstados: TEstados): Boolean; function Excluir(aEsTados: TEstados): Boolean; function EstadoExiste(aEstados: TEstados): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'cadastro_estados'; implementation { TEstadosDAO } function TEstadosDAO.Alterar(aEstados: TEstados): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + 'set nom_estado = :pnom_estado, cep_inicial = :pcep_inicial, cep_final = :pcep_final, ' + 'des_log = :pdes_log ' + 'where uf_estado = :puf_estado;', [aEstados.Nome, aEstados.CEPInicial, aEstados.CEPFinal, aEstados.LOG, aEstados.UF]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TEstadosDAO.Create; begin FConexao := TConexao.Create; end; destructor TEstadosDAO.Destroy; begin FConexao.Free; end; function TEstadosDAO.EstadoExiste(aEstados: TEstados): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('select * from ' + TABLENAME + 'where uf_estado = :puf_estado;', [aEstados.UF]); if FDQuery.IsEmpty then Exit; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEstadosDAO.Excluir(aEsTados: TEstados): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + 'where uf_estado = :puf_estado;', [aEstados.UF]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEstadosDAO.Inserir(aEstados: TEstados): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('insert into ' + TABLENAME + '(uf_estado, nom_estado, cep_inicial, cep_final, des_log) values' + '(:puf_estado, :pnom_estado, :pcep_inicial, :pcep_final, :pdes_log);', [aEstados.UF, aEstados.Nome, aEstados.CEPInicial, aEstados.CEPFinal, aEstados.LOG]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TEstadosDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery : TFDQuery; begin FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'UF' then begin FDQuery.SQL.Add('where uf_estado = :puf_estado'); FDQuery.ParamByName('puf_estado').AsString := aParam[1]; end else if aParam[0] = 'NOME' then begin FDQuery.SQL.Add('where nom_estado = :pnom_estado'); FDQuery.ParamByName('pnom_estado').AsString := aParam[1]; end else if aParam[0] = 'CEP' then begin FDQuery.SQL.Add('where cep_inicial <= :pcep and cep_final >= :pcep'); FDQuery.ParamByName('pcep').AsString := aParam[1]; end else if aParam[0] = 'FAIXA' then begin FDQuery.SQL.Add('where cep_inicial <= :pcep_inicial and cep_final >= :pcep_final'); FDQuery.ParamByName('pcep_inicial').AsString := aParam[1]; FDQuery.ParamByName('pcep_final').AsString := aParam[2]; end else if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
{ Double Commander ------------------------------------------------------------------------- Simple key file implementation based on GKeyFile Copyright (C) 2014 Alexander Koblov (alexx2000@mail.ru) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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 uKeyFile; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles, DCBasicTypes, uGLib2; const { Constants for handling freedesktop.org Desktop files } DESKTOP_GROUP = 'Desktop Entry'; DESKTOP_KEY_CATEGORIES = 'Categories'; DESKTOP_KEY_COMMENT = 'Comment'; DESKTOP_KEY_EXEC = 'Exec'; DESKTOP_KEY_ICON = 'Icon'; DESKTOP_KEY_NAME = 'Name'; DESKTOP_KEY_TYPE = 'Type'; DESKTOP_KEY_TRY_EXEC = 'TryExec'; DESKTOP_KEY_MIME_TYPE = 'MimeType'; DESKTOP_KEY_NO_DISPLAY = 'NoDisplay'; DESKTOP_KEY_TERMINAL = 'Terminal'; DESKTOP_KEY_KDE_BUG = 'Path[$e]'; type { TKeyFile } TKeyFile = class(TCustomIniFile) private FGKeyFile: PGKeyFile; protected function LoadFromFile(const AFileName: String; out AMessage: String): Boolean; inline; public constructor Create(const AFileName: String; AEscapeLineFeeds : Boolean = False); override; destructor Destroy; override; public function SectionExists(const Section: String): Boolean; override; function ReadBool(const Section, Ident: String; Default: Boolean): Boolean; override; function ReadString(const Section, Ident, Default: String): String; override; function ReadLocaleString(const Section, Ident, Default: String): String; virtual; function ReadStringList(const Section, Ident: String): TDynamicStringArray; virtual; protected procedure WriteString(const Section, Ident, Value: String); override; procedure ReadSection(const Section: string; Strings: TStrings); override; procedure ReadSections(Strings: TStrings); override; procedure ReadSectionValues(const Section: string; Strings: TStrings); override; procedure EraseSection(const Section: string); override; procedure DeleteKey(const Section, Ident: String); override; procedure UpdateFile; override; end; implementation uses RtlConsts, DCStrUtils; { TKeyFile } function TKeyFile.LoadFromFile(const AFileName: String; out AMessage: String): Boolean; var AChar: Pgchar; ALength: gsize; AContents: Pgchar; AError: PGError = nil; function FormatMessage: String; begin if Assigned(AError) then begin Result:= StrPas(AError^.message); g_error_free(AError); AError:= nil; end; end; begin Result:= g_key_file_load_from_file(FGKeyFile, Pgchar(AFileName), G_KEY_FILE_NONE, @AError); if not Result then begin AMessage:= FormatMessage; // KDE menu editor adds invalid "Path[$e]" key. GKeyFile cannot parse // such desktop files. We comment it before parsing to avoid this problem. if Pos(DESKTOP_KEY_KDE_BUG, AMessage) > 0 then begin Result:= g_file_get_contents(Pgchar(AFileName), @AContents, @ALength, @AError); if not Result then AMessage:= FormatMessage else try AChar:= g_strstr_len(AContents, ALength, DESKTOP_KEY_KDE_BUG); if Assigned(AChar) then AChar^:= '#'; Result:= g_key_file_load_from_data(FGKeyFile, AContents, ALength, G_KEY_FILE_NONE, @AError); if not Result then AMessage:= FormatMessage; finally g_free(AContents); end; end; end; end; constructor TKeyFile.Create(const AFileName: String; AEscapeLineFeeds: Boolean); var AMessage: String; begin FGKeyFile:= g_key_file_new(); if not LoadFromFile(AFileName, AMessage) then raise EFOpenError.CreateFmt(SFOpenErrorEx, [AFileName, AMessage]); inherited Create(AFileName, AEscapeLineFeeds); CaseSensitive:= True; end; destructor TKeyFile.Destroy; begin inherited Destroy; g_key_file_free(FGKeyFile); end; function TKeyFile.SectionExists(const Section: String): Boolean; begin Result:= g_key_file_has_group(FGKeyFile, Pgchar(Section)); end; function TKeyFile.ReadBool(const Section, Ident: String; Default: Boolean): Boolean; {$OPTIMIZATION OFF} var AError: PGError = nil; begin Result:= g_key_file_get_boolean(FGKeyFile, Pgchar(Section), Pgchar(Ident), @AError); if (AError <> nil) then begin Result:= Default; g_error_free(AError); end; end; {$OPTIMIZATION DEFAULT} function TKeyFile.ReadString(const Section, Ident, Default: String): String; var AValue: Pgchar; begin AValue:= g_key_file_get_string(FGKeyFile, Pgchar(Section), Pgchar(Ident), nil); if (AValue = nil) then Result:= Default else begin Result:= StrPas(AValue); g_free(AValue); end; end; function TKeyFile.ReadLocaleString(const Section, Ident, Default: String): String; var AValue: Pgchar; begin AValue:= g_key_file_get_locale_string(FGKeyFile, Pgchar(Section), Pgchar(Ident), nil, nil); if (AValue = nil) then Result:= Default else begin Result:= StrPas(AValue); g_free(AValue); end; end; function TKeyFile.ReadStringList(const Section, Ident: String): TDynamicStringArray; var AValue: PPgchar; AIndex, ALength: gsize; begin AValue:= g_key_file_get_string_list(FGKeyFile, Pgchar(Section), Pgchar(Ident), @ALength, nil); if Assigned(AValue) then begin SetLength(Result, ALength); for AIndex:= 0 to Pred(ALength) do begin Result[AIndex]:= StrPas(AValue[AIndex]); end; g_strfreev(AValue); end; end; procedure TKeyFile.WriteString(const Section, Ident, Value: String); begin end; procedure TKeyFile.ReadSection(const Section: string; Strings: TStrings); begin end; procedure TKeyFile.ReadSections(Strings: TStrings); begin end; procedure TKeyFile.ReadSectionValues(const Section: string; Strings: TStrings); begin end; procedure TKeyFile.EraseSection(const Section: string); begin end; procedure TKeyFile.DeleteKey(const Section, Ident: String); begin end; procedure TKeyFile.UpdateFile; begin end; end.
unit XMLTBase; interface uses Classes; type TXmlEncodingType = (xetUnknow, xetUTF_8, xetUTF_16, xetBIG5, xetGB2312, xetS_JIS, xetEUC_KR, xetIS0_8859_1); function XmlT_StrToBool(const Value: WideString): Boolean; function XmlT_BoolToStr(const Value: Boolean): WideString; function XmlT_StrToDateTime(const Value: WideString): TDateTime; function XmlT_StrToDate(const Value: WideString): TDateTime; function XmlT_StrToTime(const Value: WideString): TDateTime; function XmlT_DateTimeToStr(const Value: TDateTime): WideString; function XmlT_DateToStr(const Value: TDateTime): WideString; function XmlT_TimeToStr(const Value: TDateTime): WideString; function XmlT_Base64ToStr(Base64: WideString): WideString; function XmlT_StrToBase64(Str: WideString): WideString; procedure XmlT_MimeEncodeStream(const InputStream: TStream; const OutputStream: TStream); procedure XmlT_MimeDecodeStream(const InputStream: TStream; const OutputStream: TStream); const XT_XML_EncodingStr: array[TXmlEncodingType] of WideString = ('Unknow', 'UTF-8', 'UTF-16', 'BIG5', 'GB2312', 'S-JIS', 'EUC-KR', 'IS0-8859-1'); XT_True_Text: array[0..14] of WideString = ('true', 'T', 'Yes', 'Y', 'Just', 'Right', 'Correct', 'OK', '1', 'On', 'Agree', '是', '對', '好', '正確'); XT_False_Text: array[0..17] of WideString = ('false', 'F', 'No', 'N', 'Unjust', 'Wrong', 'Incorrect', 'Cancel', '0', 'Off', 'Disagree', '否', '不對', '錯', '不', '不好', '不正確', '錯誤'); implementation uses SysUtils, Windows, XSBuiltIns; type PByte4 = ^TByte4; TByte4 = packed record b1: Byte; b2: Byte; b3: Byte; b4: Byte; end; PByte3 = ^TByte3; TByte3 = packed record b1: Byte; b2: Byte; b3: Byte; end; const BUFFER_SIZE = $3000; { Caution: For MimeEncodeStream and all other kinds of multi-buffered Mime encodings (i.e. Files etc.), BufferSize must be set to a multiple of 3. Even though the implementation of the Mime decoding routines below does not require a particular buffer size, they work fastest with sizes of multiples of four. The chosen size is a multiple of 3 and of 4 as well. The following numbers are, in addition, also divisible by 1024: $2400, $3000, $3C00, $4800, $5400, $6000, $6C00. } MIME_ENCODE_TABLE: array[0..63] of Byte = ( 065, 066, 067, 068, 069, 070, 071, 072, // 00 - 07 073, 074, 075, 076, 077, 078, 079, 080, // 08 - 15 081, 082, 083, 084, 085, 086, 087, 088, // 16 - 23 089, 090, 097, 098, 099, 100, 101, 102, // 24 - 31 103, 104, 105, 106, 107, 108, 109, 110, // 32 - 39 111, 112, 113, 114, 115, 116, 117, 118, // 40 - 47 119, 120, 121, 122, 048, 049, 050, 051, // 48 - 55 052, 053, 054, 055, 056, 057, 043, 047); // 56 - 63 MIME_DECODE_TABLE: array[Byte] of Cardinal = ( 255, 255, 255, 255, 255, 255, 255, 255, // 00 - 07 255, 255, 255, 255, 255, 255, 255, 255, // 08 - 15 255, 255, 255, 255, 255, 255, 255, 255, // 16 - 23 255, 255, 255, 255, 255, 255, 255, 255, // 24 - 31 255, 255, 255, 255, 255, 255, 255, 255, // 32 - 39 255, 255, 255, 062, 255, 255, 255, 063, // 40 - 47 052, 053, 054, 055, 056, 057, 058, 059, // 48 - 55 060, 061, 255, 255, 255, 255, 255, 255, // 56 - 63 255, 000, 001, 002, 003, 004, 005, 006, // 64 - 71 007, 008, 009, 010, 011, 012, 013, 014, // 72 - 79 015, 016, 017, 018, 019, 020, 021, 022, // 80 - 87 023, 024, 025, 255, 255, 255, 255, 255, // 88 - 95 255, 026, 027, 028, 029, 030, 031, 032, // 96 - 103 033, 034, 035, 036, 037, 038, 039, 040, // 104 - 111 041, 042, 043, 044, 045, 046, 047, 048, // 112 - 119 049, 050, 051, 255, 255, 255, 255, 255, // 120 - 127 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255); function MimeEncodedSize(const i: Integer): Integer; begin Result := (i + 2) div 3 * 4; end; procedure MimeEncode(const InputBuffer: Pointer; const InputByteCount: Integer; const OutputBuffer: Pointer); var b: Cardinal; InMax3: Integer; pIn, PInLimit: ^Byte; POut: PByte4; begin {$IFDEF RangeChecking} if InputBuffer = nil then raise EMime.Create(SInputBufferNil); if OutputBuffer = nil then raise EMime.Create(SOutputBufferNil); {$ENDIF} if InputByteCount <= 0 then Exit; pIn := InputBuffer; InMax3 := InputByteCount div 3 * 3; POut := OutputBuffer; Integer(PInLimit) := Integer(pIn) + InMax3; while pIn <> PInLimit do begin b := pIn^; b := b shl 8; Inc(pIn); b := b or pIn^; b := b shl 8; Inc(pIn); b := b or pIn^; Inc(pIn); // Write 4 bytes to OutputBuffer (in reverse order). POut.b4 := MIME_ENCODE_TABLE[b and $3F]; b := b shr 6; POut.b3 := MIME_ENCODE_TABLE[b and $3F]; b := b shr 6; POut.b2 := MIME_ENCODE_TABLE[b and $3F]; b := b shr 6; POut.b1 := MIME_ENCODE_TABLE[b]; Inc(POut); end; case InputByteCount - InMax3 of 1: begin b := pIn^; b := b shl 4; POut.b2 := MIME_ENCODE_TABLE[b and $3F]; b := b shr 6; POut.b1 := MIME_ENCODE_TABLE[b]; POut.b3 := Ord('='); // Fill remaining 2 bytes. POut.b4 := Ord('='); end; 2: begin b := pIn^; Inc(pIn); b := b shl 8; b := b or pIn^; b := b shl 2; POut.b3 := MIME_ENCODE_TABLE[b and $3F]; b := b shr 6; POut.b2 := MIME_ENCODE_TABLE[b and $3F]; b := b shr 6; POut.b1 := MIME_ENCODE_TABLE[b]; POut.b4 := Ord('='); // Fill remaining byte. end; end; end; procedure XmlT_MimeEncodeStream(const InputStream: TStream; const OutputStream: TStream); var InputBuffer: array[0..BUFFER_SIZE - 1] of Byte; OutputBuffer: array[0..((BUFFER_SIZE + 2) div 3) * 4 - 1] of Byte; BytesRead: Integer; begin BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer)); while BytesRead = SizeOf(InputBuffer) do begin MimeEncode(@InputBuffer, SizeOf(InputBuffer), @OutputBuffer); OutputStream.Write(OutputBuffer, SizeOf(OutputBuffer)); BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer)); end; if BytesRead > 0 then begin MimeEncode(@InputBuffer, BytesRead, @OutputBuffer); OutputStream.Write(OutputBuffer, MimeEncodedSize(BytesRead)); end; end; function MimeDecodedSize(const i: Integer): Integer; begin Result := (i + 3) div 4 * 3; end; function MimeDecodePartialEnd(const OutputBuffer: Pointer; const ByteBuffer: Cardinal; const ByteBufferSpace: Cardinal): Integer; var lByteBuffer: Cardinal; begin {$IFDEF RangeChecking} if OutputBuffer = nil then raise EMime.Create(SOutputBufferNil); {$ENDIF} case ByteBufferSpace of 1: begin lByteBuffer := ByteBuffer shr 2; PByte3(OutputBuffer).b2 := Byte(lByteBuffer); lByteBuffer := lByteBuffer shr 8; PByte3(OutputBuffer).b1 := Byte(lByteBuffer); Result := 2; end; 2: begin lByteBuffer := ByteBuffer shr 4; PByte3(OutputBuffer).b1 := Byte(lByteBuffer); Result := 1; end; else Result := 0; end; end; function MimeDecodePartial(const InputBuffer: Pointer; const InputBytesCount: Integer; const OutputBuffer: Pointer; var ByteBuffer: Cardinal; var ByteBufferSpace: Cardinal): Integer; var lByteBuffer, lByteBufferSpace, c: Cardinal; pIn, PInLimit: ^Byte; POut: PByte3; begin {$IFDEF RangeChecking} if InputBuffer = nil then raise EMime.Create(SInputBufferNil); if OutputBuffer = nil then raise EMime.Create(SOutputBufferNil); {$ENDIF} if InputBytesCount > 0 then begin pIn := InputBuffer; Integer(PInLimit) := Integer(pIn) + InputBytesCount; POut := OutputBuffer; lByteBuffer := ByteBuffer; lByteBufferSpace := ByteBufferSpace; while pIn <> PInLimit do begin c := MIME_DECODE_TABLE[pIn^]; // Read from InputBuffer. Inc(pIn); if c = $FF then Continue; lByteBuffer := lByteBuffer shl 6; lByteBuffer := lByteBuffer or c; Dec(lByteBufferSpace); if lByteBufferSpace <> 0 then Continue; // Read 4 bytes from InputBuffer? POut.b3 := Byte(lByteBuffer); // Write 3 bytes to OutputBuffer (in reverse order). lByteBuffer := lByteBuffer shr 8; POut.b2 := Byte(lByteBuffer); lByteBuffer := lByteBuffer shr 8; POut.b1 := Byte(lByteBuffer); lByteBuffer := 0; Inc(POut); lByteBufferSpace := 4; end; ByteBuffer := lByteBuffer; ByteBufferSpace := lByteBufferSpace; Result := Integer(POut) - Integer(OutputBuffer); end else Result := 0; end; procedure XmlT_MimeDecodeStream(const InputStream: TStream; const OutputStream: TStream); var ByteBuffer, ByteBufferSpace: Cardinal; InputBuffer: array[0..BUFFER_SIZE - 1] of Byte; OutputBuffer: array[0..(BUFFER_SIZE + 3) div 4 * 3 - 1] of Byte; BytesRead: Integer; begin ByteBuffer := 0; ByteBufferSpace := 4; BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer)); while BytesRead > 0 do begin OutputStream.Write(OutputBuffer, MimeDecodePartial(@InputBuffer, BytesRead, @OutputBuffer, ByteBuffer, ByteBufferSpace)); BytesRead := InputStream.Read(InputBuffer, SizeOf(InputBuffer)); end; OutputStream.Write(OutputBuffer, MimeDecodePartialEnd(@OutputBuffer, ByteBuffer, ByteBufferSpace)); end; function NumberToken(var SrcStr: WideString; IncludeTokenText: Boolean = False): Integer; var i: Integer; begin Result := 0; if SrcStr = '' then Exit; while True do begin if not (SrcStr[1] in [WideChar('0')..WideChar('9')]) then Delete(SrcStr, 1, 1) else Break; end; for i := 1 to Length(SrcStr) do if not (SrcStr[i] in [WideChar('0')..WideChar('9')]) then begin Result := StrToIntDef(Copy(SrcStr, 1, i - 1), 0); Delete(SrcStr, 1, i - 1); Exit; end; Result := StrToIntDef(SrcStr, 0); SrcStr := ''; end; function GetTimeZoneBias: Integer; var TimeZoneInfo: TTimeZoneInformation; begin case GetTimeZoneInformation(TimeZoneInfo) of TIME_ZONE_ID_STANDARD: Result := TimeZoneInfo.Bias + TimeZoneInfo.StandardBias; TIME_ZONE_ID_DAYLIGHT: Result := TimeZoneInfo.Bias + TimeZoneInfo.DaylightBias; TIME_ZONE_ID_INVALID: Result := 0; else Result := TimeZoneInfo.Bias; end; end; const BoolHourMarker: array [Boolean] of string = (XMLHourOffsetMinusMarker, XMLHourOffsetPlusMarker); function FixDateStr(Str: WideString): WideString; var Y, M, D: Word; begin Str := UpperCase(Trim(Str)); Str := StringReplace(Str, '/', XMLDateSeparator, [rfReplaceAll]); Str := StringReplace(Str, '.', XMLDateSeparator, [rfReplaceAll]); Str := StringReplace(Str, ',', XMLDateSeparator, [rfReplaceAll]); Str := StringReplace(Str, ' ', XMLDateSeparator, [rfReplaceAll]); Y := NumberToken(Str); M := NumberToken(Str); D := NumberToken(Str); Result := Format('%.04d%s%.02d%s%.02d%s', [Y, XMLDateSeparator, M, XMLDateSeparator, D, Str]); end; function FixTimeStr(Str: WideString): WideString; var H, N, S, MS: Word; TimeZoneBias: Integer; begin Str := UpperCase(Trim(Str)); Str := StringReplace(Str, '-', XMLTimeSeparator, [rfReplaceAll]); Str := StringReplace(Str, '.', XMLTimeSeparator, [rfReplaceAll]); Str := StringReplace(Str, ' ', XMLTimeSeparator, [rfReplaceAll]); H := NumberToken(Str); N := NumberToken(Str); S := NumberToken(Str); if (Str <> '') and (Str[1] in [WideChar('.'), WideChar(':')]) then MS := NumberToken(Str) else MS := 0; if (Str = '') or not (Str[1] in [WideChar('Z'), WideChar('+'), WideChar('-')]) then begin TimeZoneBias := GetTimeZoneBias; Str := Format('%s%.02d%s%.02d', [BoolHourMarker[TimeZoneBias < 0], (TimeZoneBias div 60)*-1, XMLTimeSeparator, (TimeZoneBias mod 60)*-1]); end; Result := Format('%.02d%s%.02d%s%.02d%s%.03d%s', [H, XMLTimeSeparator, N, XMLTimeSeparator, S, SoapDecimalSeparator, MS, Str]); end; function LocaleDateTimeToGMTDateTime(const Value: TDateTime): TDateTime; begin Result := Value + (GetTimeZoneBias / MinsPerDay); end; function GMTDateTimeToLocaleDateTime(const Value: TDateTime): TDateTime; begin Result := Value - (GetTimeZoneBias / MinsPerDay); end; function XmlT_StrToBool(const Value: WideString): Boolean; var TestStr: WideString; i: Integer; begin Result := False; TestStr := UpperCase(Trim(Value)); for i := Low(XT_True_Text) to High(XT_True_Text) do if UpperCase(XT_True_Text[i]) = TestStr then begin Result := True; Break; end; end; function XmlT_BoolToStr(const Value: Boolean): WideString; begin if Value then Result := XT_True_Text[0] else Result := XT_False_Text[0]; end; function XmlT_StrToDateTime(const Value: WideString): TDateTime; var TestStr, DateStr, TimeStr: WideString; begin Result := 0; TestStr := Trim(Value); if TestStr = '' then Exit; if Pos(' ', TestStr) > 0 then TestStr[Pos(' ', TestStr)] := SoapTimePrefix; if Pos(SoapTimePrefix, TestStr) = 0 then begin if Pos(XMLTimeSeparator, TestStr) > 0 then Result := XmlT_StrToTime(TestStr) else Result := XmlT_StrToDate(TestStr); end else begin try DateStr := Copy(TestStr, 1, Pos(SoapTimePrefix, TestStr) - 1); TimeStr := Copy(TestStr, Pos(SoapTimePrefix, TestStr) + 1, MaxInt); DateStr := FixDateStr(DateStr); TimeStr := FixTimeStr(TimeStr); Result := XmlT_StrToDate(DateStr) + XmlT_StrToTime(TimeStr); except Result := 0; end; end; end; function XmlT_StrToDate(const Value: WideString): TDateTime; var TestStr: WideString; XSDate: TXSDate; begin Result := 0; try TestStr := Trim(Value); if TestStr = '' then Exit; TestStr := FixDateStr(TestStr); XSDate := TXSDate.Create; try XSDate.XSToNative(TestStr); Result := EncodeDate(XSDate.Year, XSDate.Month, XSDate.Day); finally XSDate.Free; end; except Result := 0; end; end; function XmlT_StrToTime(const Value: WideString): TDateTime; var TestStr: WideString; XSTime: TXSTime; begin Result := 0; try TestStr := Trim(Value); if Pos('T', TestStr) > 0 then Delete(TestStr, 1, Pos('T', TestStr)); if TestStr = '' then Exit; TestStr := FixTimeStr(TestStr); XSTime := TXSTime.Create; try XSTime.UseZeroMilliseconds := False; XSTime.XSToNative(TestStr); Result := GMTDateTimeToLocaleDateTime( EncodeTime( (XSTime.Hour-XSTime.HourOffset) mod 24, (XSTime.Minute-XSTime.MinuteOffset) mod 60, XSTime.Second, XSTime.Millisecond) ); finally XSTime.Free; end; except Result := 0; end; end; function XmlT_DateTimeToStr(const Value: TDateTime): WideString; function IsOnlyDate: Boolean; var D1, D2, D3: Word; begin DecodeDate(Value, D1, D2, D3); Result := Value = EncodeDate(D1, D2, D3); end; function IsOnlyTime: Boolean; var D1, D2, D3: Word; begin DecodeDate(Value, D1, D2, D3); Result := (D1 = 1899) and (D2 = 12) and (D3 = 30); end; begin Result := ''; if Value = 0 then Result := '' else begin if IsOnlyDate then Result := XmlT_DateToStr(Value) else if IsOnlyTime then Result := XmlT_TimeToStr(Value) else Result := XmlT_DateToStr(Value) + SoapTimePrefix + XmlT_TimeToStr(Value); end; end; function XmlT_DateToStr(const Value: TDateTime): WideString; var XSDate: TXSDate; begin Result := ''; if Value = 0 then Result := '' else begin XSDate := TXSDate.Create; try XSDate.AsDate := Value; Result := XSDate.NativeToXS; finally XSDate.Free; end; end; end; function XmlT_TimeToStr(const Value: TDateTime): WideString; var XSTime: TXSTime; TimeZoneBias: Integer; begin Result := ''; if Value = 0 then Result := '' else begin XSTime := TXSTime.Create; try XSTime.UseZeroMilliseconds := False; XSTime.AsTime := Value; TimeZoneBias := GetTimeZoneBias; Result := Format('%.02d%s%.02d%s%.02d%s%.03d%s%.02d%s%.02d', [XSTime.Hour, XMLTimeSeparator, XSTime.Minute, XMLTimeSeparator, XSTime.Second, SoapDecimalSeparator, XSTime.Millisecond, BoolHourMarker[TimeZoneBias < 0], Abs(TimeZoneBias div 60), XMLTimeSeparator, Abs(TimeZoneBias mod 60)]) finally XSTime.Free; end; end; end; function XmlT_Base64ToStr(Base64: WideString): WideString; var S1, S2: TStringStream; begin S2 := TStringStream.Create(Trim(Base64)); try S1 := TStringStream.Create(''); try S2.Position := 0; XmlT_MimeDecodeStream(S2, S1); Result := S1.DataString; finally S1.Free; end; finally S2.Free; end; end; function XmlT_StrToBase64(Str: WideString): WideString; var S1, S2: TStringStream; begin S1 := TStringStream.Create(Str); try S2 := TStringStream.Create(''); try S1.Position := 0; XmlT_MimeEncodeStream(S1, S2); Result := S2.DataString; finally S2.Free; end; finally S1.Free; end; end; end.
unit RemoveRouteDestinationResponseUnit; interface uses REST.Json.Types, HttpQueryMemberAttributeUnit, GenericParametersUnit; type TRemoveRouteDestinationResponse = class(TGenericParameters) private [JSONName('deleted')] FDeleted: boolean; [JSONName('route_destination_id')] FRouteDestinationId: integer; public property Deleted: boolean read FDeleted write FDeleted; property RouteDestinationId: integer read FRouteDestinationId write FRouteDestinationId; end; implementation end.
//****************************************************************************** //*** Cactus Jukebox *** //*** *** //*** (c) 2006-2009 *** //*** *** //*** Massimo Magnano, maxm.dev@gmail.com *** //*** *** //****************************************************************************** // File : CJ_Plugin.pas // // Description : Declaration of Functions and Class that a plugin must export. // //****************************************************************************** // // functions that must be exported by a Plugin : // function GetPlugin :TCJ_Plugin; stdcall; // function GetPluginInfo :TCJ_PluginInfo; stdcall; // // Class Methods Call Sequenze : // Program Side | Plugin Side //------------------------------------------ // Create --> OnCreate // if LastEnabledState then SetEnabled(True) // // CloseQuery --> CanClose (if all plugins return true then Destroy) // // Destroy --> if Enabled then SetEnabled(False) // OnDestroy unit cj_plugin; {$mode delphi}{$H+} interface uses cj_interfaces; const PLUGIN_TYPE_NONE = 0; PLUGIN_TYPE_STD = 1; type TChars50 =array[0..50] of char; TCJ_PluginInfo = record pType :Integer; //PLUGIN_TYPE_XXXX pPackName, //The Name of Package when auto-install-uninstall (future use) pTitle, pAuthor, pEMail, pDescript :TChars50; end; PCJ_PluginInfo =^TCJ_PluginInfo; TCJ_Plugin = class public procedure OnCreate(ACJInterface :TCJ_Interface); virtual; abstract; procedure OnDestroy; virtual; abstract; function CanClose :Boolean; virtual; abstract; procedure SetEnabled(Value :Boolean); virtual; abstract; procedure SettingsChanged; virtual; abstract; procedure Settings; virtual; abstract; function GetInfo :TCJ_PluginInfo; virtual; abstract; end; Tfunction_GetPlugin = function :TCJ_Plugin; stdcall; Tfunction_GetPluginInfo = function :TCJ_PluginInfo; stdcall; implementation end.
unit FFSList; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FFSTypes; type TFFSListItemClickEvent = procedure(Sender: TObject; ItemIndex:integer) of object; TFFSListGroupClickEvent = procedure(Sender: TObject; GroupName:string) of object; // TRangeList TFFSList = class(TCustomControl) private Groups : set of 0..255; Items : set of 0..255; FActiveCell: integer; FOnGroupClick: TFFSListGroupClickEvent; FOnItemClick: TFFSListItemClickEvent; procedure SetActiveCell(const Value: integer); procedure SetOnGroupClick(const Value: TFFSListGroupClickEvent); procedure SetOnItemClick(const Value: TFFSListItemClickEvent); procedure MapList; private { Private declarations } FItemStringList: TStringList; procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure WMLButtonDblClk(var Message: TMessage); message WM_LBUTTONDBLCLK; procedure DrawCell(n: integer); function CellHeight:integer; function CellCount:integer; function MouseToCell(y: smallint): integer; property ActiveCell:integer read FActiveCell write SetActiveCell; function GroupName(AnIndex:integer):string; function ItemName(AnIndex:integer):string; function ItemIndex(AnIndex:integer):integer; function GetFFSItemCount: integer; protected { Protected declarations } procedure Paint;override; public { Public declarations } constructor create(AOwner:TComponent);override; destructor Destroy;override; procedure Clear; procedure AddItem(AGroup, ADescription: string; AValue:integer); property Count:integer read GetFFSItemCount; published { Published declarations } property Align; property Font; property OnItemClick:TFFSListItemClickEvent read FOnItemClick write SetOnItemClick; property OnGroupClick:TFFSListGroupClickEvent read FOnGroupClick write SetOnGroupClick; end; procedure Register; implementation const HeightBuffer = 6; procedure Register; begin RegisterComponents('FFS Controls', [TFFSList]); end; { TFFSList } procedure TFFSList.AddItem(AGroup, ADescription: string; AValue:integer); var x : integer; gs : string; begin gs := '~~' + AGroup; x := FItemStringList.IndexOf(gs); if x < 0 then begin FItemStringList.Add(gs); x := FItemStringList.IndexOf(gs); end; FItemStringList.Insert(x+1, ADescription+'~*~'+inttostr(AValue)); Invalidate; end; procedure TFFSList.Clear; begin FItemStringList.Clear; InValidate; end; constructor TFFSList.create(AOwner: TComponent); begin inherited; FItemStringList := TStringList.create; Height := 80; Width := 200; Clear; Cursor := crHandPoint; FActiveCell := -1; end; destructor TFFSList.Destroy; begin FItemStringList.Free; inherited; end; procedure TFFSList.MsgFFSColorChange(var Msg: TMessage); begin invalidate; end; procedure TFFSList.DrawCell(n: integer); var r : TRect; begin if (n < 0) or (n >= CellCount) then exit; r := GetClientRect; r.Top := n * CellHeight; r.Bottom := r.top + CellHeight; if n = FActiveCell then canvas.brush.Color := FFSColor[fcsListRollover] else canvas.brush.Color := FFSColor[fcsListBackGround]; canvas.FillRect(r); if n in Groups then begin canvas.font.Style := canvas.Font.Style + [fsBold]; canvas.TextRect(r, 4, r.top + (HeightBuffer div 2) - 1, GroupName(n)); end else begin canvas.Font.Style := Canvas.Font.Style - [fsBold]; canvas.TextRect(r, 8, r.top + (HeightBuffer div 2) - 1, ItemName(n)); end; end; procedure TFFSList.Paint; var r,r2 : TRect; x : integer; begin MapList; Canvas.brush.Color := FFSColor[fcsListBackGround]; r := GetClientRect; canvas.FillRect(r); for x := 0 to CellCount-1 do DrawCell(x); end; function TFFSList.CellHeight: integer; var fh : integer; begin fh := font.Height; if fh < 0 then fh := fh * -1; inc(fh,HeightBuffer); result := fh; end; procedure TFFSList.MapList; var x : integer; begin Groups := []; Items := []; for x := 0 to CellCount - 1 do begin if copy(FItemStringList[x],1,2) = '~~' then Groups := Groups + [x] else Items := Items + [x]; end; end; procedure TFFSList.WMLButtonDown(var Message: TWMLButtonDown); begin end; procedure TFFSList.WMLButtonUp(var Message: TWMLButtonUp); begin if (FActiveCell >= 0) and (FActiveCell < CellCount) then begin if (FActiveCell in Groups) and (assigned(OnGroupClick)) then OnGroupClick(self, GroupName(FActiveCell)); if (FActiveCell in Items) and (assigned(OnItemClick)) then OnItemClick(self, ItemIndex(FActiveCell)); end; end; function TFFSList.MouseToCell(y:SmallInt):integer; begin result := y div CellHeight; end; procedure TFFSList.WMMouseMove(var Message: TWMMouseMove); var ac : integer; begin ac := MouseToCell(Message.YPos); ActiveCell := ac; end; function TFFSList.CellCount: integer; begin result := FItemStringList.Count; end; procedure TFFSList.SetActiveCell(const Value: integer); var oldactive : integer; nv : integer; begin if (Value < 0) or (value >= CellCount) then nv := -1 else nv := value; if nv <> FActiveCell then begin oldactive := FActiveCell; FActiveCell := nv; DrawCell(OldActive); DrawCell(FActiveCell); end; end; procedure TFFSList.CMMouseLeave(var Message: TMessage); begin ActiveCell := -1; end; procedure TFFSList.SetOnGroupClick(const Value: TFFSListGroupClickEvent); begin FOnGroupClick := Value; end; procedure TFFSList.SetOnItemClick(const Value: TFFSListItemClickEvent); begin FOnItemClick := Value; end; function TFFSList.GroupName(AnIndex: integer): string; var s : string; begin result := ''; if not (AnIndex in Groups) then exit; s := FItemStringList[AnIndex]; result := copy(s, 3, length(s)-2); end; function TFFSList.ItemIndex(AnIndex: integer): integer; var p : integer; s : string; begin result := -1; if not (AnIndex in Items) then exit; s := FItemStringList[AnIndex]; p := pos('~*~', s); s := copy(s, p+3, length(s)); result := strtointdef(s,-1); end; function TFFSList.ItemName(AnIndex: integer): string; var p : integer; s : string; begin result := ''; if not (AnIndex in Items) then exit; s := FItemStringList[AnIndex]; p := pos('~*~', s); result := copy(s, 1, p-1); end; procedure TFFSList.WMLButtonDblClk(var Message: TMessage); begin Message.Result := 0; end; function TFFSList.GetFFSItemCount: integer; begin result := FItemStringList.Count; end; end.
PROGRAM Mortgage(Input, Output); { This program computes the monthly installments of a mortgage loan over a number of years. Ph. Gabrini November 1991 } Var Loan, AnnualRate, MonthlyRate, Payment, MonthlyInterest, Interests, Balance: REAL; Years, Months: Integer; Answer: CHAR; {******************************************************} PROCEDURE GetLoanData(Var Amount, InterestRate: REAL; Var Duration: Integer); { Get loan amount (from 10,000 to 500,000), annual interest rate (from 3% to 20%), and loan duration (from 1 year to 35 years) } Begin Write('Amount of mortgage loan: '); REPEAT Readln(Amount); Writeln; IF (Amount < 10000.0) OR (Amount > 500000.0) THEN Write('Amount either too large or too small, please re-enter: '); UNTIL (Amount >= 10000) AND (Amount <= 500000.0); Write('Annual interest rate: '); REPEAT Readln(InterestRate); Writeln; IF (InterestRate > 20.0) OR (InterestRate < 3.0) THEN Write('Impossible rate, please reenter: ') UNTIL (InterestRate >= 3.0) AND (InterestRate <= 20.0); Write('Length of mortgage loan (in years): '); REPEAT Readln(Duration); Writeln; IF (Duration <1) OR (Duration > 35) THEN Write('Invalid length, please reenter: ') UNTIL (Duration >= 1) AND (Duration <= 35); End; {GetLoanData} {******************************************************} FUNCTION Power(Number: REAL; Exponent: Integer): REAL; { Compute Number to the Exponent power } Var Index: Integer; Result: REAL; Begin Result := 1.0; FOR Index := 1 TO Exponent DO Result := Result * Number; Power := Result; End; {Power} {******************************************************} PROCEDURE ComputeMonthlyPayment(Amount, Rate: REAL; Length: Integer; Var Payment, MonthRate: REAL); { Given an Amount, an annual interest Rate and a loan Length in months compute the monthly interest rate and the monthly payment } Var Coefficient: REAL; Begin MonthRate := EXP(LN(1.0 + 0.01 * Rate / 2.0) / 6.0) - 1.0; Coefficient := Power(1.0 + MonthRate, Length); Payment := MonthRate * Loan * (Coefficient / (Coefficient - 1.0)) End; {ComputeMonthlyPayment} {******************************************************} PROCEDURE ComputeCostOfLoan(Balance, MonthRate: REAL; Period: Integer; Var Interests: REAL; Report: BOOLEAN); { Given a loan Balance, the monthly interest rate, the length of the loan in months, compute the interests paid and generate a detailed report if requested. } Var Index: Integer; MonthInterest, Reduction: REAL; Begin IF Report THEN Writeln(' Payment# Interest Capital', ' Cum. Int. Balance'); FOR Index := 1 TO Period DO Begin MonthInterest := MonthRate * Balance; Interests := Interests + MonthInterest; Reduction := Payment - MonthInterest; Balance := Balance - Reduction; IF Balance < 0.0 THEN Balance := 0.0; IF Report AND (Index <= 60) THEN Writeln(' ', Index:3, MonthInterest:13:2, Reduction:12:2, Interests:15:2, Balance:15:2); IF Index = 60 THEN Begin Writeln('Interest paid in 5 years: ', Interests:15:2); Writeln('Balance after 5 years: ', Balance:15:2); End { IF } End { FOR } End; {ComputeCostOfLoan} {******************************************************} Begin { program } REPEAT GetLoanData(Loan, AnnualRate, Years); Months := 12 * Years; ComputeMonthlyPayment(Loan, AnnualRate, Months, Payment, MonthlyRate); Writeln('Monthly payment: ', Payment:9:2); Write('Do you want a detailed report? '); Readln(Answer); Writeln; Balance := Loan; Interests := 0.0; ComputeCostOfLoan(Balance, MonthlyRate, Months, Interests, Answer in ['y', 'Y']); Writeln('Total cost of mortgage loan: ', Interests:15:2); Writeln; Write('Do you want another loan computation? '); Readln(Answer); Writeln; UNTIL Answer in ['n', 'N']; End.
// the code formatter expert as a regular expert // Original Author: Thomas Mueller (http://blog.dummzeuch.de) unit GX_Formatter; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, GX_GenericUtils, GX_Experts, GX_CodeFormatterExpert, GX_ConfigurationInfo; type TGxCodeFormatterExpert = class(TGX_Expert) private FExpert: TCodeFormatterExpert; protected procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public constructor Create; override; destructor Destroy; override; procedure Execute(Sender: TObject); override; procedure Configure; override; function GetDefaultShortCut: TShortCut; override; function GetActionCaption: string; override; class function GetName: string; override; function HasConfigOptions: Boolean; override; function HasMenuItem: Boolean; override; end; implementation uses {$IFOPT D+}GX_DbugIntf, {$ENDIF} Menus, GX_GExperts, GX_About; { TCodeFormatterExpert } procedure TGxCodeFormatterExpert.Execute(Sender: TObject); begin FExpert.Execute; end; procedure TGxCodeFormatterExpert.Configure; begin FExpert.Configure; end; constructor TGxCodeFormatterExpert.Create; begin inherited Create; FExpert := TCodeFormatterExpert.Create; end; destructor TGxCodeFormatterExpert.Destroy; begin FreeAndNil(FExpert); inherited; end; function TGxCodeFormatterExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Code &Formatter'; begin Result := SMenuCaption; end; function TGxCodeFormatterExpert.GetDefaultShortCut: TShortCut; begin Result := Menus.ShortCut(Word('F'), [ssCtrl, ssAlt]); end; class function TGxCodeFormatterExpert.GetName: string; begin Result := 'CodeFormatter'; end; function TGxCodeFormatterExpert.HasConfigOptions: Boolean; begin Result := True; end; function TGxCodeFormatterExpert.HasMenuItem: Boolean; begin Result := True; end; procedure TGxCodeFormatterExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited; FExpert.InternalLoadSettings(Settings); end; procedure TGxCodeFormatterExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited; FExpert.InternalSaveSettings(Settings); end; function FormatFile(_FileName: PChar): Boolean; {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} var FormatterStandAlone: TGxCodeFormatterExpert; begin Result := false; InitSharedResources; try try FormatterStandAlone := TGxCodeFormatterExpert.Create; try FormatterStandAlone.LoadSettings; Result := FormatterStandAlone.FExpert.FormatFile(_FileName); FormatterStandAlone.SaveSettings; finally FormatterStandAlone.Free; end; except on E: Exception do begin GxLogAndShowException(E, e.Message); end; end; finally FreeSharedResources; end; end; { This is a simple implementation. It originally TStrings.StrictDelimiter was used but that only exists in Delphi 2006 and up. } procedure SplitStr(_InStr: string; _Delimiter: char; _sl: TStrings); var Start: integer; i: Integer; begin Assert(Assigned(_sl)); _InStr := _InStr + ';'; _sl.Clear; Start := 1; for i := 1 to Length(_InStr) do begin if _InStr[i] = _Delimiter then begin _sl.Add(Copy(_InStr, Start, i - Start)); Start := i + 1; end; end; end; procedure FormatFiles(AFileNames: PChar); {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} var FormatterStandAlone: TGxCodeFormatterExpert; FileList: TStringList; i: Integer; begin InitSharedResources; try try FormatterStandAlone := TGxCodeFormatterExpert.Create; try FormatterStandAlone.LoadSettings; FileList := TStringList.Create; try SplitStr(AFileNames, ';', FileList); for i := 0 to Pred(FileList.Count) do FormatterStandAlone.FExpert.FormatFile(FileList[i]); finally FileList.Free; end; FormatterStandAlone.SaveSettings; finally FormatterStandAlone.Free; end; except on E: Exception do begin GxLogAndShowException(E, e.Message); end; end; finally FreeSharedResources; end; end; procedure ConfigureFormatter(); {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} var FormatterStandAlone: TGxCodeFormatterExpert; begin InitSharedResources; try try FormatterStandAlone := TGxCodeFormatterExpert.Create; try FormatterStandAlone.LoadSettings; FormatterStandAlone.Configure; FormatterStandAlone.SaveSettings; finally FormatterStandAlone.Free; end; except on E: Exception do begin GxLogAndShowException(E, e.Message); end; end; finally FreeSharedResources; end; end; procedure AboutFormatter(); {$IFNDEF GX_BCB} export; {$ENDIF GX_BCB} var frm: TfmAbout; begin InitSharedResources; try try frm := gblAboutFormClass.Create(nil); try frm.ShowModal; finally frm.Free; end; except on E: Exception do begin GxLogAndShowException(E, e.Message); end; end; finally FreeSharedResources; end; end; exports FormatFile, FormatFiles, ConfigureFormatter, AboutFormatter; 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.12 2/23/2005 6:34:28 PM JPMugaas New property for displaying permissions ina GUI column. Note that this should not be used like a CHMOD because permissions are different on different platforms - you have been warned. Rev 1.11 10/26/2004 10:03:22 PM JPMugaas Updated refs. Rev 1.10 7/31/2004 1:08:24 PM JPMugaas Now should handle listings without time. Rev 1.9 6/21/2004 10:57:42 AM JPMugaas Now indicates that ModifiedDate and File Size are not available if VMS returns an error in the entry. Rev 1.8 6/11/2004 9:35:08 AM DSiders Added "Do not Localize" comments. Rev 1.7 6/7/2004 3:47:48 PM JPMugaas VMS Recursive Dir listings now supported. This is done with a [...]. Note that VMS does have some strange syntaxes with their file system. Rev 1.6 4/20/2004 4:01:16 PM JPMugaas Fix for nasty typecasting error. The wrong create was being called. Rev 1.5 4/19/2004 5:05:18 PM JPMugaas Class rework Kudzu wanted. Rev 1.4 2004.02.03 5:45:16 PM czhower Name changes Rev 1.3 10/19/2003 3:48:12 PM DSiders Added localization comments. Rev 1.2 10/1/2003 12:53:08 AM JPMugaas Indicated that VMS returns block sizes. Note that in VMS, the traditional block size is 512 bytes (this is a fixed constant). Rev 1.1 4/7/2003 04:04:36 PM JPMugaas User can now descover what output a parser may give. Rev 1.0 2/19/2003 02:01:58 AM JPMugaas Individual parsing objects for the new framework. } unit IdFTPListParseVMS; { This parser works with VMS (OpenVMS) systems including UCX, MadGoat, Multinet, VMS TCPWare, plus some non-multinet systems. } interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdVMSFTPListItem = class(TIdOwnerFTPListItem) protected FGroupName : String; FVMSOwnerPermissions: String; FVMSWorldPermissions: String; FVMSSystemPermissions: String; FVMSGroupPermissions: String; FNumberBlocks : Integer; FBlockSize : Integer; FVersion : Integer; public property GroupName : String read FGroupName write FGroupName; //VMS File Protections //These are different than Unix. See: //See http://www.djesys.com/vms/freevms/mentor/vms_prot.html#prvs property VMSSystemPermissions : String read FVMSSystemPermissions write FVMSSystemPermissions; property VMSOwnerPermissions : String read FVMSOwnerPermissions write FVMSOwnerPermissions; property VMSGroupPermissions : String read FVMSGroupPermissions write FVMSGroupPermissions; property VMSWorldPermissions : String read FVMSWorldPermissions write FVMSWorldPermissions; property Version : Integer read FVersion write FVersion; property NumberBlocks : Integer read FNumberBlocks write FNumberBlocks; property BlockSize : Integer read FBlockSize write FBlockSize; end; TIdFTPLPVMS = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsVMSHeader(const AData: String): Boolean; class function IsVMSFooter(const AData: String): Boolean; class function IsContinuedLine(const AData: String): Boolean; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; class function ParseListing(AListing : TStrings; ADir : TIdFTPListItems) : Boolean; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseVMS"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils; { TIdFTPLPVMS } class function TIdFTPLPVMS.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var LData : String; i : Integer; begin Result := False; for i := 0 to AListing.Count - 1 do begin if AListing[i] <> '' then begin LData := AListing[i]; Result := Length(LData) > 1; if Result then begin Result := IsVMSHeader(LData); //see if file listing starts a file name if not Result then begin LData := Fetch(LData); Fetch(LData, ';'); {do not localize} Result := IsNumeric(LData); end; end; Break; end; end; end; class function TIdFTPLPVMS.GetIdent: String; begin Result := 'VMS'; {do not localize} end; class function TIdFTPLPVMS.IsContinuedLine(const AData: String): Boolean; begin Result := TextStartsWith(AData, ' ') and (IndyPos(';', AData) = 0); {do not localize} end; class function TIdFTPLPVMS.IsVMSFooter(const AData: String): Boolean; var LData : String; begin //The bottum banner may be in the following forms: //Total of 1 file, 0 blocks. //Total of 6 Files, 1582 Blocks. //Total of 90 files. //Grand total of 87 directories, 2593 files, 2220036 blocks. //*.*; <%RMS-E-FNF, file not found> //VMS returns TOTAL at the end. We test for " files" at the end of the line //so we don't break something with another parser. LData := UpperCase(AData); Result := TextStartsWith(LData, 'TOTAL OF ') or {do not localize} TextStartsWith(LData, 'GRAND TOTAL OF '); {do not localize} if Result then begin Result := (IndyPos(' FILE', LData) > 9); {do not localize} if not Result then begin Result := Fetch(LData) = '*.*;'; {do not localize} end; end; end; class function TIdFTPLPVMS.IsVMSHeader(const AData: String): Boolean; begin Result := TextEndsWith(AData, ']') and {Do not localize} (IndyPos(':[', AData) > 0); {Do not localize} end; class function TIdFTPLPVMS.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdVMSFTPListItem.Create(AOwner); end; class function TIdFTPLPVMS.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuffer, LBuf2, LLine : String; LDay, LMonth, LYear : Integer; //LHour, LMinute, LSec : Integer; LCols : TStrings; LOwnerIdx : Integer; LVMSError : Boolean; LI : TIdVMSFTPListItem; begin { 1 2 3 4 5 6 1234567890123456789012345678901234567890123456789012345678901234567890 BILF.C;2 13 5-JUL-1991 12:00 [1,1] (RWED,RWED,RE,RE) and non-MutliNet VMS: CII-MANUAL.TEX;1 213/216 29-JAN-1996 03:33:12 [ANONYMOU,ANONYMOUS] (RWED,RWED,,) or possibly VMS TCPware V5.5-3 .WELCOME;1 2 13-FEB-2002 23:32:40.47 } LI := AItem as TIdVMSFTPListItem; LVMSError := False; LLine := LI.Data; // Charon VAX 5.4.2 uses tabs between some of its columns and spaces between others LLine := StringReplace(LLine, #9, ' ', [rfReplaceAll]); //File Name //We do this in a roundabout way because spaces in VMS files may actually //be legal and that throws of a typical non-position based column parser. //this assumes that the file contains a ";". In VMS, this separates the name //from the version number. LBuffer := Fetch(LLine, ';'); {do not localize} LI.LocalFileName := LowerCase(LBuffer); LBuf2 := Fetch(LLine); //Some FTP servers might follow the filename with a tab and than //give an error such as this: //1KBTEST.PTF;10#9No privilege for attempted operation LI.Version := IndyStrToInt(LBuf2, 0); LBuffer := LBuffer + ';' + LBuf2; {do not localize} //Dirs have to be processed differently then //files because a version mark and .DIR exctension //are not used to CWD into a subdir although they are //listed in a dir listed. if (IndyPos('.DIR;', LBuffer) > 0) then {do not localize} begin AItem.ItemType := ditDirectory; //note that you can NOT simply do a Fetch('.') to extract the dir name //you use with a CD because the period is also a separator between pathes // //e.g. // //[VMSSERV.FILES]ALARM.DIR;1 1/3 5-MAR-1993 18:09 if IndyPos(PATH_FILENAME_SEP_VMS, LBuffer) = 0 then begin LBuf2 := ''; end else begin LBuf2 := Fetch(LBuffer, PATH_FILENAME_SEP_VMS) + PATH_FILENAME_SEP_VMS; {Do not localize} end; AItem.FileName := LBuf2 + Fetch(LBuffer, '.'); {do not localize} AItem.LocalFileName := LowerCase(AItem.FileName); end else begin AItem.ItemType := ditFile; AItem.FileName := LBuffer; end; if APath <> '' then begin AItem.FileName := APath + AItem.FileName; end; LCols := TStringList.Create; try SplitColumns(LLine, LCols); LOwnerIdx := 3; //if this isn't numeric, there may be an error that is //is reported in the File list. Do not parse the line further. if LCols.Count > 0 then begin LBuffer := LCols[0]; LBuffer := Fetch(LBuffer, '/'); if IsNumeric(LBuffer) then begin //File Size LI.NumberBlocks := IndyStrToInt(LBuffer, 0); LI.BlockSize := VMS_BLOCK_SIZE; LI.Size := IndyStrToInt64(LBuffer, 0) * VMS_BLOCK_SIZE; //512 is the size of a VMS block end else begin //on the UCX VMS server, the file size might not be reported. Probably the file owner if not TextStartsWith(LCols[0], '[') then {do not localize} begin if not IsNumeric(LCols[0], 1, 1) then begin //the server probably reported an error in the FTP list such as no permission //we need to stop right there. LVMSError := True; AItem.SizeAvail := False; AItem.ModifiedAvail := False; end; end else begin LOwnerIdx := 0; end; end; if not LVMSError then begin if LOwnerIdx > 0 then begin //Date if LCols.Count > 1 then begin LBuffer := LCols[1]; LDay := IndyStrToInt(Fetch(LBuffer, '-'), 1); {do not localize} LMonth := StrToMonth(Fetch(LBuffer, '-')); {do not localize} LYear := IndyStrToInt(Fetch(LBuffer), 1989); LI.ModifiedDate := EncodeDate(LYear, LMonth, LDay); end; //Time if LCols.Count > 2 then begin //Modified Time of Day //Some dir listings might be missing the time //such as this: // //vms_dir_2.DIR;1 1 19-NOV-2001 [root,root] (RWE,RWE,RE,RE) if IndyPos(':', LCols[2]) = 0 then begin {do not localize} Dec(LOwnerIdx); end else begin LI.ModifiedDate := AItem.ModifiedDate + TimeHHMMSS(LCols[2]); end; end; end; //Owner/Group //This is in the order of Group/Owner //See: // http://seqaxp.bio.caltech.edu/www/vms_beginners_faq.html#FILE00 if LCols.Count > LOwnerIdx then begin LBuffer := LCols[LOwnerIdx]; Fetch(LBuffer, '['); {do not localize} LBuffer := Fetch(LBuffer,']'); LI.GroupName := Trim(Fetch(LBuffer, ',')); {do not localize} LI.OwnerName := Trim(LBuffer); {do not localize} end; //Protections if LCols.Count > (LOwnerIdx+1) then begin LBuffer := LCols[LOwnerIdx+1]; Fetch(LBuffer, '('); {do not localize} LBuffer := Fetch(LBuffer, ')'); {do not localize} LI.PermissionDisplay := '(' + LBuffer + ')'; {do not localize} LI.VMSSystemPermissions := Trim(Fetch(LBuffer, ',')); {do not localize} LI.VMSOwnerPermissions := Trim(Fetch(LBuffer, ',')); {do not localize} LI.VMSGroupPermissions := Trim(Fetch(LBuffer, ',')); {do not localize} LI.VMSWorldPermissions := Trim(LBuffer); end; end; end; finally FreeAndNil(LCols); end; Result := True; end; class function TIdFTPLPVMS.ParseListing(AListing: TStrings; ADir: TIdFTPListItems): Boolean; var i : Integer; LItem : TIdFTPListItem; LStartLine, LEndLine : Integer; LRootPath : String; //needed for recursive dir listings "DIR [...]" LRelPath : String; begin { VMS is really a ball because the listing can start and end with blank lines as well as a begging and ending banner } LStartLine := 0; LRelPath := ''; LEndLine := AListing.Count-1; for i := 0 to LEndLine do begin if IsWhiteString(AListing[i]) then begin Inc(LStartLine); end else begin if IsVMSHeader(AListing[i]) then begin LRootPath := AListing[i]; //to make things easy, we will only use entire banner for deteriming a subdir //such as this: // //Directory ANONYMOUS_ROOT:[000000.VMS-FREEWARE.NARNIA] // if //Directory ANONYMOUS_ROOT:[000000.VMS-FREEWARE.NARNIA.COM] // then result = [.COM] LRootPath := Fetch(LRootPath, PATH_FILENAME_SEP_VMS) + '.'; {do not localize} Inc(LStartLine); end; Break; end; end; //find the end of our parsing for i := LEndLine downto LStartLine do begin if IsWhiteString(AListing[i]) or IsVMSFooter(AListing[i]) then begin Dec(LEndLine); end else begin Break; end; end; for i := LStartLine to LEndLine do begin if not IsWhiteString(AListing[i]) then begin if IsVMSHeader(AListing[i]) then begin //+1 is used because there's a period that we are dropping and then adding back LRelPath := Copy(AListing[i], Length(LRootPath)+1, MaxInt); LRelPath := VMS_RELPATH_PREFIX + LRelPath; end else if not IsContinuedLine(AListing[i]) then //needed because some VMS computers return entries with multiple lines begin LItem := MakeNewItem(ADir); LItem.Data := UnfoldLines(AListing[i], i, AListing); Result := ParseLine(LItem, LRelPath); if not Result then begin FreeAndNil(LItem); Exit; end; end; end; end; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPVMS); finalization UnRegisterFTPListParser(TIdFTPLPVMS); end.
unit clFinanceiroEmpresa; interface uses clConexao, Vcl.Dialogs, System.SysUtils, clBancos; type TFinanceiroEmpresa = class(TObject) protected FConta: String; FAgencia: String; FBanco: String; FTipoConta: String; FSequencia: Integer; FEmpresa: Integer; FPadrao: String; FForma: String; FCNPJ: String; FFavorecido: String; conexao: TConexao; bancos: TBancos; private procedure SetEmpresa(val: Integer); procedure SetSequencia(val: Integer); procedure SetTipoConta(val: String); procedure SetBanco(val: String); procedure SetAgencia(val: String); procedure SetConta(val: String); procedure SetFavorecido(val: String); procedure SetCNPJ(val: String); procedure SetForma(val: String); procedure SetPadrao(val: String); public constructor Create; property Empresa: Integer read FEmpresa write SetEmpresa; property Sequencia: Integer read FSequencia write SetSequencia; property TipoConta: String read FTipoConta write SetTipoConta; property Banco: String read FBanco write SetBanco; property Agencia: String read FAgencia write SetAgencia; property Conta: String read FConta write SetConta; property Favorecido: String read FFavorecido write SetFavorecido; property CNPJ: String read FCNPJ write SetCNPJ; property Forma: String read FForma write SetForma; property Padrao: String read FPadrao write SetPadrao; procedure MaxSeq; function Validar: Boolean; function Insert: Boolean; function Update: Boolean; function Delete(sFiltro: String): Boolean; function getObject(sId: String; sFiltro: String): Boolean; function getObjects: Boolean; function getField(sCampo: String; sColuna: String): String; destructor Destroy; override; end; const TABLENAME = 'CAD_FINANCEIRO_EMPRESA'; implementation uses udm, clUtil; constructor TFinanceiroEmpresa.Create; begin inherited Create; conexao := TConexao.Create; bancos := TBancos.Create; end; procedure TFinanceiroEmpresa.SetEmpresa(val: Integer); begin FEmpresa := val; end; procedure TFinanceiroEmpresa.SetSequencia(val: Integer); begin FSequencia := val; end; procedure TFinanceiroEmpresa.SetTipoConta(val: String); begin FTipoConta := val; end; procedure TFinanceiroEmpresa.SetBanco(val: String); begin FBanco := val; end; procedure TFinanceiroEmpresa.SetAgencia(val: String); begin FAgencia := val; end; procedure TFinanceiroEmpresa.SetConta(val: String); begin FConta := val; end; procedure TFinanceiroEmpresa.SetFavorecido(val: String); begin FFavorecido := val; end; procedure TFinanceiroEmpresa.SetCNPJ(val: String); begin FCNPJ := val; end; procedure TFinanceiroEmpresa.SetForma(val: String); begin FForma := val; end; procedure TFinanceiroEmpresa.SetPadrao(val: String); begin FPadrao := val; end; procedure TFinanceiroEmpresa.MaxSeq; begin try if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(SEQ_FINANCEIRO) AS SEQUENCIA FROM ' + TABLENAME + ' WHERE COD_ENTREGADOR = :CODIGO'; ParamByName('CODIGO').AsString := IntToStr(Self.Empresa); dm.ZConn.PingServer; Open; if not(IsEmpty) then begin First; end; end; Self.Sequencia := (dm.QryGetObject.FieldByName('SEQUENCIA').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TFinanceiroEmpresa.Validar: Boolean; begin Result := False; if Self.Empresa = 0 then begin MessageDlg('Código de Empresa inválido!',mtWarning,[mbCancel],0); Exit; end; if Self.Sequencia = 0 then begin MessageDlg('Sequência inválida!',mtWarning,[mbCancel],0); Exit; end; if Self.TipoConta.IsEmpty then begin MessageDlg('Informe o Tipo de Conta!',mtWarning,[mbCancel],0); Exit; end; if Self.Banco.IsEmpty then begin MessageDlg('Informe o Banco da Conta!',mtWarning,[mbCancel],0); Exit; end else begin if Self.Bancos.getObject(Self.Banco,'CODIGO') then begin MessageDlg('Banco não cadastrado!',mtWarning,[mbCancel],0); dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; Exit; end; dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; end; if Self.Agencia.IsEmpty then begin MessageDlg('Informe a Agência do Banco!',mtWarning,[mbCancel],0); Exit; end; if Self.Conta.IsEmpty then begin MessageDlg('Informe o Número da Conta!',mtWarning,[mbCancel],0); Exit; end; if Self.Favorecido.IsEmpty then begin MessageDlg('Informe o Nome do Favorecido!',mtWarning,[mbCancel],0); Exit; end; if Self.CNPJ.IsEmpty then begin MessageDlg('Informe o CPF ou CNPJ do Favorecido!',mtWarning,[mbCancel],0); Exit; end else begin if (not TUtil.CPF(Self.CNPJ)) then begin if (not TUtil.CNPJ(Self.CNPJ)) then begin MessageDlg('CPF ou CNPJ do Favorecido inválido!',mtWarning,[mbCancel],0); Exit; end; end; end; Result := True; end; function TFinanceiroEmpresa.Insert: Boolean; begin Try Result := False; MaxSeq; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_EMPRESA, ' + 'SEQ_FINANCEIRO, ' + 'DES_TIPO_CONTA, ' + 'COD_BANCO, ' + 'COD_AGENCIA, ' + 'NUM_CONTA, ' + 'NOM_FAVORECIDO, ' + 'NUM_CPF_CNPJ, ' + 'DES_FORMA_PAGAMENTO, ' + 'DOM_PADRAO) ' + 'VALUES (' + ':CODIGO, ' + ':SEQUENCIA, ' + ':TIPOCONTA, ' + ':BANCO, ' + ':AGENCIA, ' + ':CONTA, ' + ':FAVORECIDO, ' + ':CPFCNPJ, ' + ':FORMA, ' + ':PADRAO)'; ParamByName('CODIGO').AsInteger :=Self.Empresa; ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; ParamByName('TIPOCONTA').AsString := Self.TipoConta; ParamByName('BANCO').AsString := Self.Banco; ParamByName('AGENCIA').AsString := Self.Agencia; ParamByName('CONTA').AsString := Self.Conta; ParamByName('FAVORECIDO').AsString := Self.Favorecido; ParamByName('CPFCNPJ').AsString := Self.CNPJ; ParamByName('FORMA').AsString := Self.Forma; ParamByName('PADRAO').AsString := Self.Padrao; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TFinanceiroEmpresa.Update: Boolean; begin try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_TIPO_CONTA = :TIPOCONTA, ' + 'COD_BANCO = :BANCO, ' + 'COD_AGENCIA = :AGENCIA, ' + 'NUM_CONTA = :CONTA, ' + 'NOM_FAVORECIDO = :FAVORECIDO, ' + 'NUM_CPF_CNPJ = :CPFCNPJ, ' + 'DES_FORMA_PAGAMENTO = :FORMA, ' + 'DOM_PADRAO = :PADRAO ' + 'WHERE COD_EMPRESA = :CODIGO AND SEQ_FINANCEIRO = :SEQUENCIA'; ParamByName('CODIGO').AsInteger :=Self.Empresa; ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; ParamByName('TIPOCONTA').AsString := Self.TipoConta; ParamByName('BANCO').AsString := Self.Banco; ParamByName('AGENCIA').AsString := Self.Agencia; ParamByName('CONTA').AsString := Self.Conta; ParamByName('FAVORECIDO').AsString := Self.Favorecido; ParamByName('CPFCNPJ').AsString := Self.CNPJ; ParamByName('FORMA').AsString := Self.Forma; ParamByName('PADRAO').AsString := Self.Padrao; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TFinanceiroEmpresa.Delete(sFiltro: String): Boolean; begin Try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if sFiltro.IsEmpty then begin Exit; end; with dm.qryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin SQL.Add(' WHERE COD_EMPRESA = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Empresa; end else if sFiltro = 'SEQUENCIA' then begin SQL.Add(' WHERE COD_EMPRESA = :CODIGO AND SEQ_FINANCEIRO = :SEQUENCIA'); ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; end else if sFiltro = 'CNPJ' then begin SQL.Add(' WHERE NUM_CPF_CNPJ = :CPFCNPJ'); ParamByName('CPFCNPJ').AsString := Self.CNPJ; end else if sFiltro = 'BANCO' then begin SQL.Add(' WHERE COD_BANCO = :BANCO'); ParamByName('BANCO').AsString := Self.Banco; end else if sFiltro = 'TIPO' then begin SQL.Add(' WHERE DES_TIPO_CONTA = :TIPO'); ParamByName('TIPO').AsString := Self.TipoConta; end else if sFiltro = 'NOME' then begin SQL.Add(' WHERE NOM_FAVORECIDO = :NOME'); ParamByName('NOME').AsString := Self.Favorecido; end; dm.ZConn.PingServer; ExecSQL; Close; SQL.Clear; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TFinanceiroEmpresa.getObject(sId: String; sFiltro: String): Boolean; begin Try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if sId.IsEmpty then begin Exit; end; if sFiltro.IsEmpty then begin Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if sFiltro = 'CODIGO' then begin SQL.Add(' WHERE COD_EMPRESA = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(sId); end else if sFiltro = 'SEQUENCIA' then begin SQL.Add(' WHERE COD_EMPRESA = :CODIGO AND SEQ_FINANCEIRO = :SEQUENCIA'); ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('SEQUENCIA').AsInteger := StrToInt(sId); end else if sFiltro = 'CNPJ' then begin SQL.Add(' WHERE NUM_CPF_CNPJ = :CPFCNPJ'); ParamByName('CPFCNPJ').AsString := sId; end else if sFiltro = 'BANCO' then begin SQL.Add(' WHERE COD_BANCO = :BANCO'); ParamByName('BANCO').AsString := sId; end else if sFiltro = 'TIPO' then begin SQL.Add(' WHERE DES_TIPO_CONTA = :TIPO'); ParamByName('TIPO').AsString := sId; end else if sFiltro = 'NOME' then begin SQL.Add(' WHERE NOM_FAVORECIDO LIKE :NOME'); ParamByName('NOME').AsString := QuotedStr('%' + sId + '%'); end; dm.ZConn.PingServer; Open; if not IsEmpty then begin First; Self.Empresa := FieldByName('COD_EMPRESA').AsInteger; Self.Sequencia := FieldByName('SEQ_FINANCEIRO').AsInteger; Self.TipoConta := FieldByName('DES_TIPO_CONTA').AsString; Self.Banco := FieldByName('COD_BANCO').AsString; Self.Agencia := FieldByName('COD_AGENCIA').AsString; Self.Conta := FieldByName('NUM_CONTA').AsString; Self.Favorecido := FieldByName('NOM_FAVORECIDO').AsString; Self.CNPJ := FieldByName('NUM_CPF_CNPJ').AsString; Self.Forma := FieldByName('DES_FORMA_PAGAMENTO').AsString; Self.Padrao := FieldByName('DOM_PADRAO').AsString; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TFinanceiroEmpresa.getObjects: Boolean; begin Try Result := False; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then begin First; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TFinanceiroEmpresa.getField(sCampo: String; sColuna: String): String; begin Try Result := ''; if (not conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0); Exit; end; if sCampo.IsEmpty then begin Exit; end; if sColuna.IsEmpty then begin Exit; end; with dm.qryFields do begin Close; SQL.Clear; SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME); if sColuna = 'CODIGO' then begin SQL.Add(' WHERE COD_EMPRESA = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Empresa; end else if sColuna = 'SEQUENCIA' then begin SQL.Add(' WHERE COD_EMPRESA = :CODIGO AND SEQ_FINANCEIRO = :SEQUENCIA'); ParamByName('CODIGO').AsInteger := Self.Empresa; ParamByName('SEQUENCIA').AsInteger := Self.Sequencia; end else if sColuna = 'CNPJ' then begin SQL.Add(' WHERE NUM_CPF_CNPJ = :CPFCNPJ'); ParamByName('CPFCNPJ').AsString := Self.CNPJ; end else if sColuna = 'BANCO' then begin SQL.Add(' WHERE COD_BANCO = :BANCO'); ParamByName('BANCO').AsString := Self.Banco; end else if sColuna = 'TIPO' then begin SQL.Add(' WHERE DES_TIPO_CONTA = :TIPO'); ParamByName('TIPO').AsString := Self.TipoConta; end else if sColuna = 'NOME' then begin SQL.Add(' WHERE NOM_FAVORECIDO = :NOME'); ParamByName('NOME').AsString := Self.Favorecido; end; dm.ZConn.PingServer; Open; if not IsEmpty then begin First; Result := FieldByName(sCampo).AsString; end; Close; SQL.Clear; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; destructor TFinanceiroEmpresa.Destroy; begin conexao.Free; bancos.Free; inherited Destroy; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, dxBar, dxBarExtItems, dxsbar, ComCtrls, StdCtrls, dxDockControl, ExtCtrls, dxDockPanel, cxGraphics, cxControls, dxStatusBar, GenelDM, Buttons, Ora, OraBarConn, Menus, DB, DBAccess; type TMainFrm = class(TForm) BarManager: TdxBarManager; dxBarSubItemFile: TdxBarSubItem; dxBarSubItemWindow: TdxBarSubItem; dxBarSubItemHelp: TdxBarSubItem; StatusBar: TdxStatusBar; dxBarPopupFormType: TdxBarPopupMenu; MI_SchemaBrowser: TdxBarButton; MI_SQLEditor: TdxBarButton; MI_Disconnect: TdxBarButton; dxBarListWindows: TdxBarListItem; dxBarLargeButton1: TdxBarLargeButton; btnSessions: TdxBarButton; dxBarSubItem1: TdxBarSubItem; btnDBA: TdxBarButton; barConnectDatabase: TdxBarButton; Memo1: TMemo; btnExit: TdxBarButton; dxBarSubItem4: TdxBarSubItem; btnUserReports: TdxBarButton; btnVisualOptions: TdxBarButton; btnDBStatus: TdxBarButton; btnFindInFiles: TdxBarButton; btnDatabaseSearch: TdxBarButton; btnVisualCompare: TdxBarButton; btnSQLPlus: TdxBarButton; dxBarSubItem3: TdxBarSubItem; btnAlertOptions: TdxBarButton; btnViewAlarms: TdxBarButton; btnExport: TdxBarButton; btnImport: TdxBarButton; bbtnDBMSOutput: TdxBarButton; dxBarSubItem2: TdxBarSubItem; btnAbout: TdxBarButton; btnEnvironmentOptions: TdxBarButton; procedure barConnectDatabaseClick(Sender: TObject); procedure onConnectionClick(Sender: TObject); procedure MI_SchemaBrowserClick(Sender: TObject); procedure MI_DisconnectClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure dxBarListWindowsClick(Sender: TObject); procedure dxBarListWindowsGetData(Sender: TObject); procedure MI_SQLEditorClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnSessionsClick(Sender: TObject); procedure btnDBAClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure btnVisualOptionsClick(Sender: TObject); procedure btnDBStatusClick(Sender: TObject); procedure btnVisualCompareClick(Sender: TObject); procedure btnAlertOptionsClick(Sender: TObject); procedure btnViewAlarmsClick(Sender: TObject); procedure bbtnDBMSOutputClick(Sender: TObject); procedure btnEnvironmentOptionsClick(Sender: TObject); procedure btnDatabaseSearchClick(Sender: TObject); private { Private declarations } myButton: TBarConnection; BarConnectionCount: integer; function BarConnection: TBarConnection; procedure CheckConnection; public { Public declarations } procedure ShowStatus(msg: string=''; panel : Integer=0; busy: Boolean=false); procedure ShowConnButton(ConnButton: TBarConnection); procedure FormDelete(ABarConnection: TBarConnection); end; var MainFrm: TMainFrm; implementation {$R *.dfm} uses frmLogin, frmSchemaBrowser, frmSQLEditor, frmSessionBrowser, frmDBA, frmVisualOptions, VisualOptions, frmDatabaseStatus, frmDiffMain, frmAlarmOptions, frmAlarmHistory, frmDBMSOutput, frmEnvironmentOptions, frmFindInDB; procedure TMainFrm.FormCreate(Sender: TObject); begin DMGenel.ChangeLanguage(self); ChangeVisualGUI(MainFrm); BarConnectionCount := 0; end; procedure TMainFrm.barConnectDatabaseClick(Sender: TObject); var LP: TLoginParams; myItem : TdxBarItemLink; begin LP := LoginFrm.login; CheckConnection; if LP.UserName = '' then exit; if not LP.OraSession.Connected then exit; myButton := TBarConnection.Create(self); inc(BarConnectionCount); myButton.Name := LP.UserName+IntTostr(BarConnectionCount); myButton.ButtonStyle := bsChecked; myButton.Caption := LP.Server+'/'+LP.UserName; myButton.Category := 2; myButton.GroupIndex := 9; myButton.Visible :=ivNever; myButton.Down := true; myButton.Session := LP.OraSession; myButton.OnClick := onConnectionClick; myButton.Count := 0; //ilk baglanti, hic bir ekran acik degil, ilk ekrana bu baglanti verilecek. myItem := BarManager.Bars[3].ItemLinks.Add; myItem.Item := myButton; myButton.Visible :=ivAlways; //FreeAndNil(LP); CheckConnection; end; procedure TMainFrm.CheckConnection; var OpenConnection: boolean; i: integer; Temp: TComponent; begin OpenConnection := False; for I := ComponentCount - 1 downto 0 do begin Temp := Components[I]; if (Temp is TBarConnection) then begin OpenConnection := True; break; end; end; MI_SchemaBrowser.Enabled := OpenConnection; MI_SQLEditor.Enabled := OpenConnection; btnDBA.Enabled := OpenConnection; btnSessions.Enabled := OpenConnection; btnDBStatus.Enabled := OpenConnection; btnAlertOptions.Enabled := OpenConnection; btnViewAlarms.Enabled := OpenConnection; bbtnDBMSOutput.Enabled := OpenConnection; end; procedure TMainFrm.MI_DisconnectClick(Sender: TObject); var i : integer; Temp: TComponent; begin Temp := nil; for I := ComponentCount - 1 downto 0 do begin Temp := Components[I]; if (Temp is TBarConnection) then begin if TBarConnection(Temp).Down then break; end; end; if MessageDlg('End connection '+TBarConnection(Temp).Caption+' . are you sure ?',mtConfirmation, [mbYes, mbNo], 0) = mrNo then exit; if Temp is TBarConnection then begin //bütün bağlı formları kapat with MainFrm do for I := MDIChildCount-1 downto 0 do begin if MDIChildren[I] is TSchemaBrowserFrm then if TSchemaBrowserFrm(MDIChildren[I]).BarConnName = TBarConnection(Temp).Name then MDIChildren[I].Close; if MDIChildren[I] is TSQLEditorFrm then if TSQLEditorFrm(MDIChildren[I]).BarConnName = TBarConnection(Temp).Name then MDIChildren[I].Close; if MDIChildren[I] is TDBAfrm then if TDBAfrm(MDIChildren[I]).BarConnName = TBarConnection(Temp).Name then MDIChildren[I].Close; if MDIChildren[I] is TSessionBrowserFrm then if TSessionBrowserFrm(MDIChildren[I]).BarConnName = TBarConnection(Temp).Name then MDIChildren[I].Close; end; TBarConnection(Temp).Count := 0; if TBarConnection(Temp).Session <> nil then TBarConnection(Temp).Session.Disconnect; FreeAndNil(TBarConnection(Temp)); end; CheckConnection; end; procedure TMainFrm.onConnectionClick(Sender: TObject); begin dxBarPopupFormType.PopupFromCursorPos; end; procedure TMainFrm.MI_SchemaBrowserClick(Sender: TObject); var f : TSchemaBrowserFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TSchemaBrowserFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.MI_SQLEditorClick(Sender: TObject); var f : TSQLEditorFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TSQLEditorFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.btnSessionsClick(Sender: TObject); var f : TSessionBrowserFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TSessionBrowserFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.btnDBAClick(Sender: TObject); var f : TDBAFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TDBAFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.btnDBStatusClick(Sender: TObject); var f : TDatabaseStatusFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TDatabaseStatusFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.btnVisualCompareClick(Sender: TObject); var f: TDiffMainFrm; begin f := TDiffMainFrm.Create(Application); f.Init; end; procedure TMainFrm.btnVisualOptionsClick(Sender: TObject); begin VisualOptionsFrm.Init; ChangeVisualGUI(MainFrm); end; procedure TMainFrm.btnEnvironmentOptionsClick(Sender: TObject); begin EnvironmentOptionsFrm.Init(); DMGenel.ChangeLanguage(self); ChangeVisualGUI(MainFrm); end; procedure TMainFrm.btnAlertOptionsClick(Sender: TObject); begin AlarmOptionsFrm.Init; end; procedure TMainFrm.btnViewAlarmsClick(Sender: TObject); var f: TAlarmHistoryFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TAlarmHistoryFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.bbtnDBMSOutputClick(Sender: TObject); var f: TDBMSOutputFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TDBMSOutputFrm.Create(Application); f.Init(BarConnection); end; procedure TMainFrm.FormDelete(ABarConnection: TBarConnection); begin TBarConnection(ABarConnection).Count := TBarConnection(ABarConnection).Count - 1; end; procedure TMainFrm.FormClose(Sender: TObject; var Action: TCloseAction); var i : integer; Temp: TComponent; begin with MainFrm do for I := MDIChildCount-1 downto 0 do MDIChildren[I].Close; for I := ComponentCount - 1 downto 0 do begin Temp := Components[I]; if (Temp is TBarConnection) then begin RemoveComponent(Temp); end; end; Action := caFree; end; procedure TMainFrm.ShowStatus(msg: string=''; panel : Integer=0; busy: Boolean=false); begin // show Message in statusbar if panel = 2 then begin StatusBar.Panels[panel].Text := msg; if busy then TdxStatusBarTextPanelStyle(StatusBar.Panels[1].PanelStyle).ImageIndex := 43 else TdxStatusBarTextPanelStyle(StatusBar.Panels[1].PanelStyle).ImageIndex := 42; end else StatusBar.Panels[panel].Text := msg; StatusBar.Repaint; end; procedure TMainFrm.ShowConnButton(ConnButton: TBarConnection); var i: integer; Temp: TComponent; begin for I := ComponentCount - 1 downto 0 do begin Temp := Components[I]; if (Temp is TBarConnection) then begin if TBarConnection(Temp) = ConnButton then begin TBarConnection(Temp).Down := true; break; end; end; end; end; procedure TMainFrm.dxBarListWindowsClick(Sender: TObject); begin with dxBarListWindows do TCustomForm(Items.Objects[ItemIndex]).Show; end; procedure TMainFrm.dxBarListWindowsGetData(Sender: TObject); begin with dxBarListWindows do ItemIndex := Items.IndexOfObject(ActiveMDIChild); end; procedure TMainFrm.FormShow(Sender: TObject); begin barConnectDatabase.Click; end; function TMainFrm.BarConnection: TBarConnection; var i : integer; Temp: TComponent; begin Temp := nil; for I := ComponentCount - 1 downto 0 do begin Temp := Components[I]; if (Temp is TBarConnection) then begin if TBarConnection(Temp).Down then break; end; end; result := TBarConnection(Temp); end; procedure TMainFrm.btnExitClick(Sender: TObject); begin close; end; procedure TMainFrm.btnDatabaseSearchClick(Sender: TObject); var f : TFindInDBFrm; begin if BarConnection = nil then exit; BarConnection.Count := BarConnection.Count + 1; f := TFindInDBFrm.Create(Application); f.Init(BarConnection); end; initialization dxBarRegisterItem(TBarConnection, TdxBarButtonControl, false); finalization dxBarUnregisterItem(TBarConnection); end.
{ TForge Library Copyright (c) Sergey Kasandrov 1997, 2018 ------------------------------------------------------- # AES block cipher algorithm } unit tfAlgAES; {$I TFL.inc} interface uses tfTypes; type PAESAlgorithm = ^TAESAlgorithm; TAESAlgorithm = record private const MaxRounds = 14; private type PBlock = ^TAESBlock; TAESBlock = record case Byte of 0: (Bytes: array[0..15] of Byte); 1: (LWords: array[0..3] of UInt32); end; PExpandedKey = ^TExpandedKey; TExpandedKey = record case Byte of 0: (Bytes: array[0 .. (MaxRounds + 2) * SizeOf(TAESBlock) - 1] of Byte); 1: (LWords: array[0 .. (MaxRounds + 2) * (SizeOf(TAESBlock) shr 2) - 1] of UInt32); 2: (Blocks: array[0 .. MaxRounds + 1] of TAESBlock); end; public const BLOCK_SIZE = 16; public type TBlock = array[0..BLOCK_SIZE - 1] of Byte; private FExpandedKey: TExpandedKey; FRounds: Cardinal; class procedure DoRound(const RoundKey: TAESBlock; var State: TAESBlock; Last: Boolean); static; class procedure DoInvRound(const RoundKey: TAESBlock; var State: TAESBlock; First: Boolean); static; public function ExpandKey(Key: PByte; KeySize: Cardinal): TF_RESULT; function EncryptBlock(Data: PByte): TF_RESULT; function DecryptBlock(Data: PByte): TF_RESULT; end; implementation procedure Xor128(Target: Pointer; Value: Pointer); inline; begin PUInt32(Target)^:= PUInt32(Target)^ xor PUInt32(Value)^; Inc(PUInt32(Target)); Inc(PUInt32(Value)); PUInt32(Target)^:= PUInt32(Target)^ xor PUInt32(Value)^; Inc(PUInt32(Target)); Inc(PUInt32(Value)); PUInt32(Target)^:= PUInt32(Target)^ xor PUInt32(Value)^; Inc(PUInt32(Target)); Inc(PUInt32(Value)); PUInt32(Target)^:= PUInt32(Target)^ xor PUInt32(Value)^; end; procedure XorBytes(Target: Pointer; Value: Pointer; Count: Integer); inline; var LCount: Integer; begin LCount:= Count shr 2; while LCount > 0 do begin PUInt32(Target)^:= PUInt32(Target)^ xor PUInt32(Value)^; Inc(PUInt32(Target)); Inc(PUInt32(Value)); Dec(LCount); end; LCount:= Count and 3; while LCount > 0 do begin PByte(Target)^:= PByte(Target)^ xor PByte(Value)^; Inc(PByte(Target)); Inc(PByte(Value)); Dec(LCount); end; end; { TAESAlgorithm } const RDLSBox : array[$00..$FF] of Byte = ($63, $7C, $77, $7B, $F2, $6B, $6F, $C5, $30, $01, $67, $2B, $FE, $D7, $AB, $76, $CA, $82, $C9, $7D, $FA, $59, $47, $F0, $AD, $D4, $A2, $AF, $9C, $A4, $72, $C0, $B7, $FD, $93, $26, $36, $3F, $F7, $CC, $34, $A5, $E5, $F1, $71, $D8, $31, $15, $04, $C7, $23, $C3, $18, $96, $05, $9A, $07, $12, $80, $E2, $EB, $27, $B2, $75, $09, $83, $2C, $1A, $1B, $6E, $5A, $A0, $52, $3B, $D6, $B3, $29, $E3, $2F, $84, $53, $D1, $00, $ED, $20, $FC, $B1, $5B, $6A, $CB, $BE, $39, $4A, $4C, $58, $CF, $D0, $EF, $AA, $FB, $43, $4D, $33, $85, $45, $F9, $02, $7F, $50, $3C, $9F, $A8, $51, $A3, $40, $8F, $92, $9D, $38, $F5, $BC, $B6, $DA, $21, $10, $FF, $F3, $D2, $CD, $0C, $13, $EC, $5F, $97, $44, $17, $C4, $A7, $7E, $3D, $64, $5D, $19, $73, $60, $81, $4F, $DC, $22, $2A, $90, $88, $46, $EE, $B8, $14, $DE, $5E, $0B, $DB, $E0, $32, $3A, $0A, $49, $06, $24, $5C, $C2, $D3, $AC, $62, $91, $95, $E4, $79, $E7, $C8, $37, $6D, $8D, $D5, $4E, $A9, $6C, $56, $F4, $EA, $65, $7A, $AE, $08, $BA, $78, $25, $2E, $1C, $A6, $B4, $C6, $E8, $DD, $74, $1F, $4B, $BD, $8B, $8A, $70, $3E, $B5, $66, $48, $03, $F6, $0E, $61, $35, $57, $B9, $86, $C1, $1D, $9E, $E1, $F8, $98, $11, $69, $D9, $8E, $94, $9B, $1E, $87, $E9, $CE, $55, $28, $DF, $8C, $A1, $89, $0D, $BF, $E6, $42, $68, $41, $99, $2D, $0F, $B0, $54, $BB, $16); const RDLInvSBox : array[$00..$FF] of Byte = ($52, $09, $6A, $D5, $30, $36, $A5, $38, $BF, $40, $A3, $9E, $81, $F3, $D7, $FB, $7C, $E3, $39, $82, $9B, $2F, $FF, $87, $34, $8E, $43, $44, $C4, $DE, $E9, $CB, $54, $7B, $94, $32, $A6, $C2, $23, $3D, $EE, $4C, $95, $0B, $42, $FA, $C3, $4E, $08, $2E, $A1, $66, $28, $D9, $24, $B2, $76, $5B, $A2, $49, $6D, $8B, $D1, $25, $72, $F8, $F6, $64, $86, $68, $98, $16, $D4, $A4, $5C, $CC, $5D, $65, $B6, $92, $6C, $70, $48, $50, $FD, $ED, $B9, $DA, $5E, $15, $46, $57, $A7, $8D, $9D, $84, $90, $D8, $AB, $00, $8C, $BC, $D3, $0A, $F7, $E4, $58, $05, $B8, $B3, $45, $06, $D0, $2C, $1E, $8F, $CA, $3F, $0F, $02, $C1, $AF, $BD, $03, $01, $13, $8A, $6B, $3A, $91, $11, $41, $4F, $67, $DC, $EA, $97, $F2, $CF, $CE, $F0, $B4, $E6, $73, $96, $AC, $74, $22, $E7, $AD, $35, $85, $E2, $F9, $37, $E8, $1C, $75, $DF, $6E, $47, $F1, $1A, $71, $1D, $29, $C5, $89, $6F, $B7, $62, $0E, $AA, $18, $BE, $1B, $FC, $56, $3E, $4B, $C6, $D2, $79, $20, $9A, $DB, $C0, $FE, $78, $CD, $5A, $F4, $1F, $DD, $A8, $33, $88, $07, $C7, $31, $B1, $12, $10, $59, $27, $80, $EC, $5F, $60, $51, $7F, $A9, $19, $B5, $4A, $0D, $2D, $E5, $7A, $9F, $93, $C9, $9C, $EF, $A0, $E0, $3B, $4D, $AE, $2A, $F5, $B0, $C8, $EB, $BB, $3C, $83, $53, $99, $61, $17, $2B, $04, $7E, $BA, $77, $D6, $26, $E1, $69, $14, $63, $55, $21, $0C, $7D); const RCon : array[1..TAESAlgorithm.MaxRounds] of UInt32 = ($00000001, $00000002, $00000004, $00000008, $00000010, $00000020, $00000040, $00000080, $0000001B, $00000036, $0000006C, $000000D8, $000000AB, $0000004D); const RDL_T0 : array[Byte] of UInt32 = ($A56363C6, $847C7CF8, $997777EE, $8D7B7BF6, $0DF2F2FF, $BD6B6BD6, $B16F6FDE, $54C5C591, $50303060, $03010102, $A96767CE, $7D2B2B56, $19FEFEE7, $62D7D7B5, $E6ABAB4D, $9A7676EC, $45CACA8F, $9D82821F, $40C9C989, $877D7DFA, $15FAFAEF, $EB5959B2, $C947478E, $0BF0F0FB, $ECADAD41, $67D4D4B3, $FDA2A25F, $EAAFAF45, $BF9C9C23, $F7A4A453, $967272E4, $5BC0C09B, $C2B7B775, $1CFDFDE1, $AE93933D, $6A26264C, $5A36366C, $413F3F7E, $02F7F7F5, $4FCCCC83, $5C343468, $F4A5A551, $34E5E5D1, $08F1F1F9, $937171E2, $73D8D8AB, $53313162, $3F15152A, $0C040408, $52C7C795, $65232346, $5EC3C39D, $28181830, $A1969637, $0F05050A, $B59A9A2F, $0907070E, $36121224, $9B80801B, $3DE2E2DF, $26EBEBCD, $6927274E, $CDB2B27F, $9F7575EA, $1B090912, $9E83831D, $742C2C58, $2E1A1A34, $2D1B1B36, $B26E6EDC, $EE5A5AB4, $FBA0A05B, $F65252A4, $4D3B3B76, $61D6D6B7, $CEB3B37D, $7B292952, $3EE3E3DD, $712F2F5E, $97848413, $F55353A6, $68D1D1B9, $00000000, $2CEDEDC1, $60202040, $1FFCFCE3, $C8B1B179, $ED5B5BB6, $BE6A6AD4, $46CBCB8D, $D9BEBE67, $4B393972, $DE4A4A94, $D44C4C98, $E85858B0, $4ACFCF85, $6BD0D0BB, $2AEFEFC5, $E5AAAA4F, $16FBFBED, $C5434386, $D74D4D9A, $55333366, $94858511, $CF45458A, $10F9F9E9, $06020204, $817F7FFE, $F05050A0, $443C3C78, $BA9F9F25, $E3A8A84B, $F35151A2, $FEA3A35D, $C0404080, $8A8F8F05, $AD92923F, $BC9D9D21, $48383870, $04F5F5F1, $DFBCBC63, $C1B6B677, $75DADAAF, $63212142, $30101020, $1AFFFFE5, $0EF3F3FD, $6DD2D2BF, $4CCDCD81, $140C0C18, $35131326, $2FECECC3, $E15F5FBE, $A2979735, $CC444488, $3917172E, $57C4C493, $F2A7A755, $827E7EFC, $473D3D7A, $AC6464C8, $E75D5DBA, $2B191932, $957373E6, $A06060C0, $98818119, $D14F4F9E, $7FDCDCA3, $66222244, $7E2A2A54, $AB90903B, $8388880B, $CA46468C, $29EEEEC7, $D3B8B86B, $3C141428, $79DEDEA7, $E25E5EBC, $1D0B0B16, $76DBDBAD, $3BE0E0DB, $56323264, $4E3A3A74, $1E0A0A14, $DB494992, $0A06060C, $6C242448, $E45C5CB8, $5DC2C29F, $6ED3D3BD, $EFACAC43, $A66262C4, $A8919139, $A4959531, $37E4E4D3, $8B7979F2, $32E7E7D5, $43C8C88B, $5937376E, $B76D6DDA, $8C8D8D01, $64D5D5B1, $D24E4E9C, $E0A9A949, $B46C6CD8, $FA5656AC, $07F4F4F3, $25EAEACF, $AF6565CA, $8E7A7AF4, $E9AEAE47, $18080810, $D5BABA6F, $887878F0, $6F25254A, $722E2E5C, $241C1C38, $F1A6A657, $C7B4B473, $51C6C697, $23E8E8CB, $7CDDDDA1, $9C7474E8, $211F1F3E, $DD4B4B96, $DCBDBD61, $868B8B0D, $858A8A0F, $907070E0, $423E3E7C, $C4B5B571, $AA6666CC, $D8484890, $05030306, $01F6F6F7, $120E0E1C, $A36161C2, $5F35356A, $F95757AE, $D0B9B969, $91868617, $58C1C199, $271D1D3A, $B99E9E27, $38E1E1D9, $13F8F8EB, $B398982B, $33111122, $BB6969D2, $70D9D9A9, $898E8E07, $A7949433, $B69B9B2D, $221E1E3C, $92878715, $20E9E9C9, $49CECE87, $FF5555AA, $78282850, $7ADFDFA5, $8F8C8C03, $F8A1A159, $80898909, $170D0D1A, $DABFBF65, $31E6E6D7, $C6424284, $B86868D0, $C3414182, $B0999929, $772D2D5A, $110F0F1E, $CBB0B07B, $FC5454A8, $D6BBBB6D, $3A16162C); const RDL_T1 : array[Byte] of UInt32 = ($6363C6A5, $7C7CF884, $7777EE99, $7B7BF68D, $F2F2FF0D, $6B6BD6BD, $6F6FDEB1, $C5C59154, $30306050, $01010203, $6767CEA9, $2B2B567D, $FEFEE719, $D7D7B562, $ABAB4DE6, $7676EC9A, $CACA8F45, $82821F9D, $C9C98940, $7D7DFA87, $FAFAEF15, $5959B2EB, $47478EC9, $F0F0FB0B, $ADAD41EC, $D4D4B367, $A2A25FFD, $AFAF45EA, $9C9C23BF, $A4A453F7, $7272E496, $C0C09B5B, $B7B775C2, $FDFDE11C, $93933DAE, $26264C6A, $36366C5A, $3F3F7E41, $F7F7F502, $CCCC834F, $3434685C, $A5A551F4, $E5E5D134, $F1F1F908, $7171E293, $D8D8AB73, $31316253, $15152A3F, $0404080C, $C7C79552, $23234665, $C3C39D5E, $18183028, $969637A1, $05050A0F, $9A9A2FB5, $07070E09, $12122436, $80801B9B, $E2E2DF3D, $EBEBCD26, $27274E69, $B2B27FCD, $7575EA9F, $0909121B, $83831D9E, $2C2C5874, $1A1A342E, $1B1B362D, $6E6EDCB2, $5A5AB4EE, $A0A05BFB, $5252A4F6, $3B3B764D, $D6D6B761, $B3B37DCE, $2929527B, $E3E3DD3E, $2F2F5E71, $84841397, $5353A6F5, $D1D1B968, $00000000, $EDEDC12C, $20204060, $FCFCE31F, $B1B179C8, $5B5BB6ED, $6A6AD4BE, $CBCB8D46, $BEBE67D9, $3939724B, $4A4A94DE, $4C4C98D4, $5858B0E8, $CFCF854A, $D0D0BB6B, $EFEFC52A, $AAAA4FE5, $FBFBED16, $434386C5, $4D4D9AD7, $33336655, $85851194, $45458ACF, $F9F9E910, $02020406, $7F7FFE81, $5050A0F0, $3C3C7844, $9F9F25BA, $A8A84BE3, $5151A2F3, $A3A35DFE, $404080C0, $8F8F058A, $92923FAD, $9D9D21BC, $38387048, $F5F5F104, $BCBC63DF, $B6B677C1, $DADAAF75, $21214263, $10102030, $FFFFE51A, $F3F3FD0E, $D2D2BF6D, $CDCD814C, $0C0C1814, $13132635, $ECECC32F, $5F5FBEE1, $979735A2, $444488CC, $17172E39, $C4C49357, $A7A755F2, $7E7EFC82, $3D3D7A47, $6464C8AC, $5D5DBAE7, $1919322B, $7373E695, $6060C0A0, $81811998, $4F4F9ED1, $DCDCA37F, $22224466, $2A2A547E, $90903BAB, $88880B83, $46468CCA, $EEEEC729, $B8B86BD3, $1414283C, $DEDEA779, $5E5EBCE2, $0B0B161D, $DBDBAD76, $E0E0DB3B, $32326456, $3A3A744E, $0A0A141E, $494992DB, $06060C0A, $2424486C, $5C5CB8E4, $C2C29F5D, $D3D3BD6E, $ACAC43EF, $6262C4A6, $919139A8, $959531A4, $E4E4D337, $7979F28B, $E7E7D532, $C8C88B43, $37376E59, $6D6DDAB7, $8D8D018C, $D5D5B164, $4E4E9CD2, $A9A949E0, $6C6CD8B4, $5656ACFA, $F4F4F307, $EAEACF25, $6565CAAF, $7A7AF48E, $AEAE47E9, $08081018, $BABA6FD5, $7878F088, $25254A6F, $2E2E5C72, $1C1C3824, $A6A657F1, $B4B473C7, $C6C69751, $E8E8CB23, $DDDDA17C, $7474E89C, $1F1F3E21, $4B4B96DD, $BDBD61DC, $8B8B0D86, $8A8A0F85, $7070E090, $3E3E7C42, $B5B571C4, $6666CCAA, $484890D8, $03030605, $F6F6F701, $0E0E1C12, $6161C2A3, $35356A5F, $5757AEF9, $B9B969D0, $86861791, $C1C19958, $1D1D3A27, $9E9E27B9, $E1E1D938, $F8F8EB13, $98982BB3, $11112233, $6969D2BB, $D9D9A970, $8E8E0789, $949433A7, $9B9B2DB6, $1E1E3C22, $87871592, $E9E9C920, $CECE8749, $5555AAFF, $28285078, $DFDFA57A, $8C8C038F, $A1A159F8, $89890980, $0D0D1A17, $BFBF65DA, $E6E6D731, $424284C6, $6868D0B8, $414182C3, $999929B0, $2D2D5A77, $0F0F1E11, $B0B07BCB, $5454A8FC, $BBBB6DD6, $16162C3A); const RDL_T2 : array[Byte] of UInt32 = ($63C6A563, $7CF8847C, $77EE9977, $7BF68D7B, $F2FF0DF2, $6BD6BD6B, $6FDEB16F, $C59154C5, $30605030, $01020301, $67CEA967, $2B567D2B, $FEE719FE, $D7B562D7, $AB4DE6AB, $76EC9A76, $CA8F45CA, $821F9D82, $C98940C9, $7DFA877D, $FAEF15FA, $59B2EB59, $478EC947, $F0FB0BF0, $AD41ECAD, $D4B367D4, $A25FFDA2, $AF45EAAF, $9C23BF9C, $A453F7A4, $72E49672, $C09B5BC0, $B775C2B7, $FDE11CFD, $933DAE93, $264C6A26, $366C5A36, $3F7E413F, $F7F502F7, $CC834FCC, $34685C34, $A551F4A5, $E5D134E5, $F1F908F1, $71E29371, $D8AB73D8, $31625331, $152A3F15, $04080C04, $C79552C7, $23466523, $C39D5EC3, $18302818, $9637A196, $050A0F05, $9A2FB59A, $070E0907, $12243612, $801B9B80, $E2DF3DE2, $EBCD26EB, $274E6927, $B27FCDB2, $75EA9F75, $09121B09, $831D9E83, $2C58742C, $1A342E1A, $1B362D1B, $6EDCB26E, $5AB4EE5A, $A05BFBA0, $52A4F652, $3B764D3B, $D6B761D6, $B37DCEB3, $29527B29, $E3DD3EE3, $2F5E712F, $84139784, $53A6F553, $D1B968D1, $00000000, $EDC12CED, $20406020, $FCE31FFC, $B179C8B1, $5BB6ED5B, $6AD4BE6A, $CB8D46CB, $BE67D9BE, $39724B39, $4A94DE4A, $4C98D44C, $58B0E858, $CF854ACF, $D0BB6BD0, $EFC52AEF, $AA4FE5AA, $FBED16FB, $4386C543, $4D9AD74D, $33665533, $85119485, $458ACF45, $F9E910F9, $02040602, $7FFE817F, $50A0F050, $3C78443C, $9F25BA9F, $A84BE3A8, $51A2F351, $A35DFEA3, $4080C040, $8F058A8F, $923FAD92, $9D21BC9D, $38704838, $F5F104F5, $BC63DFBC, $B677C1B6, $DAAF75DA, $21426321, $10203010, $FFE51AFF, $F3FD0EF3, $D2BF6DD2, $CD814CCD, $0C18140C, $13263513, $ECC32FEC, $5FBEE15F, $9735A297, $4488CC44, $172E3917, $C49357C4, $A755F2A7, $7EFC827E, $3D7A473D, $64C8AC64, $5DBAE75D, $19322B19, $73E69573, $60C0A060, $81199881, $4F9ED14F, $DCA37FDC, $22446622, $2A547E2A, $903BAB90, $880B8388, $468CCA46, $EEC729EE, $B86BD3B8, $14283C14, $DEA779DE, $5EBCE25E, $0B161D0B, $DBAD76DB, $E0DB3BE0, $32645632, $3A744E3A, $0A141E0A, $4992DB49, $060C0A06, $24486C24, $5CB8E45C, $C29F5DC2, $D3BD6ED3, $AC43EFAC, $62C4A662, $9139A891, $9531A495, $E4D337E4, $79F28B79, $E7D532E7, $C88B43C8, $376E5937, $6DDAB76D, $8D018C8D, $D5B164D5, $4E9CD24E, $A949E0A9, $6CD8B46C, $56ACFA56, $F4F307F4, $EACF25EA, $65CAAF65, $7AF48E7A, $AE47E9AE, $08101808, $BA6FD5BA, $78F08878, $254A6F25, $2E5C722E, $1C38241C, $A657F1A6, $B473C7B4, $C69751C6, $E8CB23E8, $DDA17CDD, $74E89C74, $1F3E211F, $4B96DD4B, $BD61DCBD, $8B0D868B, $8A0F858A, $70E09070, $3E7C423E, $B571C4B5, $66CCAA66, $4890D848, $03060503, $F6F701F6, $0E1C120E, $61C2A361, $356A5F35, $57AEF957, $B969D0B9, $86179186, $C19958C1, $1D3A271D, $9E27B99E, $E1D938E1, $F8EB13F8, $982BB398, $11223311, $69D2BB69, $D9A970D9, $8E07898E, $9433A794, $9B2DB69B, $1E3C221E, $87159287, $E9C920E9, $CE8749CE, $55AAFF55, $28507828, $DFA57ADF, $8C038F8C, $A159F8A1, $89098089, $0D1A170D, $BF65DABF, $E6D731E6, $4284C642, $68D0B868, $4182C341, $9929B099, $2D5A772D, $0F1E110F, $B07BCBB0, $54A8FC54, $BB6DD6BB, $162C3A16); const RDL_T3 : array[Byte] of UInt32 = ($C6A56363, $F8847C7C, $EE997777, $F68D7B7B, $FF0DF2F2, $D6BD6B6B, $DEB16F6F, $9154C5C5, $60503030, $02030101, $CEA96767, $567D2B2B, $E719FEFE, $B562D7D7, $4DE6ABAB, $EC9A7676, $8F45CACA, $1F9D8282, $8940C9C9, $FA877D7D, $EF15FAFA, $B2EB5959, $8EC94747, $FB0BF0F0, $41ECADAD, $B367D4D4, $5FFDA2A2, $45EAAFAF, $23BF9C9C, $53F7A4A4, $E4967272, $9B5BC0C0, $75C2B7B7, $E11CFDFD, $3DAE9393, $4C6A2626, $6C5A3636, $7E413F3F, $F502F7F7, $834FCCCC, $685C3434, $51F4A5A5, $D134E5E5, $F908F1F1, $E2937171, $AB73D8D8, $62533131, $2A3F1515, $080C0404, $9552C7C7, $46652323, $9D5EC3C3, $30281818, $37A19696, $0A0F0505, $2FB59A9A, $0E090707, $24361212, $1B9B8080, $DF3DE2E2, $CD26EBEB, $4E692727, $7FCDB2B2, $EA9F7575, $121B0909, $1D9E8383, $58742C2C, $342E1A1A, $362D1B1B, $DCB26E6E, $B4EE5A5A, $5BFBA0A0, $A4F65252, $764D3B3B, $B761D6D6, $7DCEB3B3, $527B2929, $DD3EE3E3, $5E712F2F, $13978484, $A6F55353, $B968D1D1, $00000000, $C12CEDED, $40602020, $E31FFCFC, $79C8B1B1, $B6ED5B5B, $D4BE6A6A, $8D46CBCB, $67D9BEBE, $724B3939, $94DE4A4A, $98D44C4C, $B0E85858, $854ACFCF, $BB6BD0D0, $C52AEFEF, $4FE5AAAA, $ED16FBFB, $86C54343, $9AD74D4D, $66553333, $11948585, $8ACF4545, $E910F9F9, $04060202, $FE817F7F, $A0F05050, $78443C3C, $25BA9F9F, $4BE3A8A8, $A2F35151, $5DFEA3A3, $80C04040, $058A8F8F, $3FAD9292, $21BC9D9D, $70483838, $F104F5F5, $63DFBCBC, $77C1B6B6, $AF75DADA, $42632121, $20301010, $E51AFFFF, $FD0EF3F3, $BF6DD2D2, $814CCDCD, $18140C0C, $26351313, $C32FECEC, $BEE15F5F, $35A29797, $88CC4444, $2E391717, $9357C4C4, $55F2A7A7, $FC827E7E, $7A473D3D, $C8AC6464, $BAE75D5D, $322B1919, $E6957373, $C0A06060, $19988181, $9ED14F4F, $A37FDCDC, $44662222, $547E2A2A, $3BAB9090, $0B838888, $8CCA4646, $C729EEEE, $6BD3B8B8, $283C1414, $A779DEDE, $BCE25E5E, $161D0B0B, $AD76DBDB, $DB3BE0E0, $64563232, $744E3A3A, $141E0A0A, $92DB4949, $0C0A0606, $486C2424, $B8E45C5C, $9F5DC2C2, $BD6ED3D3, $43EFACAC, $C4A66262, $39A89191, $31A49595, $D337E4E4, $F28B7979, $D532E7E7, $8B43C8C8, $6E593737, $DAB76D6D, $018C8D8D, $B164D5D5, $9CD24E4E, $49E0A9A9, $D8B46C6C, $ACFA5656, $F307F4F4, $CF25EAEA, $CAAF6565, $F48E7A7A, $47E9AEAE, $10180808, $6FD5BABA, $F0887878, $4A6F2525, $5C722E2E, $38241C1C, $57F1A6A6, $73C7B4B4, $9751C6C6, $CB23E8E8, $A17CDDDD, $E89C7474, $3E211F1F, $96DD4B4B, $61DCBDBD, $0D868B8B, $0F858A8A, $E0907070, $7C423E3E, $71C4B5B5, $CCAA6666, $90D84848, $06050303, $F701F6F6, $1C120E0E, $C2A36161, $6A5F3535, $AEF95757, $69D0B9B9, $17918686, $9958C1C1, $3A271D1D, $27B99E9E, $D938E1E1, $EB13F8F8, $2BB39898, $22331111, $D2BB6969, $A970D9D9, $07898E8E, $33A79494, $2DB69B9B, $3C221E1E, $15928787, $C920E9E9, $8749CECE, $AAFF5555, $50782828, $A57ADFDF, $038F8C8C, $59F8A1A1, $09808989, $1A170D0D, $65DABFBF, $D731E6E6, $84C64242, $D0B86868, $82C34141, $29B09999, $5A772D2D, $1E110F0F, $7BCBB0B0, $A8FC5454, $6DD6BBBB, $2C3A1616); const RDL_InvT0 : array[Byte] of UInt32 = ($00000000, $0B0D090E, $161A121C, $1D171B12, $2C342438, $27392D36, $3A2E3624, $31233F2A, $58684870, $5365417E, $4E725A6C, $457F5362, $745C6C48, $7F516546, $62467E54, $694B775A, $B0D090E0, $BBDD99EE, $A6CA82FC, $ADC78BF2, $9CE4B4D8, $97E9BDD6, $8AFEA6C4, $81F3AFCA, $E8B8D890, $E3B5D19E, $FEA2CA8C, $F5AFC382, $C48CFCA8, $CF81F5A6, $D296EEB4, $D99BE7BA, $7BBB3BDB, $70B632D5, $6DA129C7, $66AC20C9, $578F1FE3, $5C8216ED, $41950DFF, $4A9804F1, $23D373AB, $28DE7AA5, $35C961B7, $3EC468B9, $0FE75793, $04EA5E9D, $19FD458F, $12F04C81, $CB6BAB3B, $C066A235, $DD71B927, $D67CB029, $E75F8F03, $EC52860D, $F1459D1F, $FA489411, $9303E34B, $980EEA45, $8519F157, $8E14F859, $BF37C773, $B43ACE7D, $A92DD56F, $A220DC61, $F66D76AD, $FD607FA3, $E07764B1, $EB7A6DBF, $DA595295, $D1545B9B, $CC434089, $C74E4987, $AE053EDD, $A50837D3, $B81F2CC1, $B31225CF, $82311AE5, $893C13EB, $942B08F9, $9F2601F7, $46BDE64D, $4DB0EF43, $50A7F451, $5BAAFD5F, $6A89C275, $6184CB7B, $7C93D069, $779ED967, $1ED5AE3D, $15D8A733, $08CFBC21, $03C2B52F, $32E18A05, $39EC830B, $24FB9819, $2FF69117, $8DD64D76, $86DB4478, $9BCC5F6A, $90C15664, $A1E2694E, $AAEF6040, $B7F87B52, $BCF5725C, $D5BE0506, $DEB30C08, $C3A4171A, $C8A91E14, $F98A213E, $F2872830, $EF903322, $E49D3A2C, $3D06DD96, $360BD498, $2B1CCF8A, $2011C684, $1132F9AE, $1A3FF0A0, $0728EBB2, $0C25E2BC, $656E95E6, $6E639CE8, $737487FA, $78798EF4, $495AB1DE, $4257B8D0, $5F40A3C2, $544DAACC, $F7DAEC41, $FCD7E54F, $E1C0FE5D, $EACDF753, $DBEEC879, $D0E3C177, $CDF4DA65, $C6F9D36B, $AFB2A431, $A4BFAD3F, $B9A8B62D, $B2A5BF23, $83868009, $888B8907, $959C9215, $9E919B1B, $470A7CA1, $4C0775AF, $51106EBD, $5A1D67B3, $6B3E5899, $60335197, $7D244A85, $7629438B, $1F6234D1, $146F3DDF, $097826CD, $02752FC3, $335610E9, $385B19E7, $254C02F5, $2E410BFB, $8C61D79A, $876CDE94, $9A7BC586, $9176CC88, $A055F3A2, $AB58FAAC, $B64FE1BE, $BD42E8B0, $D4099FEA, $DF0496E4, $C2138DF6, $C91E84F8, $F83DBBD2, $F330B2DC, $EE27A9CE, $E52AA0C0, $3CB1477A, $37BC4E74, $2AAB5566, $21A65C68, $10856342, $1B886A4C, $069F715E, $0D927850, $64D90F0A, $6FD40604, $72C31D16, $79CE1418, $48ED2B32, $43E0223C, $5EF7392E, $55FA3020, $01B79AEC, $0ABA93E2, $17AD88F0, $1CA081FE, $2D83BED4, $268EB7DA, $3B99ACC8, $3094A5C6, $59DFD29C, $52D2DB92, $4FC5C080, $44C8C98E, $75EBF6A4, $7EE6FFAA, $63F1E4B8, $68FCEDB6, $B1670A0C, $BA6A0302, $A77D1810, $AC70111E, $9D532E34, $965E273A, $8B493C28, $80443526, $E90F427C, $E2024B72, $FF155060, $F418596E, $C53B6644, $CE366F4A, $D3217458, $D82C7D56, $7A0CA137, $7101A839, $6C16B32B, $671BBA25, $5638850F, $5D358C01, $40229713, $4B2F9E1D, $2264E947, $2969E049, $347EFB5B, $3F73F255, $0E50CD7F, $055DC471, $184ADF63, $1347D66D, $CADC31D7, $C1D138D9, $DCC623CB, $D7CB2AC5, $E6E815EF, $EDE51CE1, $F0F207F3, $FBFF0EFD, $92B479A7, $99B970A9, $84AE6BBB, $8FA362B5, $BE805D9F, $B58D5491, $A89A4F83, $A397468D); const RDL_InvT1 : array[Byte] of UInt32 = ($00000000, $0D090E0B, $1A121C16, $171B121D, $3424382C, $392D3627, $2E36243A, $233F2A31, $68487058, $65417E53, $725A6C4E, $7F536245, $5C6C4874, $5165467F, $467E5462, $4B775A69, $D090E0B0, $DD99EEBB, $CA82FCA6, $C78BF2AD, $E4B4D89C, $E9BDD697, $FEA6C48A, $F3AFCA81, $B8D890E8, $B5D19EE3, $A2CA8CFE, $AFC382F5, $8CFCA8C4, $81F5A6CF, $96EEB4D2, $9BE7BAD9, $BB3BDB7B, $B632D570, $A129C76D, $AC20C966, $8F1FE357, $8216ED5C, $950DFF41, $9804F14A, $D373AB23, $DE7AA528, $C961B735, $C468B93E, $E757930F, $EA5E9D04, $FD458F19, $F04C8112, $6BAB3BCB, $66A235C0, $71B927DD, $7CB029D6, $5F8F03E7, $52860DEC, $459D1FF1, $489411FA, $03E34B93, $0EEA4598, $19F15785, $14F8598E, $37C773BF, $3ACE7DB4, $2DD56FA9, $20DC61A2, $6D76ADF6, $607FA3FD, $7764B1E0, $7A6DBFEB, $595295DA, $545B9BD1, $434089CC, $4E4987C7, $053EDDAE, $0837D3A5, $1F2CC1B8, $1225CFB3, $311AE582, $3C13EB89, $2B08F994, $2601F79F, $BDE64D46, $B0EF434D, $A7F45150, $AAFD5F5B, $89C2756A, $84CB7B61, $93D0697C, $9ED96777, $D5AE3D1E, $D8A73315, $CFBC2108, $C2B52F03, $E18A0532, $EC830B39, $FB981924, $F691172F, $D64D768D, $DB447886, $CC5F6A9B, $C1566490, $E2694EA1, $EF6040AA, $F87B52B7, $F5725CBC, $BE0506D5, $B30C08DE, $A4171AC3, $A91E14C8, $8A213EF9, $872830F2, $903322EF, $9D3A2CE4, $06DD963D, $0BD49836, $1CCF8A2B, $11C68420, $32F9AE11, $3FF0A01A, $28EBB207, $25E2BC0C, $6E95E665, $639CE86E, $7487FA73, $798EF478, $5AB1DE49, $57B8D042, $40A3C25F, $4DAACC54, $DAEC41F7, $D7E54FFC, $C0FE5DE1, $CDF753EA, $EEC879DB, $E3C177D0, $F4DA65CD, $F9D36BC6, $B2A431AF, $BFAD3FA4, $A8B62DB9, $A5BF23B2, $86800983, $8B890788, $9C921595, $919B1B9E, $0A7CA147, $0775AF4C, $106EBD51, $1D67B35A, $3E58996B, $33519760, $244A857D, $29438B76, $6234D11F, $6F3DDF14, $7826CD09, $752FC302, $5610E933, $5B19E738, $4C02F525, $410BFB2E, $61D79A8C, $6CDE9487, $7BC5869A, $76CC8891, $55F3A2A0, $58FAACAB, $4FE1BEB6, $42E8B0BD, $099FEAD4, $0496E4DF, $138DF6C2, $1E84F8C9, $3DBBD2F8, $30B2DCF3, $27A9CEEE, $2AA0C0E5, $B1477A3C, $BC4E7437, $AB55662A, $A65C6821, $85634210, $886A4C1B, $9F715E06, $9278500D, $D90F0A64, $D406046F, $C31D1672, $CE141879, $ED2B3248, $E0223C43, $F7392E5E, $FA302055, $B79AEC01, $BA93E20A, $AD88F017, $A081FE1C, $83BED42D, $8EB7DA26, $99ACC83B, $94A5C630, $DFD29C59, $D2DB9252, $C5C0804F, $C8C98E44, $EBF6A475, $E6FFAA7E, $F1E4B863, $FCEDB668, $670A0CB1, $6A0302BA, $7D1810A7, $70111EAC, $532E349D, $5E273A96, $493C288B, $44352680, $0F427CE9, $024B72E2, $155060FF, $18596EF4, $3B6644C5, $366F4ACE, $217458D3, $2C7D56D8, $0CA1377A, $01A83971, $16B32B6C, $1BBA2567, $38850F56, $358C015D, $22971340, $2F9E1D4B, $64E94722, $69E04929, $7EFB5B34, $73F2553F, $50CD7F0E, $5DC47105, $4ADF6318, $47D66D13, $DC31D7CA, $D138D9C1, $C623CBDC, $CB2AC5D7, $E815EFE6, $E51CE1ED, $F207F3F0, $FF0EFDFB, $B479A792, $B970A999, $AE6BBB84, $A362B58F, $805D9FBE, $8D5491B5, $9A4F83A8, $97468DA3); const RDL_InvT2 : array[Byte] of UInt32 = ($00000000, $090E0B0D, $121C161A, $1B121D17, $24382C34, $2D362739, $36243A2E, $3F2A3123, $48705868, $417E5365, $5A6C4E72, $5362457F, $6C48745C, $65467F51, $7E546246, $775A694B, $90E0B0D0, $99EEBBDD, $82FCA6CA, $8BF2ADC7, $B4D89CE4, $BDD697E9, $A6C48AFE, $AFCA81F3, $D890E8B8, $D19EE3B5, $CA8CFEA2, $C382F5AF, $FCA8C48C, $F5A6CF81, $EEB4D296, $E7BAD99B, $3BDB7BBB, $32D570B6, $29C76DA1, $20C966AC, $1FE3578F, $16ED5C82, $0DFF4195, $04F14A98, $73AB23D3, $7AA528DE, $61B735C9, $68B93EC4, $57930FE7, $5E9D04EA, $458F19FD, $4C8112F0, $AB3BCB6B, $A235C066, $B927DD71, $B029D67C, $8F03E75F, $860DEC52, $9D1FF145, $9411FA48, $E34B9303, $EA45980E, $F1578519, $F8598E14, $C773BF37, $CE7DB43A, $D56FA92D, $DC61A220, $76ADF66D, $7FA3FD60, $64B1E077, $6DBFEB7A, $5295DA59, $5B9BD154, $4089CC43, $4987C74E, $3EDDAE05, $37D3A508, $2CC1B81F, $25CFB312, $1AE58231, $13EB893C, $08F9942B, $01F79F26, $E64D46BD, $EF434DB0, $F45150A7, $FD5F5BAA, $C2756A89, $CB7B6184, $D0697C93, $D967779E, $AE3D1ED5, $A73315D8, $BC2108CF, $B52F03C2, $8A0532E1, $830B39EC, $981924FB, $91172FF6, $4D768DD6, $447886DB, $5F6A9BCC, $566490C1, $694EA1E2, $6040AAEF, $7B52B7F8, $725CBCF5, $0506D5BE, $0C08DEB3, $171AC3A4, $1E14C8A9, $213EF98A, $2830F287, $3322EF90, $3A2CE49D, $DD963D06, $D498360B, $CF8A2B1C, $C6842011, $F9AE1132, $F0A01A3F, $EBB20728, $E2BC0C25, $95E6656E, $9CE86E63, $87FA7374, $8EF47879, $B1DE495A, $B8D04257, $A3C25F40, $AACC544D, $EC41F7DA, $E54FFCD7, $FE5DE1C0, $F753EACD, $C879DBEE, $C177D0E3, $DA65CDF4, $D36BC6F9, $A431AFB2, $AD3FA4BF, $B62DB9A8, $BF23B2A5, $80098386, $8907888B, $9215959C, $9B1B9E91, $7CA1470A, $75AF4C07, $6EBD5110, $67B35A1D, $58996B3E, $51976033, $4A857D24, $438B7629, $34D11F62, $3DDF146F, $26CD0978, $2FC30275, $10E93356, $19E7385B, $02F5254C, $0BFB2E41, $D79A8C61, $DE94876C, $C5869A7B, $CC889176, $F3A2A055, $FAACAB58, $E1BEB64F, $E8B0BD42, $9FEAD409, $96E4DF04, $8DF6C213, $84F8C91E, $BBD2F83D, $B2DCF330, $A9CEEE27, $A0C0E52A, $477A3CB1, $4E7437BC, $55662AAB, $5C6821A6, $63421085, $6A4C1B88, $715E069F, $78500D92, $0F0A64D9, $06046FD4, $1D1672C3, $141879CE, $2B3248ED, $223C43E0, $392E5EF7, $302055FA, $9AEC01B7, $93E20ABA, $88F017AD, $81FE1CA0, $BED42D83, $B7DA268E, $ACC83B99, $A5C63094, $D29C59DF, $DB9252D2, $C0804FC5, $C98E44C8, $F6A475EB, $FFAA7EE6, $E4B863F1, $EDB668FC, $0A0CB167, $0302BA6A, $1810A77D, $111EAC70, $2E349D53, $273A965E, $3C288B49, $35268044, $427CE90F, $4B72E202, $5060FF15, $596EF418, $6644C53B, $6F4ACE36, $7458D321, $7D56D82C, $A1377A0C, $A8397101, $B32B6C16, $BA25671B, $850F5638, $8C015D35, $97134022, $9E1D4B2F, $E9472264, $E0492969, $FB5B347E, $F2553F73, $CD7F0E50, $C471055D, $DF63184A, $D66D1347, $31D7CADC, $38D9C1D1, $23CBDCC6, $2AC5D7CB, $15EFE6E8, $1CE1EDE5, $07F3F0F2, $0EFDFBFF, $79A792B4, $70A999B9, $6BBB84AE, $62B58FA3, $5D9FBE80, $5491B58D, $4F83A89A, $468DA397); const RDL_InvT3 : array[Byte] of UInt32 = ($00000000, $0E0B0D09, $1C161A12, $121D171B, $382C3424, $3627392D, $243A2E36, $2A31233F, $70586848, $7E536541, $6C4E725A, $62457F53, $48745C6C, $467F5165, $5462467E, $5A694B77, $E0B0D090, $EEBBDD99, $FCA6CA82, $F2ADC78B, $D89CE4B4, $D697E9BD, $C48AFEA6, $CA81F3AF, $90E8B8D8, $9EE3B5D1, $8CFEA2CA, $82F5AFC3, $A8C48CFC, $A6CF81F5, $B4D296EE, $BAD99BE7, $DB7BBB3B, $D570B632, $C76DA129, $C966AC20, $E3578F1F, $ED5C8216, $FF41950D, $F14A9804, $AB23D373, $A528DE7A, $B735C961, $B93EC468, $930FE757, $9D04EA5E, $8F19FD45, $8112F04C, $3BCB6BAB, $35C066A2, $27DD71B9, $29D67CB0, $03E75F8F, $0DEC5286, $1FF1459D, $11FA4894, $4B9303E3, $45980EEA, $578519F1, $598E14F8, $73BF37C7, $7DB43ACE, $6FA92DD5, $61A220DC, $ADF66D76, $A3FD607F, $B1E07764, $BFEB7A6D, $95DA5952, $9BD1545B, $89CC4340, $87C74E49, $DDAE053E, $D3A50837, $C1B81F2C, $CFB31225, $E582311A, $EB893C13, $F9942B08, $F79F2601, $4D46BDE6, $434DB0EF, $5150A7F4, $5F5BAAFD, $756A89C2, $7B6184CB, $697C93D0, $67779ED9, $3D1ED5AE, $3315D8A7, $2108CFBC, $2F03C2B5, $0532E18A, $0B39EC83, $1924FB98, $172FF691, $768DD64D, $7886DB44, $6A9BCC5F, $6490C156, $4EA1E269, $40AAEF60, $52B7F87B, $5CBCF572, $06D5BE05, $08DEB30C, $1AC3A417, $14C8A91E, $3EF98A21, $30F28728, $22EF9033, $2CE49D3A, $963D06DD, $98360BD4, $8A2B1CCF, $842011C6, $AE1132F9, $A01A3FF0, $B20728EB, $BC0C25E2, $E6656E95, $E86E639C, $FA737487, $F478798E, $DE495AB1, $D04257B8, $C25F40A3, $CC544DAA, $41F7DAEC, $4FFCD7E5, $5DE1C0FE, $53EACDF7, $79DBEEC8, $77D0E3C1, $65CDF4DA, $6BC6F9D3, $31AFB2A4, $3FA4BFAD, $2DB9A8B6, $23B2A5BF, $09838680, $07888B89, $15959C92, $1B9E919B, $A1470A7C, $AF4C0775, $BD51106E, $B35A1D67, $996B3E58, $97603351, $857D244A, $8B762943, $D11F6234, $DF146F3D, $CD097826, $C302752F, $E9335610, $E7385B19, $F5254C02, $FB2E410B, $9A8C61D7, $94876CDE, $869A7BC5, $889176CC, $A2A055F3, $ACAB58FA, $BEB64FE1, $B0BD42E8, $EAD4099F, $E4DF0496, $F6C2138D, $F8C91E84, $D2F83DBB, $DCF330B2, $CEEE27A9, $C0E52AA0, $7A3CB147, $7437BC4E, $662AAB55, $6821A65C, $42108563, $4C1B886A, $5E069F71, $500D9278, $0A64D90F, $046FD406, $1672C31D, $1879CE14, $3248ED2B, $3C43E022, $2E5EF739, $2055FA30, $EC01B79A, $E20ABA93, $F017AD88, $FE1CA081, $D42D83BE, $DA268EB7, $C83B99AC, $C63094A5, $9C59DFD2, $9252D2DB, $804FC5C0, $8E44C8C9, $A475EBF6, $AA7EE6FF, $B863F1E4, $B668FCED, $0CB1670A, $02BA6A03, $10A77D18, $1EAC7011, $349D532E, $3A965E27, $288B493C, $26804435, $7CE90F42, $72E2024B, $60FF1550, $6EF41859, $44C53B66, $4ACE366F, $58D32174, $56D82C7D, $377A0CA1, $397101A8, $2B6C16B3, $25671BBA, $0F563885, $015D358C, $13402297, $1D4B2F9E, $472264E9, $492969E0, $5B347EFB, $553F73F2, $7F0E50CD, $71055DC4, $63184ADF, $6D1347D6, $D7CADC31, $D9C1D138, $CBDCC623, $C5D7CB2A, $EFE6E815, $E1EDE51C, $F3F0F207, $FDFBFF0E, $A792B479, $A999B970, $BB84AE6B, $B58FA362, $9FBE805D, $91B58D54, $83A89A4F, $8DA39746); type TRDLVector = record case Byte of 0 : (LWord: UInt32); 1 : (Bytes: array[0..3] of Byte); end; TRDLVectors = array[0..3] of TRDLVector; // block size = 128 bits TRDLMixColMatrix = array[0..3, 0..3] of Byte; function RdlSubVector(const v : TRDLVector) : TRDLVector; { S-Box substitution } begin Result.Bytes[0]:= RdlSBox[v.Bytes[0]]; Result.Bytes[1]:= RdlSBox[v.Bytes[1]]; Result.Bytes[2]:= RdlSBox[v.Bytes[2]]; Result.Bytes[3]:= RdlSBox[v.Bytes[3]]; end; function RdlRotateVector(v : TRDLVector; Count : Byte) : TRDLVector; { rotate vector (count bytes) to the right, e.g. } { |3 2 1 0| -> |0 3 2 1| for Count = 1 } var i : Byte; begin i := Count mod 4; Result.Bytes[0] := v.Bytes[i]; Result.Bytes[1] := v.Bytes[(i+1) mod 4]; Result.Bytes[2] := v.Bytes[(i+2) mod 4]; Result.Bytes[3] := v.Bytes[(i+3) mod 4]; end; function SubVector(const Vector: TRDLVector): TRDLVector; { S-Box substitution } begin Result.Bytes[0]:= RdlSBox[Vector.Bytes[0]]; Result.Bytes[1]:= RdlSBox[Vector.Bytes[1]]; Result.Bytes[2]:= RdlSBox[Vector.Bytes[2]]; Result.Bytes[3]:= RdlSBox[Vector.Bytes[3]]; end; function RotVector(const Vector: TRDLVector): TRDLVector; { rotate vector to the right, |a b c d| -> |d a b c| } begin Result.Bytes[0]:= Vector.Bytes[1]; Result.Bytes[1]:= Vector.Bytes[2]; Result.Bytes[2]:= Vector.Bytes[3]; Result.Bytes[3]:= Vector.Bytes[0]; end; class procedure TAESAlgorithm.DoRound(const RoundKey: TAESBlock; var State: TAESBlock; Last: Boolean); var i : Integer; e : TRDLVectors; begin for i := 0 to 3 do begin if not Last then begin e[i].LWord:= RDL_T0[TRDlVectors(State)[(i+0) mod 4].Bytes[0]] xor RDL_T1[TRDlVectors(State)[(i+1) mod 4].Bytes[1]] xor RDL_T2[TRDlVectors(State)[(i+2) mod 4].Bytes[2]] xor RDL_T3[TRDlVectors(State)[(i+3) mod 4].Bytes[3]] end else begin e[i].Bytes[0]:= RDLSBox[TRDlVectors(State)[(i+0) mod 4].Bytes[0]]; e[i].Bytes[1]:= RDLSBox[TRDlVectors(State)[(i+1) mod 4].Bytes[1]]; e[i].Bytes[2]:= RDLSBox[TRDlVectors(State)[(i+2) mod 4].Bytes[2]]; e[i].Bytes[3]:= RDLSBox[TRDlVectors(State)[(i+3) mod 4].Bytes[3]]; end; end; Xor128(@e, @RoundKey); State:= TAESBlock(e); end; class procedure TAESAlgorithm.DoInvRound(const RoundKey: TAESBlock; var State: TAESBlock; First: Boolean); var i : Integer; r : TRDLVectors; e : TRDLVector; begin Xor128(PUInt32(@State), PUInt32(@RoundKey)); for i := 0 to 3 do begin if not First then begin e.LWord:= RDL_InvT0[TRDlVectors(State)[i].Bytes[0]] xor RDL_InvT1[TRDlVectors(State)[i].Bytes[1]] xor RDL_InvT2[TRDlVectors(State)[i].Bytes[2]] xor RDL_InvT3[TRDlVectors(State)[i].Bytes[3]]; r[(i+0) mod 4].Bytes[0] := RDLInvSBox[e.Bytes[0]]; r[(i+1) mod 4].Bytes[1] := RDLInvSBox[e.Bytes[1]]; r[(i+2) mod 4].Bytes[2] := RDLInvSBox[e.Bytes[2]]; r[(i+3) mod 4].Bytes[3] := RDLInvSBox[e.Bytes[3]]; end else begin r[i].Bytes[0] := RDLInvSBox[TRDlVectors(State)[(i+0) mod 4].Bytes[0]]; r[i].Bytes[1] := RDLInvSBox[TRDlVectors(State)[(i+3) mod 4].Bytes[1]]; r[i].Bytes[2] := RDLInvSBox[TRDlVectors(State)[(i+2) mod 4].Bytes[2]]; r[i].Bytes[3] := RDLInvSBox[TRDlVectors(State)[(i+1) mod 4].Bytes[3]]; end; end; State := TAESBlock(r); end; function TAESAlgorithm.DecryptBlock(Data: PByte): TF_RESULT; var I: Integer; begin DoInvRound(FExpandedKey.Blocks[FRounds], PBlock(Data)^, True); for I:= (FRounds - 1) downto 1 do DoInvRound(FExpandedKey.Blocks[I], PBlock(Data)^, False); Xor128(Data, @FExpandedKey); Result:= TF_S_OK; end; function TAESAlgorithm.EncryptBlock(Data: PByte): TF_RESULT; var I: Integer; begin Xor128(Data, @FExpandedKey); for I:= 1 to FRounds - 1 do DoRound(FExpandedKey.Blocks[I], PBlock(Data)^, False); DoRound(FExpandedKey.Blocks[FRounds], PBlock(Data)^, True); Result:= TF_S_OK; end; function TAESAlgorithm.ExpandKey(Key: PByte; KeySize: Cardinal): TF_RESULT; var I: Cardinal; Temp: TRDLVector; Nk: Cardinal; begin if (KeySize = 16) or (KeySize = 24) or (KeySize = 32) then begin Move(Key^, FExpandedKey, KeySize); // key length in 4-byte words (# of key columns) Nk:= KeySize shr 2; // Nk = 4, 6 or 8 FRounds:= 6 + Nk; // # of rounds = 10, 12 or 14 // expand key into round keys for I:= Nk to 4 * (FRounds + 1) do begin Temp.LWord:= FExpandedKey.LWords[I-1]; case Nk of 4, 6: begin if (I mod Nk) = 0 then Temp.LWord:= SubVector(RotVector(Temp)).LWord xor RCon[I div Nk]; FExpandedKey.LWords[I]:= FExpandedKey.LWords[I - Nk] xor Temp.LWord; end else { Nk = 8 } if (I mod Nk) = 0 then Temp.LWord:= SubVector(RotVector(Temp)).LWord xor RCon[I div Nk] else if (I mod Nk) = 4 then Temp:= SubVector(Temp); FExpandedKey.LWords[I]:= FExpandedKey.LWords[I - Nk] xor Temp.LWord; end; end; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Data.JSON, RemObjects.Elements.EUnit; type JsonObjectTest = public class (Test) private Obj: JsonObject; public method Setup; override; method &Add; method AddFailsWithDuplicate; method AddFailsWithNilKey; method AddValue; method AddValueFailsWithDuplicateKey; method AddValueFailsWithNilKey; method AddValueFailsWithNilValue; method Clear; method ContainsKey; method ContainsKeyFailsWithNil; method &Remove; method RemoveFailsWithNil; method Count; method GetItem; method GetItemFailsWithNil; method GetItemFaulsWithMissingKey; method SetItemAddsNewValue; method SetItemUpdateExisting; method SetItemFailsWithNilKey; method SetItemFailsWithNilValue; method Keys; method Properties; method Enumerable; end; implementation method JsonObjectTest.Setup; begin Obj := new JsonObject; end; method JsonObjectTest.Add; begin Obj.Add("a", 42); Assert.AreEqual(Obj.Count, 1); Assert.AreEqual(Obj["a"].ToInteger, 42); end; method JsonObjectTest.AddFailsWithDuplicate; begin &Add; Assert.Throws(->Obj.Add("a", 123)); end; method JsonObjectTest.AddFailsWithNilKey; begin Assert.Throws(->Obj.Add(nil, "abc")); end; method JsonObjectTest.AddValue; begin Obj.AddValue("a", new JsonValue(42)); Assert.AreEqual(Obj.Count, 1); Assert.AreEqual(Obj["a"].ToInteger, 42); end; method JsonObjectTest.AddValueFailsWithDuplicateKey; begin AddValue; Assert.Throws(->Obj.AddValue("a", new JsonValue(nil))); end; method JsonObjectTest.AddValueFailsWithNilKey; begin Assert.Throws(->Obj.AddValue(nil, new JsonValue(1))); end; method JsonObjectTest.AddValueFailsWithNilValue; begin Assert.Throws(->Obj.AddValue("a", nil)); end; method JsonObjectTest.Clear; begin &Add; Obj.Clear; Assert.AreEqual(Obj.Count, 0); end; method JsonObjectTest.ContainsKey; begin &Add; Assert.IsTrue(Obj.ContainsKey("a")); Assert.IsFalse(Obj.ContainsKey("b")); end; method JsonObjectTest.ContainsKeyFailsWithNil; begin Assert.Throws(->Obj.ContainsKey(nil)); end; method JsonObjectTest.Remove; begin &Add; Assert.IsTrue(Obj.Remove("a")); Assert.IsFalse(Obj.Remove("a")); end; method JsonObjectTest.RemoveFailsWithNil; begin Assert.Throws(->Obj.Remove(nil)); end; method JsonObjectTest.Count; begin Assert.AreEqual(Obj.Count, 0); &Add; end; method JsonObjectTest.GetItem; begin &Add; Assert.AreEqual(Obj.Item["a"], new JsonValue(42)); Assert.AreEqual(Obj["a"].ToInteger, 42); end; method JsonObjectTest.GetItemFailsWithNil; begin Assert.Throws(->Obj[nil]); end; method JsonObjectTest.GetItemFaulsWithMissingKey; begin Assert.Throws(->Obj.Item["abc"]); end; method JsonObjectTest.SetItemAddsNewValue; begin Obj["a"] := new JsonValue(42); Assert.AreEqual(Obj.Count, 1); Assert.AreEqual(Obj["a"].ToInteger, 42); end; method JsonObjectTest.SetItemUpdateExisting; begin &Add; Obj["a"] := new JsonValue(55); Assert.AreEqual(Obj.Count, 1); Assert.AreEqual(Obj["a"].ToInteger, 55); end; method JsonObjectTest.SetItemFailsWithNilKey; begin Assert.Throws(->begin Obj[nil] := new JsonValue(1) end); end; method JsonObjectTest.SetItemFailsWithNilValue; begin Assert.Throws(->begin Obj["a"] := nil end); end; method JsonObjectTest.Keys; begin Assert.IsEmpty(Obj.Keys); &Add; Assert.AreEqual(Obj.Keys, ["a"]); end; method JsonObjectTest.Properties; begin Assert.IsEmpty(Obj.Properties); &Add; Assert.AreEqual(Obj.Properties, [new Sugar.Collections.KeyValuePair<String,JsonValue>("a", new JsonValue(42))]); end; method JsonObjectTest.Enumerable; begin Assert.IsEmpty(Obj); &Add; Assert.AreEqual(Obj, [new Sugar.Collections.KeyValuePair<String,JsonValue>("a", new JsonValue(42))]); end; end.
unit UnkFacilitySheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, InternationalizerComponent; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidCurrBlock = 'CurrBlock'; tidCost = 'Cost'; tidROI = 'ROI'; const facStoppedByTycoon = $04; type TUnknownFacilitySheetHandler = class; TUnknowFacilitySheetViewer = class(TVisualControl) xfer_Name: TEdit; Label1: TLabel; Label2: TLabel; xfer_Creator: TLabel; Label6: TLabel; xfer_MetaFacilityName: TLabel; NameLabel: TLabel; btnClose: TFramedButton; btnDemolish: TFramedButton; btnConnect: TFramedButton; Label8: TLabel; lbCost: TLabel; Label9: TLabel; lbROI: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure xfer_NameKeyPress(Sender: TObject; var Key: Char); procedure btnCloseClick(Sender: TObject); procedure btnRepairClick(Sender: TObject); procedure btnDemolishClick(Sender: TObject); procedure btnConnectClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TUnknownFacilitySheetHandler; end; TUnknownFacilitySheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TUnknowFacilitySheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; private function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure SetName(str : string); procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); end; var UnknowFacilitySheetViewer: TUnknowFacilitySheetViewer; function UnknownFacilitySheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, CacheCommon, Protocol, MathUtils, SheetUtils, Literals; {$R *.DFM} // TUnknownFacilitySheetHandler function TUnknownFacilitySheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TUnknowFacilitySheetViewer.Create(Owner); fControl.fHandler := self; result := fControl; end; function TUnknownFacilitySheetHandler.GetControl : TControl; begin result := fControl; end; procedure TUnknownFacilitySheetHandler.RenderProperties(Properties : TStringList); var trouble : string; roi : integer; begin LockWindowUpdate(fControl.Handle); try FiveViewUtils.SetViewProp(fControl, Properties); trouble := Properties.Values[tidTrouble]; fOwnsFacility := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId] ); if fOwnsFacility then try fCurrBlock := StrToInt(Properties.Values[tidCurrBlock]); except fCurrBlock := 0; end else fCurrBlock := 0; try if (trouble <> '') and (StrToInt(trouble) and facStoppedByTycoon <> 0) then fControl.btnClose.Text := GetLiteral('Literal128') else fControl.btnClose.Text := GetLiteral('Literal129'); except end; fControl.NameLabel.Caption := fControl.xfer_Name.Text; fControl.NameLabel.Visible := not fOwnsFacility; fControl.xfer_Name.Enabled := fOwnsFacility; fControl.xfer_Name.Visible := fOwnsFacility; fControl.btnClose.Enabled := fOwnsFacility; fControl.btnDemolish.Enabled := fOwnsFacility; fControl.btnConnect.Enabled := true; fControl.lbCost.Caption := MathUtils.FormatMoneyStr(Properties.Values[tidCost]); try if Properties.Values[tidROI] <> '' then roi := round(StrToFloat(Properties.Values[tidROI])) else roi := 0; if roi = 0 then fControl.lbROI.Caption := GetLiteral('Literal130') else if roi > 0 then fControl.lbROI.Caption := GetFormattedLiteral('Literal131', [Properties.Values[tidROI]]) else fControl.lbROI.Caption := GetLiteral('Literal132'); except fControl.lbROI.Caption := GetLiteral('Literal133'); end; finally LockWindowUpdate(0); end; end; procedure TUnknownFacilitySheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; FiveViewUtils.GetViewPropNames(fControl, Names); Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); Names.Add(tidCost); Names.Add(tidROI); Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); end; end; procedure TUnknownFacilitySheetHandler.Clear; begin inherited; fControl.NameLabel.Caption := NA; fControl.xfer_Name.Text := ''; fControl.xfer_Name.Enabled := false; fControl.xfer_MetaFacilityName.Caption := NA; fControl.xfer_Creator.Caption := NA; fControl.lbCost.Caption := NA; fControl.lbROI.Caption := NA; fControl.btnClose.Enabled := false; fControl.btnConnect.Enabled := false; fControl.btnDemolish.Enabled := false; end; procedure TUnknownFacilitySheetHandler.SetName(str : string); var MSProxy : OleVariant; begin try try fControl.Cursor := crHourGlass; MSProxy := fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) and fOwnsFacility and CacheCommon.ValidName(str) then MSProxy.Name := str else Beep; finally fControl.Cursor := crDefault; end; except end; end; procedure TUnknownFacilitySheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; Prop : TStringList; begin Update := parms[1].vInteger; try try Prop := fContainer.GetProperties(Names); finally Names.Free; end; if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; except end; end; procedure TUnknownFacilitySheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if parms[1].vInteger = fLastUpdate then RenderProperties(Prop); finally Prop.Free; end; except end; end; // UnknownFacilitySheetHandlerCreator function UnknownFacilitySheetHandlerCreator : IPropertySheetHandler; begin result := TUnknownFacilitySheetHandler.Create; end; // TUnknowFacilitySheetViewer procedure TUnknowFacilitySheetViewer.xfer_NameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then fHandler.SetName(xfer_Name.Text) else if Key in NotAllowedChars then Key := #0; end; procedure TUnknowFacilitySheetViewer.btnCloseClick(Sender: TObject); begin if btnClose.Text = GetLiteral('Literal134') then begin fHandler.fContainer.GetMSProxy.Stopped := true; btnClose.Text := GetLiteral('Literal135'); end else begin fHandler.fContainer.GetMSProxy.Stopped := false; btnClose.Text := GetLiteral('Literal136'); end end; procedure TUnknowFacilitySheetViewer.btnRepairClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; Proxy.BindTo(fHandler.fCurrBlock); Proxy.RdoRepair; except end; end; procedure TUnknowFacilitySheetViewer.btnDemolishClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.GetContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo('World'); if Proxy.RDODelFacility(fHandler.GetContainer.GetXPos, fHandler.GetContainer.GetYPos) <> NOERROR then Beep; end; except end; end; procedure TUnknowFacilitySheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TUnknowFacilitySheetViewer.btnConnectClick(Sender: TObject); var url : string; begin url := 'http://local.asp?frame_Id=MapIsoView&frame_Action=PICKONMAP'; fHandler.GetContainer.HandleURL(url, false); end; initialization SheetHandlerRegistry.RegisterSheetHandler('unkGeneral', UnknownFacilitySheetHandlerCreator); end.
UNIT Container; INTERFACE TYPE Tree = ^NodeType; NodeType = RECORD Word: STRING; LLink, RLink: Tree; Amount: INTEGER END; PROCEDURE Insert(VAR Ptr:Tree; VAR Data: STRING); PROCEDURE PrintTree(VAR Ptr: Tree; VAR FOut: TEXT); IMPLEMENTATION PROCEDURE Insert(VAR Ptr:Tree; VAR Data: STRING); BEGIN {Insert} IF Ptr = NIL THEN BEGIN NEW(Ptr); Ptr^.Amount := 1; Ptr^.Word := Data; Ptr^.LLink := NIL; Ptr^.RLink := NIL END ELSE IF Data < Ptr^.Word THEN Insert(Ptr^.LLink, Data) ELSE IF Data > Ptr^.Word THEN Insert(Ptr^.RLink, Data) ELSE Ptr^.Amount := Ptr^.Amount + 1 END; {Insert} PROCEDURE PrintTree(VAR Ptr: Tree; VAR FOut: TEXT); BEGIN {PrintTree} IF Ptr <> NIL THEN BEGIN PrintTree(Ptr^.LLink, FOut); WRITELN(FOut, Ptr^.Word, ' ', Ptr^.Amount); PrintTree(Ptr^.RLink, FOut) END END; {PrintTree} PROCEDURE ClearTree(VAR Ptr: Tree); BEGIN {ClearTree} IF Ptr <> NIL THEN BEGIN ClearTree(Ptr^.LLink); ClearTree(Ptr^.RLink); DISPOSE(Ptr); Ptr := NIL END END; {ClearTree} BEGIN END.
unit DAO.PenalizacaoAtrasos; interface uses DAO.Base, Model.PenalizacaoAtrasos, Generics.Collections, System.Classes; type TPenalizacaoAtrasosDAO = class(TDAO) public function Insert(aPenas: Model.PenalizacaoAtrasos.TPenalizacaoatrasos): Boolean; function Update(aPenas: Model.PenalizacaoAtrasos.TPenalizacaoatrasos): Boolean; function Delete(sFiltro: String): Boolean; function FindPenalizacao(sFiltro: String): TObjectList<Model.PenalizacaoAtrasos.TPenalizacaoatrasos>; end; const TABLENAME = 'tbpenalizacaoatrasos'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TPenalizacaoAtrasosDAO.Insert(aPenas: TPenalizacaoAtrasos):Boolean; var sSQL: System.string; begin Result := False; aPenas.ID := GetKeyValue(TABLENAME,'ID_PENALIZACAO'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(ID_PENALIZACAO, DAT_PENALIZACAO, QTD_DIAS_ATRASO, VAL_PENALIZACAO, PER_PENALIZACAO, DES_LOG)' + 'VALUES ' + '(:ID, :DATA, :ATRASO, :VALOR, :PERCENTUAL, :LOG);'; Connection.ExecSQL(sSQL,[aPenas.ID, aPenas.Data, aPenas.Atraso, aPenas.Valor, aPenas.Percentual, aPenas.Log],[ftInteger, ftDate, ftInteger, ftFloat, ftFloat, ftString]); Result := True; end; function TPenalizacaoAtrasosDAO.Update(aPenas: TPenalizacaoAtrasos): Boolean; var sSQL: System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'DAT_PENALIZACAO = :DATA, QTD_DIAS_ATRASO = :ATRASO, VAL_PENALIZACAO = :VALOR, PER_PENALIZACAO = :PERCENTUAL, ' + 'DES_LOG = :LOG ' + 'WHERE ID_PENALIZACAO = :ID'; Connection.ExecSQL(sSQL,[aPenas.Data, aPenas.Atraso, aPenas.Valor, aPenas.Percentual, aPenas.Log],[ftDate, ftInteger, ftFloat, ftFloat, ftString, ftInteger]); Result := True; end; function TPenalizacaoAtrasosDAO.Delete(sFiltro: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; connection.ExecSQL(sSQL); Result := True; end; function TPenalizacaoAtrasosDAO.FindPenalizacao(sFiltro: string): TObjectList<Model.PenalizacaoAtrasos.TPenalizacaoatrasos>; var FDQuery: TFDQuery; penas: TObjectList<TPenalizacaoAtrasos>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); penas := TObjectList<TPenalizacaoAtrasos>.Create(); while not FDQuery.Eof do begin penas.Add(TPenalizacaoAtrasos.Create(FDQuery.FieldByName('ID_PENALIZACAO').AsInteger, FDQuery.FieldByName('DAT_PENALIZACAO').AsDateTime, FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger, FDQuery.FieldByName('VAL_PENALIZACAO').AsFloat, FDQuery.FieldByName('PER_PENALIZACAO').AsFloat, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := penas; end; end.
unit AutoMapper.CfgMapper; interface uses AutoMapper.MapItem , AutoMapper.TypePair , AutoMapper.MappingExpression , System.Generics.Collections , System.Rtti ; type /// <summary>Mapper setting flag</summary> TMapperSetting = ( /// <summary>Perform mapping even if the source-destination pair is not configured</summary> Automap ); /// <summary>Mapper setting flags</summary> TMapperSettings = set of TMapperSetting; TCfgMapper = class private FMaps: TDictionary<TTypePair, TMap>; FSettings: TMapperSettings; function ExpressionToValue<TSource, TDestination>(const AExpression: TMapExpression<TSource, TDestination>): TValue; overload; public constructor Create; destructor Destroy; override; function TryGetMap(const ATypePair: TTypePair; out Map: TMap): boolean; property Settings: TMapperSettings read FSettings write FSettings; procedure CreateMap(SourceType, DestType: TRttiType); overload; procedure CreateMap<TSource; TDestination>; overload; procedure CreateMap<TSource; TDestination>(const MappingExpression: TMapExpression<TSource, TDestination>); overload; function Count: integer; end; implementation uses AutoMapper.Exceptions , System.SysUtils ; { TCfgMapper } function TCfgMapper.Count: integer; begin result := FMaps.Count; end; constructor TCfgMapper.Create; begin FMaps := TObjectDictionary<TTypePair, TMap>.Create([doOwnsValues]); FSettings := [TMapperSetting.Automap]; end; procedure TCfgMapper.CreateMap<TSource, TDestination>; var Ctx: TRttiContext; SourceType, DestType: TRttiType; DefaultExp: TMapExpression<TSource, TDestination>; TypePair : TTypePair; ExpValue : TValue; Map : TMap; begin Ctx := TRttiContext.Create; SourceType := Ctx.GetType(TypeInfo(TSource)); DestType := Ctx.GetType(TypeInfo(TDestination)); case TMapExpCollections.GetExpressionType<TSource, TDestination> of TExpressionType.ObjectToObject: DefaultExp := TMapExpCollections.MapExpObjectToObject<TSource, TDestination>; TExpressionType.ObjectToRecord: DefaultExp := TMapExpCollections.MapExpObjectToRecord<TSource, TDestination>; TExpressionType.RecordToObject: DefaultExp := TMapExpCollections.MapExpRecordToObject<TSource, TDestination>; TExpressionType.RecordToRecord: DefaultExp := TMapExpCollections.MapExpRecordToRecord<TSource, TDestination>; else raise TMapperConfigureException.Create('Pair of types not supported.'); end; TypePair := TTypePair.Create(SourceType.QualifiedName, DestType.QualifiedName); ExpValue := ExpressionToValue<TSource, TDestination>(DefaultExp); Map := TMap.Create(TypePair, ExpValue); FMaps.Add(TypePair, Map); end; procedure TCfgMapper.CreateMap(SourceType, DestType: TRttiType); begin end; procedure TCfgMapper.CreateMap<TSource, TDestination>( const MappingExpression: TMapExpression<TSource, TDestination>); var Ctx: TRttiContext; SourceType, DestType: TRttiType; Map: TMap; TypePair: TTypePair; Exp: TValue; begin Ctx := TRttiContext.Create; SourceType := Ctx.GetType(TypeInfo(TSource)); DestType := Ctx.GetType(TypeInfo(TDestination)); TypePair := TTypePair.Create(SourceType.QualifiedName, DestType.QualifiedName); Exp := ExpressionToValue<TSource, TDestination>(MappingExpression); Map := TMap.Create(TypePair, Exp); FMaps.Add(TypePair, Map); end; function TCfgMapper.ExpressionToValue<TSource, TDestination>( const AExpression: TMapExpression<TSource, TDestination>): TValue; var Value: TValue; begin TValue.Make(@AExpression, TypeInfo(TMapExpression<TSource, TDestination>), Value); Result := Value; end; function TCfgMapper.TryGetMap(const ATypePair: TTypePair; out Map: TMap): boolean; begin result := FMaps.TryGetValue(ATypePair, Map); end; destructor TCfgMapper.Destroy; begin FMaps.Clear; FMaps.Free; inherited; end; end.
unit TimerTicker; interface uses Classes, TimerTypes, ShutDown, TimerUtils, ThreadTimer; type TTickerTimer = TThreadTimer; const cTimerInterval = 40; type TTimerTicker = class(TInterfacedObject, ITicker, IShutDownTarget) private fTimer : TTickerTimer; fTickeables : TList; procedure TimerTick; public constructor Create; destructor Destroy; override; private // ITicker function GetEnabled : boolean; procedure SetEnabled(which : boolean); function Count : integer; function GetTickeable(idx : integer) : ITickeable; procedure Attach(const which : ITickeable); procedure Detach(const which : ITickeable); private // IShutDownTarget function GetPriority : integer; procedure OnSuspend; procedure OnResume; procedure OnShutDown; end; procedure AttachTickeable(const which : ITickeable); procedure DetachTickeable(const which : ITickeable); procedure EnableTicker; procedure DisableTicker; implementation uses Windows; var theTicker : ITicker; // TTimerTicker constructor TTimerTicker.Create; begin inherited; fTickeables := TList.Create; fTimer := TTickerTimer.Create; fTimer.OnTimer := TimerTick; fTimer.Interval := cTimerInterval; fTimer.Enabled := true; AttachTarget(Self); end; destructor TTimerTicker.Destroy; begin DetachTarget(Self); fTimer.Free; fTickeables.Free; inherited; end; function TTimerTicker.GetEnabled : boolean; begin Result := fTimer.Enabled; end; procedure TTimerTicker.SetEnabled(which : boolean); begin fTimer.Enabled := which; end; function TTimerTicker.Count : integer; begin Result := fTickeables.Count; end; function TTimerTicker.GetTickeable(idx : integer) : ITickeable; begin Result := ITickeable(fTickeables[idx]); end; procedure TTimerTicker.Attach(const which : ITickeable); begin which._AddRef; fTickeables.Add(pointer(which)); end; procedure TTimerTicker.Detach(const which : ITickeable); var idx : integer; begin idx := fTickeables.IndexOf(pointer(which)); if idx <> -1 then begin fTickeables.Delete(idx); which._Release; end; end; function TTimerTicker.GetPriority : integer; begin Result := 100; end; procedure TTimerTicker.OnSuspend; begin if fTimer <> nil then fTimer.Enabled := false; end; procedure TTimerTicker.OnResume; begin if fTimer <> nil then fTimer.Enabled := true; end; procedure TTimerTicker.OnShutDown; begin fTimer.Enabled := false; end; procedure TTimerTicker.TimerTick; var i : integer; CurTickeable : ITickeable; mininterval : integer; desinterval : integer; begin if fTimer.Enabled then begin mininterval := high(mininterval); for i := 0 to pred(fTickeables.Count) do begin CurTickeable := ITickeable(fTickeables[i]); if CurTickeable.Enabled then begin desinterval := ITickeable(fTickeables[i]).Tick; if desinterval < mininterval then mininterval := desinterval; end; end; if (mininterval > 0) and (mininterval < 2*cTimerInterval) then fTimer.Interval := mininterval else fTimer.Interval := cTimerInterval; end; end; procedure AttachTickeable(const which : ITickeable); begin if theTicker = nil then theTicker := TTimerTicker.Create; theTicker.Attach(which); end; procedure DetachTickeable(const which : ITickeable); begin if theTicker <> nil then theTicker.Detach(which); end; procedure EnableTicker; begin if theTicker <> nil then theTicker.Enabled := true; end; procedure DisableTicker; begin if theTicker <> nil then theTicker.Enabled := false; end; end.
/// <summary> /// DSON is a customized version of BSON that more closely represents /// internal Delphi data types. /// </summary> unit DSON; interface uses System.Rtti, System.Generics.Defaults, System.SysUtils, System.Classes, System.Generics.Collections; type TDSONKind = (dkNil, dkByte, dkInt16, dkInt32, dkInt64, dkString, dkSingle, dkDouble, dkExtended, dkChar, dkTrue, dkFalse, dkEnum, dkDateTime, dkArray, dkObject, dkGUID, dkRecord, dkPair); TDSONMarker = (dmNil, dmByte, dmInt16, dmInt32, dmInt64, dmString, dmSingle, dmDouble, dmExtended, dmChar, dmTrue, dmFalse, dmEnum, dmDateTime, dmStartPair, dmEndPair, dmStartArray, dmEndArray, dmStartObject, dmEndObject, dmGUID, dmRecord); {$REGION 'Interfaces'} /// <summary> /// Base DSON value /// </summary> IDSONValue = interface(IInterface) ['{FD12E23B-DAB3-40BC-A619-8C996197B04B}'] function GetKind: TDSONKind; procedure SetKind(const Value: TDSONKind); property Kind: TDSONKind read GetKind write SetKind; end; /// <summary> /// Simple value (ordinals / strings) /// </summary> IDSONSimple = interface(IDSONValue) ['{1949DF4F-4356-427A-95CC-F286F1595D63}'] function GetValue: TValue; property Value: TValue read GetValue; end; /// <summary> /// Array value /// </summary> IDSONArray = interface(IDSONValue) ['{D98F4AA9-F567-4454-BA41-CBD261002F27}'] procedure AddArrayValue(const AValue: IDSONValue); function GetValues: TArray<IDSONValue>; property Values: TArray<IDSONValue> read GetValues; end; /// <summary> /// DSON Name, Value pair /// </summary> IDSONPair = interface(IInterface) ['{AB0D4072-4236-45E0-BD08-22A09DDBA55E}'] function GetName: string; function GetValue: IDSONValue; procedure SetName(const Value: string); procedure SetValue(const Value: IDSONValue); property Name: string read GetName write SetName; property Value: IDSONValue read GetValue write SetValue; end; /// <summary> /// DSON Object, contains DSON pairs /// </summary> IDSONObject = interface(IDSONValue) ['{877D8139-73A5-4B0A-B4D6-AE2BFE0E18CC}'] procedure AddPair(const APair: IDSONPair); overload; procedure AddPair(const AName: string; AValue: IDSONValue); overload; function GetPairs: TList<IDSONPair>; property Pairs: TList<IDSONPair> read GetPairs; end; /// <summary> /// DSON Builder /// </summary> /// <remarks> /// Can be used fluently or not. /// </remarks> /// <example> /// <para> /// Fluent Example: <br /><c> /// Builder.AddPropertyName("foo").AddValue("bar");</c> /// </para> /// <para> /// Non-fluent example: <br /><c>Builder.AddPropertyName("foo"); /// Builder.AddValue("bar");</c> /// </para> /// </example> IDSONBuilder = interface(IInterface) ['{0C10A42D-E7A1-4F42-821D-15C81369E196}'] function StartObject: IDSONBuilder; function EndObject: IDSONBuilder; function StartArray: IDSONBuilder; function EndArray: IDSONBuilder; function AddPropertyName(const AName: string): IDSONBuilder; { TODO: null values! } function AddNilValue: IDSONBuilder; function AddValue(const AValue: Shortint): IDSONBuilder; overload; function AddValue(const AValue: Smallint): IDSONBuilder; overload; function AddValue(const AValue: Integer): IDSONBuilder; overload; function AddValue(const AValue: Byte): IDSONBuilder; overload; function AddValue(const AValue: Word): IDSONBuilder; overload; function AddValue(const AValue: Cardinal): IDSONBuilder; overload; function AddValue(const AValue: Int64): IDSONBuilder; overload; function AddValue(const AValue: UInt64): IDSONBuilder; overload; function AddValue(const AValue: string): IDSONBuilder; overload; function AddValue(const AValue: Single): IDSONBuilder; overload; function AddValue(const AValue: Double): IDSONBuilder; overload; function AddValue(const AValue: Extended): IDSONBuilder; overload; function AddValue(const AValue: Char): IDSONBuilder; overload; function AddValue(const AValue: Boolean): IDSONBuilder; overload; function AddValue(const AValue: TGUID): IDSONBuilder; overload; function AddValue(const AValue: TDateTime): IDSONBuilder; overload; function GetDSONOBject: IDSONObject; property DSONObject: IDSONObject read GetDSONOBject; end; IDSONReader = interface(IInterface) ['{E924CEE7-0A79-423A-B12F-94919C56F5C9}'] function ReadObject(AStream: TStream): IDSONObject; end; IDSONWriter = interface(IInterface) ['{591492B5-567E-49B6-9182-0B8F40941298}'] end; /// <summary> /// Writes the DSON object to a stream /// </summary> /// <remarks> /// <para> /// The object is written in the following format: /// </para> /// <para> /// [dmStartObject Marker] <br />[Pair] <br />[Pair] <br />... <br /> /// [dmEndObjectMarker] /// </para> /// <para> /// Pairs are made up of a name and a value. They are written as /// follows: /// </para> /// <para> /// [dmStartPair marker] <br />[ValueType marker] <br />[Name length /// (integer)][Name] <br />[Value] <br />[dmEndPair marker] /// </para> /// <para> /// Values can be simple or complex. Fixed size values are written /// unadorned, with the ValueType marker determining the byte size. /// Strings are written with the length of the string first (integer) /// followed by the string itself. /// </para> /// <para> /// Objects are written as above. /// </para> /// <para> /// Arrays are written as follows: /// </para> /// <para> /// [dmStartArray Marker] <br />[Value] <br />[Value] <br />... <br /> /// [dmEndArray Marker] /// </para> /// </remarks> IDSONBinaryWriter = interface(IDSONWriter) ['{E28B11BE-70E3-48D7-90EC-8BDEF156CE71}'] function WriteObject(const ADsonObject: IDSONObject): TBytes; procedure WriteObjectToStream(const ADsonObject: IDSONObject; const AStream: TStream); end; /// <summary> /// Writes a DSON object to a JSON string. This will of course be lossy. /// </summary> IDSONJSONWriter = interface(IDSONWriter) ['{37C6D77D-E9AE-4A64-AB0C-76F212731F6A}'] function WriteObject(const ADsonObject: IDSONObject): string; end; {$ENDREGION} {$REGION 'Implementations'} TDSONValue = class(TInterfacedObject, IDSONValue) strict protected FKind: TDSONKind; function GetKind: TDSONKind; procedure SetKind(const Value: TDSONKind); end; TDSONSimple = class(TDSONValue, IDSONSimple) strict private FValue: TValue; function DSONKindFromValue(const AValue: TValue): TDSONKind; function GetValue: TValue; public constructor CreateNil; constructor Create(const AValue: Boolean); overload; constructor Create(const AValue: Byte); overload; constructor Create(const AValue: Char); overload; constructor Create(const AValue: Cardinal); overload; constructor Create(const AValue: Double); overload; constructor Create(const AValue: Extended); overload; constructor Create(const AValue: Integer); overload; constructor Create(const AValue: Shortint); overload; constructor Create(const AValue: Int64); overload; constructor Create(const AValue: Smallint); overload; constructor Create(const AValue: string); overload; constructor Create(const AValue: Single); overload; constructor Create(const AValue: TDateTime); overload; constructor Create(const AValue: TGUID); overload; constructor Create(const AValue: TValue); overload; constructor Create(const AValue: UInt64); overload; constructor Create(const AValue: Word); overload; end; TDSONArray = class(TDSONValue, IDSONArray) strict private FValues: TArray<IDSONValue>; function GetValues: TArray<IDSONValue>; public constructor Create; procedure AddArrayValue(const AValue: IDSONValue); end; TDSONPair = class(TDSONValue, IDSONPair) strict private FName: string; FValue: IDSONValue; function GetName: string; function GetValue: IDSONValue; procedure SetName(const Value: string); procedure SetValue(const Value: IDSONValue); public constructor Create(const AName: string; const AValue: IDSONValue); end; { TODO: This is only needed if I decide to implement sorted output } TDSONPairNameComparer = class(TComparer<IDSONPair>) public function Compare(const Left, Right: IDSONPair): Integer; override; end; TDSONObject = class(TDSONValue, IDSONObject) strict private FPairs: TList<IDSONPair>; public constructor Create; procedure AddPair(const APair: IDSONPair); overload; procedure AddPair(const AName: string; AValue: IDSONValue); overload; function GetPairs: TList<IDSONPair>; destructor Destroy; override; end; TDSONBuilder = class(TInterfacedObject, IDSONBuilder) strict private type TBuilderState = (bsError, bsReady, bsExpectingValue, bsBuildingObject, bsBuildingArray); strict private FDsonObject: IDSONObject; FNameStack: TStack<string>; FStateStack: TStack<TBuilderState>; FValueStack: TStack<IDSONValue>; function AddPair(const AName, AValue: string): IDSONBuilder; function ArrayIsOnValueStack: Boolean; function CurrentState: TBuilderState; procedure FinalizeArrayValue; procedure FinalizeObjectValue; procedure FinalizeSimpleValue; function GetDSONOBject: IDSONObject; function GetState: TBuilderState; function ObjectIsOnValueStack: Boolean; function PopPair: IDSONPair; property State: TBuilderState read GetState; public constructor Create; destructor Destroy; override; function AddPropertyName(const AName: string): IDSONBuilder; function AddNilValue: IDSONBuilder; function AddValue(const AValue: Boolean): IDSONBuilder; overload; function AddValue(const AValue: Byte): IDSONBuilder; overload; function AddValue(const AValue: Char): IDSONBuilder; overload; function AddValue(const AValue: Cardinal): IDSONBuilder; overload; function AddValue(const AValue: Double): IDSONBuilder; overload; function AddValue(const AValue: Extended): IDSONBuilder; overload; function AddValue(const AValue: Integer): IDSONBuilder; overload; function AddValue(const AValue: Shortint): IDSONBuilder; overload; function AddValue(const AValue: Int64): IDSONBuilder; overload; function AddValue(const AValue: Smallint): IDSONBuilder; overload; function AddValue(const AValue: string): IDSONBuilder; overload; function AddValue(const AValue: Single): IDSONBuilder; overload; function AddValue(const AValue: TDateTime): IDSONBuilder; overload; function AddValue(const AValue: TGUID): IDSONBuilder; overload; function AddValue(const AValue: UInt64): IDSONBuilder; overload; function AddValue(const AValue: Word): IDSONBuilder; overload; function StartArray: IDSONBuilder; function EndArray: IDSONBuilder; function StartObject: IDSONBuilder; function EndObject: IDSONBuilder; property DSONObject: IDSONObject read GetDSONOBject; end; TDSONWriter = class abstract(TInterfacedObject, IDSONWriter) strict protected FStream: TStream; procedure InternalWriteArrayValue(const Value: IDSONArray); virtual; abstract; procedure InternalWriteBuffer(const Buffer: pointer; ACount: Integer); virtual; abstract; procedure InternalWriteDateTime(const Value: IDSONSimple); virtual; abstract; procedure InternalWriteGuidValue(const Value: IDSONSimple); virtual; abstract; procedure InternalWriteMarker(const AMarker: TDSONMarker); virtual; abstract; procedure InternalWriteName(const AName: string); virtual; abstract; procedure InternalWriteObject(const ADsonObject: IDSONObject); virtual; abstract; procedure InternalWriteSimpleValue(const Value: IDSONSimple); virtual; abstract; procedure InternalWriteString(const AValue: string); virtual; abstract; function MarkerForSimpleKind(ADsonKind: TDSONKind): TDSONMarker; procedure WriteArrayValue(const Value: IDSONArray); procedure WriteBuffer(const Buffer: pointer; ACount: Integer); procedure WriteDateTime(const Value: IDSONSimple); procedure WriteGUIDValue(const Value: IDSONSimple); procedure WriteMarker(const AMarker: TDSONMarker); procedure WriteName(const AName: string); virtual; procedure WritePair(const APair: IDSONPair); procedure WriteSimpleValue(const Value: IDSONSimple); procedure WriteString(const AValue: string); procedure WriteValue(const Value: IDSONValue); public procedure WriteObjectToStream(const ADsonObject: IDSONObject; const AStream: TStream); end; TDSONBinaryWriter = class(TDSONWriter, IDSONBinaryWriter) strict private procedure WriteExtended(const AValue: TValue); private strict protected procedure InternalWriteArrayValue(const Value: IDSONArray); override; procedure InternalWriteBuffer(const Buffer: pointer; ACount: Integer); override; procedure InternalWriteDateTime(const Value: IDSONSimple); override; procedure InternalWriteGuidValue(const Value: IDSONSimple); override; procedure InternalWriteMarker(const AMarker: TDSONMarker); override; procedure InternalWriteName(const AName: string); override; procedure InternalWriteObject(const ADsonObject: IDSONObject); override; procedure InternalWriteSimpleValue(const Value: IDSONSimple); override; procedure InternalWriteString(const AValue: string); override; public function WriteObject(const ADsonObject: IDSONObject): TBytes; end; TDSONJSONWriter = class(TDSONWriter, IDSONJSONWriter) strict private function DoubleQuoted(const AString: string): String; function MarkerToString(const AMarker: TDSONMarker): string; strict protected procedure InternalWriteArrayValue(const Value: IDSONArray); override; procedure InternalWriteBuffer(const Buffer: pointer; ACount: Integer); override; procedure InternalWriteDateTime(const Value: IDSONSimple); override; procedure InternalWriteGuidValue(const Value: IDSONSimple); override; procedure InternalWriteMarker(const AMarker: TDSONMarker); override; procedure InternalWriteName(const AName: string); override; procedure InternalWriteObject(const ADsonObject: IDSONObject); override; procedure InternalWriteSimpleValue(const Value: IDSONSimple); override; procedure InternalWriteString(const AValue: string); override; public function WriteObject(const ADsonObject: IDSONObject): string; end; TDSONReader = class(TInterfacedObject, IDSONReader) strict private type TReaderState = (rsError, rsReady, rsExpectingValue, rsReadingObject, rsReadingArray); strict private FStateStack: TStack<TReaderState>; FStream: TStream; function PeekMarker: TDSONMarker; function ReadArray: IDSONArray; function ReadDateTime: IDSONValue; function ReadExtended: IDSONValue; function ReadGUID: IDSONValue; function ReadPair: TDSONPair; function ReadPropertyName: string; function ReadSimple<T>: IDSONSimple; function ReadString: string; function ReadValue: IDSONValue; strict protected function ReadMarker: TDSONMarker; virtual; public constructor Create; function ReadObject: IDSONObject; overload; function ReadObject(AStream: TStream): IDSONObject; overload; destructor Destroy; override; end; {$ENDREGION} function BinaryWriter: IDSONBinaryWriter; function Builder: IDSONBuilder; function JSONWriter: IDSONJSONWriter; function Reader: IDSONReader; implementation uses System.DateUtils; function Reader: IDSONReader; begin Result := TDSONReader.Create; end; function BinaryWriter: IDSONBinaryWriter; begin Result := TDSONBinaryWriter.Create; end; function JSONWriter: IDSONJSONWriter; begin Result := TDSONJSONWriter.Create; end; function Builder: IDSONBuilder; begin Result := TDSONBuilder.Create; end; constructor TDSONPair.Create(const AName: string; const AValue: IDSONValue); begin FName := AName; FValue := AValue; FKind := dkPair; end; function TDSONPair.GetName: string; begin Result := FName; end; function TDSONPair.GetValue: IDSONValue; begin Result := FValue; end; procedure TDSONPair.SetName(const Value: string); begin FName := Value; end; procedure TDSONPair.SetValue(const Value: IDSONValue); begin FValue := Value; end; procedure TDSONObject.AddPair(const AName: string; AValue: IDSONValue); begin AddPair(TDSONPair.Create(AName, AValue)); end; procedure TDSONObject.AddPair(const APair: IDSONPair); begin FPairs.Add(APair); end; constructor TDSONObject.Create; begin FKind := dkObject; FPairs := TList<IDSONPair>.Create(TDSONPairNameComparer.Create); end; destructor TDSONObject.Destroy; begin FPairs.Free; inherited; end; function TDSONObject.GetPairs: TList<IDSONPair>; begin Result := FPairs; end; {TDSONPairNameComparer} function TDSONPairNameComparer.Compare(const Left, Right: IDSONPair): Integer; begin Result := CompareText(Left.Name, Right.Name); end; procedure TDSONBinaryWriter.InternalWriteArrayValue(const Value: IDSONArray); var ArrayValue: IDSONValue; begin WriteMarker(dmStartArray); for ArrayValue in Value.Values do begin WriteValue(ArrayValue); end; WriteMarker(dmEndArray); end; procedure TDSONBinaryWriter.InternalWriteBuffer(const Buffer: pointer; ACount: Integer); begin FStream.Write(Buffer^, ACount); end; procedure TDSONBinaryWriter.InternalWriteDateTime(const Value: IDSONSimple); var DateTime: TDateTime; begin DateTime := Value.Value.AsType<TDateTime>; FStream.Write(DateTime, Sizeof(DateTime)); end; procedure TDSONBinaryWriter.InternalWriteGuidValue(const Value: IDSONSimple); var GUID: TGUID; GUIDBytes: TBytes; begin {internally this is stored as a GUID string. When writing binary, write the 16 actual GUID bytes} GUID := TGUID.Create(Value.Value.AsString); GUIDBytes := GUID.ToByteArray; FStream.Write(GUIDBytes[0], Length(GUIDBytes)); end; procedure TDSONBinaryWriter.InternalWriteMarker(const AMarker: TDSONMarker); begin FStream.Write(AMarker, Sizeof(TDSONMarker)); end; procedure TDSONBinaryWriter.InternalWriteName(const AName: string); begin WriteString(AName); end; procedure TDSONBinaryWriter.InternalWriteObject(const ADsonObject: IDSONObject); var Pair: IDSONPair; begin WriteMarker(dmStartObject); for Pair in ADsonObject.Pairs do begin WritePair(Pair); end; WriteMarker(dmEndObject); end; procedure TDSONBinaryWriter.InternalWriteSimpleValue(const Value: IDSONSimple); var Buffer: pointer; begin WriteMarker(MarkerForSimpleKind(Value.Kind)); Buffer := Value.Value.GetReferenceToRawData; // Null, true and false are fully represented by the marker, nothing else needs to be written. case Value.Kind of dkNil: exit; dkByte: WriteBuffer(Buffer, 1); dkInt16: WriteBuffer(Buffer, 2); dkInt32: WriteBuffer(Buffer, 4); dkInt64: WriteBuffer(Buffer, 8); dkString: WriteString(Value.Value.AsString); dkSingle: WriteBuffer(Buffer, Sizeof(Single)); dkDouble: WriteBuffer(Buffer, Sizeof(Double)); dkExtended: WriteExtended(Value.Value); dkChar: WriteBuffer(Buffer, Sizeof(Char)); dkTrue: exit; dkFalse: exit; dkEnum: raise Exception.Create('Enums not supported'); {internally this is a unix date int64} dkDateTime: WriteDateTime(Value); dkGUID: WriteGUIDValue(Value); dkRecord: raise Exception.Create('Records not supported'); end; end; procedure TDSONBinaryWriter.InternalWriteString(const AValue: string); var Bytes: TBytes; Len: Integer; begin Bytes := TEncoding.UTF8.GetBytes(AValue); Len := Length(Bytes); FStream.Write(Len, Sizeof(Integer)); FStream.Write(Bytes[0], Length(Bytes)); end; procedure TDSONBinaryWriter.WriteExtended(const AValue: TValue); var Dbl: Double; begin // I don't like it but until I figure out a better way, Extended must be forced to Double // because Extended is so many different sizes on all platforms. Dbl := Double(AValue.AsExtended); FStream.Write(Dbl,Sizeof(Double)); end; function TDSONBinaryWriter.WriteObject(const ADsonObject: IDSONObject): TBytes; var BS: TBytesStream; begin BS := TBytesStream.Create; try WriteObjectToStream(ADsonObject, BS); SetLength(Result, BS.Size); Move(BS.Bytes[0], Result[0], BS.Size); finally BS.Free; end; end; constructor TDSONSimple.Create(const AValue: Boolean); begin if AValue then FKind := dkTrue else FKind := dkFalse; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Byte); begin FKind := dkByte; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Char); begin FKind := dkChar; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Cardinal); begin FKind := dkInt32; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Double); begin FKind := dkDouble; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Extended); begin FKind := dkExtended; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Integer); begin FKind := dkInt32; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Shortint); begin FKind := dkByte; FValue := TValue.From(AValue); end; {TDSONSimple} constructor TDSONSimple.Create(const AValue: Int64); begin FKind := dkInt64; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Smallint); begin FKind := dkInt16; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: string); begin FKind := dkString; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Single); begin FKind := dkSingle; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: TDateTime); begin FKind := dkDateTime; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: TGUID); begin FKind := dkGUID; {internal guid storage is a guid string} FValue := TValue.From(AValue.ToString); end; constructor TDSONSimple.Create(const AValue: TValue); begin FKind := DSONKindFromValue(AValue); FValue := AValue; end; constructor TDSONSimple.Create(const AValue: UInt64); begin FKind := dkInt64; FValue := TValue.From(AValue); end; constructor TDSONSimple.Create(const AValue: Word); begin FKind := dkInt16; FValue := TValue.From(AValue); end; constructor TDSONSimple.CreateNil; begin FKind := dkNil; FValue := TValue.From(nil); end; function TDSONSimple.DSONKindFromValue(const AValue: TValue): TDSONKind; begin case AValue.Kind of tkUnknown, tkSet, tkClass, tkMethod, tkVariant, tkArray, tkRecord, tkInterface, tkDynArray, tkClassRef, tkPointer, tkProcedure: raise Exception.Create('Too complex for a simple DSON type'); tkInteger: begin case AValue.DataSize of 1: Result := dkByte; 2: Result := dkInt16; 4: Result := dkInt32; end; end; tkChar: Result := dkChar; tkEnumeration: raise Exception.Create('Enums not supported yet'); tkFloat: begin case AValue.DataSize of 4: Result := dkSingle; 8: Result := dkDouble; end; end; tkString, tkLString, tkWString, tkUString: Result := dkString; tkWChar: Result := dkChar; tkInt64: Result := dkInt64; end; end; function TDSONSimple.GetValue: TValue; begin Result := FValue; end; function TDSONValue.GetKind: TDSONKind; begin Result := FKind; end; procedure TDSONValue.SetKind(const Value: TDSONKind); begin FKind := Value; end; {TDSONArray<T>} procedure TDSONArray.AddArrayValue(const AValue: IDSONValue); begin SetLength(FValues, Length(FValues) + 1); FValues[High(FValues)] := AValue; end; constructor TDSONArray.Create; begin FKind := dkArray; SetLength(FValues, 0); end; function TDSONArray.GetValues: TArray<IDSONValue>; begin Result := FValues; end; constructor TDSONBuilder.Create; begin FDsonObject := nil; FNameStack := TStack<String>.Create; FValueStack := TStack<IDSONValue>.Create; FStateStack := TStack<TBuilderState>.Create; end; destructor TDSONBuilder.Destroy; begin FStateStack.Free; FNameStack.Free; FValueStack.Free; inherited; end; function TDSONBuilder.AddNilValue: IDSONBuilder; begin FValueStack.Push(TDSONSimple.CreateNil); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddPair(const AName, AValue: string): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); Result := Self; end; function TDSONBuilder.AddPropertyName(const AName: string): IDSONBuilder; begin FNameStack.Push(AName); FStateStack.Push(bsExpectingValue); Result := Self; end; function TDSONBuilder.AddValue(const AValue: Boolean): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Byte): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Char): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Cardinal): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Double): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Extended): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Integer): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; {TDSONBuilder} function TDSONBuilder.AddValue(const AValue: Shortint): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Int64): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Smallint): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: string): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Single): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: TDateTime): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: TGUID): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: UInt64): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.AddValue(const AValue: Word): IDSONBuilder; begin FValueStack.Push(TDSONSimple.Create(AValue)); FinalizeSimpleValue; Result := Self; end; function TDSONBuilder.ArrayIsOnValueStack: Boolean; begin if (FValueStack.Count > 0) then Result := Supports(FValueStack.Peek, IDSONArray) else Result := false; end; function TDSONBuilder.CurrentState: TBuilderState; begin if FStateStack.Count = 0 then Result := bsReady else Result := FStateStack.Peek; end; function TDSONBuilder.EndArray: IDSONBuilder; begin FinalizeArrayValue; Result := Self; end; function TDSONBuilder.EndObject: IDSONBuilder; begin FinalizeObjectValue; Result := Self; end; procedure TDSONBuilder.FinalizeArrayValue; var DArr: IDSONArray; DObj: IDSONObject; Pair: IDSONPair; begin Pair := PopPair; if FStateStack.Peek = bsBuildingArray then begin if ObjectIsOnValueStack then begin DObj := FValueStack.Peek as IDSONObject; DObj.AddPair(Pair); end else if ArrayIsOnValueStack then begin // Array members don't have a property name. Since the property name has already been popped from // the name stack, it needs to be put back, and only the value needs to be added to the // parent array. This method could be refactored in such a way that only the value is popped. DArr := FValueStack.Peek as IDSONArray; DArr.AddArrayValue(Pair.Value); FNameStack.Push(Pair.Name); end else begin FDsonObject.AddPair(Pair); end; // Gotta pop the stack twice! Once for bsBuildingArray and once for bsExpectingValue FStateStack.Pop; if State = bsExpectingValue then FStateStack.Pop; end else raise Exception.Create('Cannot finalize array unless currently building array'); end; procedure TDSONBuilder.FinalizeObjectValue; var DArr: IDSONArray; DObj: IDSONObject; Pair: IDSONPair; begin if FStateStack.Count = 1 then begin // Finalizing the outer object. Pop the object off the value stack and assign it to FDSONObject. FDsonObject := FValueStack.Pop as IDSONObject; FStateStack.Pop; end else begin if FStateStack.Peek = bsBuildingObject then begin Pair := PopPair; if ObjectIsOnValueStack then begin DObj := FValueStack.Peek as IDSONObject; DObj.AddPair(Pair); end else if ArrayIsOnValueStack then begin // Array members don't have a property name. Since the property name has already been popped from // the name stack, it needs to be put back, and only the value needs to be added to the // parent array. This method could be refactored in such a way that only the value is popped. DArr := FValueStack.Peek as IDSONArray; DArr.AddArrayValue(Pair.Value); FNameStack.Push(Pair.Name); end else begin FDsonObject.AddPair(Pair); end; // Gotta pop the stack twice! Once for bsBuildingObject and once for bsExpectingValue FStateStack.Pop; if State = bsExpectingValue then FStateStack.Pop; end else raise Exception.Create('Cannot finalize object unless currently building object'); end; end; procedure TDSONBuilder.FinalizeSimpleValue; var Obj: IDSONObject; Pair: IDSONPair; Value: IDSONValue; begin if FStateStack.Peek = bsBuildingArray then begin Value := FValueStack.Pop; with (FValueStack.Peek as IDSONArray) do begin AddArrayValue(Value); end; end else if FStateStack.Peek = bsExpectingValue then begin Pair := PopPair; Obj := FValueStack.Peek as IDSONObject; Obj.AddPair(Pair); FStateStack.Pop; end else raise Exception.Create('Invalid builder state'); end; function TDSONBuilder.GetDSONOBject: IDSONObject; begin if FDSONObject = nil then raise Exception.Create('DSON Object not finished being built.'); Result := FDsonObject; end; function TDSONBuilder.GetState: TBuilderState; begin if FStateStack.Count = 0 then Result := bsReady else Result := FStateStack.Peek; end; function TDSONBuilder.ObjectIsOnValueStack: Boolean; begin if (FValueStack.Count > 0) then Result := Supports(FValueStack.Peek, IDSONObject) else Result := false; end; function TDSONBuilder.PopPair: IDSONPair; begin Result := TDSONPair.Create(FNameStack.Pop, FValueStack.Pop); end; function TDSONBuilder.StartArray: IDSONBuilder; begin FValueStack.Push(TDSONArray.Create); FStateStack.Push(bsBuildingArray); Result := Self; end; function TDSONBuilder.StartObject: IDSONBuilder; begin if FStateStack.Count = 0 then begin // Beginning new object. Clear FDSONObject. FDsonObject := nil; end; FValueStack.Push(TDSONObject.Create); FStateStack.Push(bsBuildingObject); Result := Self; end; function TDSONJSONWriter.DoubleQuoted(const AString: string): String; begin Result := '"' + AString + '"'; end; {TDSONJSONWriter} procedure TDSONJSONWriter.InternalWriteArrayValue(const Value: IDSONArray); var ArrayValue: IDSONValue; StreamPosition: Int64; begin WriteMarker(dmStartArray); StreamPosition := FStream.Position; for ArrayValue in Value.Values do begin WriteValue(ArrayValue); WriteString(','); end; if FStream.Position > StreamPosition then begin // Strip off the last comma FStream.Position := FStream.Position - 1; end; WriteMarker(dmEndArray); end; procedure TDSONJSONWriter.InternalWriteBuffer(const Buffer: pointer; ACount: Integer); begin FStream.Write(Buffer, ACount); end; procedure TDSONJSONWriter.InternalWriteDateTime(const Value: IDSONSimple); var DateString: string; begin DateString := DateToISO8601(Value.Value.AsType<TDateTime>,False); WriteString(DoubleQuoted(DateString)); end; procedure TDSONJSONWriter.InternalWriteGuidValue(const Value: IDSONSimple); begin WriteString(DoubleQuoted(Value.Value.AsString)); end; procedure TDSONJSONWriter.InternalWriteMarker(const AMarker: TDSONMarker); var MarkerStr: String; begin MarkerStr := MarkerToString(AMarker); WriteString(MarkerStr); end; procedure TDSONJSONWriter.InternalWriteName(const AName: string); begin WriteString(DoubleQuoted(AName) + ':'); end; procedure TDSONJSONWriter.InternalWriteObject(const ADsonObject: IDSONObject); var Pair: IDSONPair; begin WriteMarker(dmStartObject); for Pair in ADsonObject.Pairs do begin WritePair(Pair); if ADsonObject.Pairs.IndexOf(Pair) < ADsonObject.Pairs.Count - 1 then WriteString(','); end; WriteMarker(dmEndObject); end; procedure TDSONJSONWriter.InternalWriteSimpleValue(const Value: IDSONSimple); begin case Value.Kind of dkNil: WriteString('null'); dkTrue, dkFalse: WriteString(Value.Value.ToString.ToLower); dkByte, dkInt16, dkInt32, dkInt64, dkSingle, dkDouble, dkExtended: WriteString(Value.Value.ToString); dkChar, dkString: WriteString(DoubleQuoted(Value.Value.ToString)); dkEnum: raise Exception.Create('Enums not supported'); dkDateTime: WriteDateTime(Value); dkGUID: WriteGUIDValue(Value); dkRecord: raise Exception.Create('Records not supported'); end; end; procedure TDSONJSONWriter.InternalWriteString(const AValue: string); var Bytes: TBytes; begin Bytes := TEncoding.UTF8.GetBytes(AValue); FStream.Write(Bytes[0], Length(Bytes)); end; function TDSONJSONWriter.MarkerToString(const AMarker: TDSONMarker): string; begin case AMarker of dmNil, dmByte, dmInt16, dmInt32, dmInt64, dmString, dmSingle, dmDouble, dmExtended, dmChar, dmTrue, dmFalse, dmGUID: Result := ''; dmEnum: raise Exception.Create('Enums not yet supported'); dmRecord: raise Exception.Create('Records not yet supported'); dmStartArray: Result := '['; dmEndArray: Result := ']'; dmStartObject: Result := '{'; dmEndObject: Result := '}'; end; end; function TDSONJSONWriter.WriteObject(const ADsonObject: IDSONObject): string; var StrStream: TStringStream; begin StrStream := TStringStream.Create; try WriteObjectToStream(ADsonObject, StrStream); Result := StrStream.DataString; finally StrStream.Free; end; end; function TDSONWriter.MarkerForSimpleKind(ADsonKind: TDSONKind): TDSONMarker; begin case ADsonKind of dkNil: exit(dmNil); dkByte: exit(dmByte); dkInt16: Result := dmInt16; dkInt32: Result := dmInt32; dkInt64: Result := dmInt64; dkString: Result := dmString; dkSingle: Result := dmSingle; dkDouble: Result := dmDouble; dkExtended: Result := dmExtended; dkChar: Result := dmChar; dkTrue: Result := dmTrue; dkFalse: Result := dmFalse; dkEnum: Result := dmEnum; dkDateTime: Result := dmDateTime; dkGUID: Result := dmGUID; end; end; procedure TDSONWriter.WriteArrayValue(const Value: IDSONArray); begin InternalWriteArrayValue(Value); end; procedure TDSONWriter.WriteBuffer(const Buffer: pointer; ACount: Integer); begin InternalWriteBuffer(Buffer, ACount); end; procedure TDSONWriter.WriteDateTime(const Value: IDSONSimple); var UnixDate: Int64; begin InternalWriteDateTime(Value); end; procedure TDSONWriter.WriteGUIDValue(const Value: IDSONSimple); var GUID: TGUID; GUIDBytes: TBytes; begin InternalWriteGuidValue(Value); end; procedure TDSONWriter.WriteMarker(const AMarker: TDSONMarker); begin InternalWriteMarker(AMarker); end; procedure TDSONWriter.WriteName(const AName: string); begin InternalWriteName(AName); end; procedure TDSONWriter.WriteObjectToStream(const ADsonObject: IDSONObject; const AStream: TStream); begin FStream := AStream; InternalWriteObject(ADsonObject); end; procedure TDSONWriter.WritePair(const APair: IDSONPair); var Marker: TDSONMarker; Name: string; begin WriteMarker(dmStartPair); Name := APair.Name; // compiler friendly // Write name WriteName(Name); // Write value WriteValue(APair.Value); WriteMarker(dmEndPair); end; procedure TDSONWriter.WriteSimpleValue(const Value: IDSONSimple); begin InternalWriteSimpleValue(Value); end; procedure TDSONWriter.WriteString(const AValue: string); begin InternalWriteString(AValue); end; procedure TDSONWriter.WriteValue(const Value: IDSONValue); var Pair: IDSONPair; begin if Supports(Value, IDSONSimple) then WriteSimpleValue(Value as IDSONSimple) else if Supports(Value, IDSONArray) then WriteArrayValue(Value as IDSONArray) else if Supports(Value, IDSONObject) then WriteObjectToStream(Value as IDSONObject,FStream) else if Supports(Value, IDSONPair) then begin Pair := Value as IDSONPair; WriteName(Pair.Name); WriteValue(Pair.Value); end; end; {TDSONReader} constructor TDSONReader.Create; begin FStateStack := TStack<TReaderState>.Create; end; destructor TDSONReader.Destroy; begin FStateStack.Free; inherited; end; function TDSONReader.PeekMarker: TDSONMarker; begin Result := ReadMarker; FStream.Position := FStream.Position - Sizeof(TDSONMarker); end; function TDSONReader.ReadArray: IDSONArray; var Value: IDSONValue; begin Result := TDSONArray.Create; while PeekMarker <> dmEndArray do begin Value := ReadValue; Result.AddArrayValue(Value); end; ReadMarker; end; function TDSONReader.ReadDateTime: IDSONValue; var DateTime: TDateTime; begin // Date time is stored as a UNIX 64 bit value. FStream.Read(DateTime,Sizeof(DateTime)); Result := TDSONSimple.Create(DateTime); end; function TDSONReader.ReadExtended: IDSONValue; var Dbl: Double; begin // Extended is stored as double due to the wide variety of sizes extended has on different platforms. FStream.Read(Dbl,Sizeof(Double)); Result := TDSONSimple.Create(Extended(Dbl)); end; function TDSONReader.ReadGUID: IDSONValue; var Bytes: TBytes; GUID: TGUID; begin SetLength(Bytes,16); FStream.Read(Bytes[0],16); GUID := TGUID.Create(Bytes); Result := TDSONSimple.Create(GUID); end; function TDSONReader.ReadMarker: TDSONMarker; begin FStream.Read(Result, Sizeof(TDSONMarker)); end; function TDSONReader.ReadObject: IDSONObject; var Marker: TDSONMarker; Pair: TDSONPair; begin Marker := ReadMarker; if Marker = dmStartObject then begin Result := TDSONObject.Create; while PeekMarker <> dmEndObject do begin Pair := ReadPair; Result.AddPair(Pair); end; ReadMarker; end else raise Exception.Create('Expected a DSON Object Marker'); end; function TDSONReader.ReadObject(AStream: TStream): IDSONObject; begin FStream := AStream; Result := ReadObject; end; function TDSONReader.ReadPair: TDSONPair; var Name: string; Value: IDSONValue; begin if ReadMarker <> dmStartPair then raise Exception.Create('Expected to read dmStartPair marker'); Name := ReadPropertyName; Value := ReadValue; Result := TDSONPair.Create(Name, Value); if ReadMarker <> dmEndPair then raise Exception.Create('Expected to read dmEndPair marker'); end; function TDSONReader.ReadPropertyName: string; begin Result := ReadString; end; function TDSONReader.ReadSimple<T>: IDSONSimple; var Bytes: TBytes; Value: TValue; begin SetLength(Bytes,Sizeof(T)); FStream.Read(Bytes[0],Sizeof(T)); TValue.Make(Bytes,TypeInfo(T),Value); Result := TDSONSimple.Create(Value); end; function TDSONReader.ReadString: string; var Bytes: TBytes; Count: Integer; begin FStream.Read(Count, Sizeof(Integer)); SetLength(Bytes, Count); FStream.Read(Bytes[0], Count); Result := TEncoding.UTF8.GetString(Bytes); end; function TDSONReader.ReadValue: IDSONValue; var Marker: TDSONMarker; begin Marker := ReadMarker; case Marker of dmNil: Result := TDSONSimple.CreateNil; dmByte: Result := ReadSimple<Byte>; dmInt16: Result := ReadSimple<Int16>; dmInt32: Result := ReadSimple<Int32>; dmInt64: Result := ReadSimple<Int64>; dmString: Result := TDSONSimple.Create(ReadString); dmSingle: Result := ReadSimple<Single>; dmDouble: Result := ReadSimple<Double>; dmExtended: Result := ReadExtended; dmChar: Result := ReadSimple<Char>; dmTrue: Result := TDSONSimple.Create(True); dmFalse: Result := TDSONSimple.Create(False); dmEnum: raise Exception.Create('Enums not supported'); dmDateTime: Result := ReadDateTime; dmStartArray: Result := ReadArray; dmEndArray: raise Exception.Create('End-of-array marker should never be read here'); dmStartObject: begin // ReadObject expects to read the marker. FStream.Position := FStream.Position - Sizeof(TDSONMarker); Result := ReadObject; end; dmEndObject: raise Exception.Create('End-of-object marker should never be read here'); dmGUID: Result := ReadGUID; dmRecord: raise Exception.Create('records not supported') ; end; end; end.
unit ntvPanels; {** * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey * @ported ported from Lazarus component TSplitter in ExtCtrls *} {$mode objfpc}{$H+} {$define USE_NTV_THEME} interface uses SysUtils, Classes, Graphics, Controls, Variants, {$ifdef USE_NTV_THEME} ntvThemes, {$endif USE_NTV_THEME} LCLIntf, LCLType, GraphType; type { TntvCustomPanel } TntvResizeStyle = ( nrsNone, // draw nothing and don't update splitter position during moving nrsUpdate, // draw nothing, update splitter position during moving nrsLine // draw a line, don't update splitter position during moving ); TCanOffsetEvent = procedure(Sender: TObject; var NewOffset: Integer; var Accept: Boolean) of object; TCanResizeEvent = procedure(Sender: TObject; var NewSize: Integer; var Accept: Boolean) of object; TntvResizeBevel = (spsNone, spsSpace, spsLoweredLine, spsRaisedLine); TntvCustomPanel = class(TCustomControl) private FAutoSnap: Boolean; FMouseInControl: Boolean; FOnCanOffset: TCanOffsetEvent; FOnCanResize: TCanResizeEvent; FOnMoved: TNotifyEvent; FResizeStyle: TntvResizeStyle; FResizeBevel: TntvResizeBevel; FSplitDragging: Boolean; FSplitterSize: Integer; FSplitterPoint: TPoint; // in screen coordinates FSplitterStartPoint: TPoint; // in screen coordinates FSplitterWindow: HWND; procedure SetResizeBevel(AValue: TntvResizeBevel); procedure SetSplitterSize(AValue: Integer); protected procedure Paint; override; function CheckNewSize(var NewSize: Integer): Boolean; virtual; function CheckOffset(var NewOffset: Integer): Boolean; virtual; function CalcOffset(MousePos: TPoint): Integer; procedure MouseEnter; override; procedure MouseLeave; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure UpdateCursor(X, Y: Integer); function GetSplitterRect: TRect; procedure StartSplitterMove(const MousePos: TPoint); procedure StopSplitterMove(const MousePos: TPoint); procedure MoveSplitter(Offset: Integer); procedure AlignControls(AControl: TControl; var Rect: TRect); override; public constructor Create(TheOwner: TComponent); override; procedure Loaded; override; public property AutoSnap: Boolean read FAutoSnap write FAutoSnap default False; property ResizeBevel: TntvResizeBevel read FResizeBevel write SetResizeBevel default spsLoweredLine; property ResizeStyle: TntvResizeStyle read FResizeStyle write FResizeStyle default nrsNone; property SplitterSize: Integer read FSplitterSize write SetSplitterSize default 8; property OnCanOffset: TCanOffsetEvent read FOnCanOffset write FOnCanOffset; property OnCanResize: TCanResizeEvent read FOnCanResize write FOnCanResize; property OnMoved: TNotifyEvent read FOnMoved write FOnMoved; end; TntvPanel = class(TntvCustomPanel) published property OnResize; property Anchors; property Align; property Color; property Constraints; property Height; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property Width; property OnMoved; property OnChangeBounds; property OnCanOffset; property OnCanResize; property AutoSnap; property ResizeStyle; property SplitterSize; end; implementation uses Math; { TntvCustomPanel } procedure TntvCustomPanel.MoveSplitter(Offset: Integer); var aMinSize: Integer; aMaxSize: Integer; function GetParentClientSize: Integer; begin case Align of alLeft, alRight: Result := Parent.ClientWidth; alTop, alBottom: Result := Parent.ClientHeight; else Result := 0; end; end; function GetControlMinPos: Integer; begin case Align of alLeft, alRight: Result := Left; alTop, alBottom: Result := Top; else Result := 0; end; end; function GetControlSize: Integer; begin case Align of alLeft, alRight: Result := Width; alTop, alBottom: Result := Height; else Result := 0; end; end; function GetControlConstraintsMinSize: Integer; begin case Align of alLeft, alRight: Result := Constraints.EffectiveMinWidth; alTop, alBottom: Result := Constraints.EffectiveMinHeight; else Result := 0; end; end; function GetControlConstraintsMaxSize: Integer; begin case Align of alLeft, alRight: Result := Constraints.EffectiveMaxWidth; alTop, alBottom: Result := Constraints.EffectiveMaxHeight; else Result := 0; end; end; procedure SetAlignControlSize(NewSize: Integer); var NewBounds: TRect; begin NewBounds := BoundsRect; case Align of alLeft: NewBounds.Right := NewBounds.Left + NewSize; alRight: NewBounds.Left := NewBounds.Right - NewSize; alTop: NewBounds.Bottom := NewBounds.Top + NewSize; alBottom: NewBounds.Top := NewBounds.Bottom - NewSize; else ; end; BoundsRect := NewBounds; end; procedure DrawAlignControlSize(NewSize: Integer); var NewRect: TRect; OldSize: Integer; begin // get the splitter position NewRect := GetSplitterRect; NewRect.TopLeft := ClientToScreen(NewRect.TopLeft); NewRect.BottomRight := ClientToScreen(NewRect.BottomRight); OldSize := GetControlSize; case Align of alLeft: OffsetRect(NewRect, NewSize - OldSize, 0); alRight: OffsetRect(NewRect, OldSize - NewSize, 0); alTop: OffsetRect(NewRect, 0, NewSize - OldSize); alBottom: OffsetRect(NewRect, 0, OldSize - NewSize); else ; end; SetRubberBandRect(FSplitterWindow, NewRect); end; function CalcNewSize(MinSize, EndSize, Offset: Integer): Integer; var NewSize: Integer; begin NewSize := GetControlSize; case Align of alLeft: Inc(NewSize, Offset); alTop: Inc(NewSize, Offset); alRight: Dec(NewSize, Offset); alBottom: Dec(NewSize, Offset); else ; end; if NewSize > EndSize then NewSize := EndSize; if NewSize < MinSize then NewSize := MinSize; if AutoSnap and (NewSize < MinSize) then NewSize := MinSize; Result := NewSize; end; var NewSize: Integer; begin if Offset <> 0 then begin // calculate minimum size if not AutoSnap then aMinSize := GetControlConstraintsMinSize else aMinSize := 1; if aMinSize > 1 then Dec(aMinSize); // calculate maximum size case Align of alLeft, alTop: aMaxSize := GetControlSize - GetControlMinPos + (GetParentClientSize - GetControlSize); alRight, alBottom: aMaxSize := GetControlSize + GetControlMinPos + (GetParentClientSize - GetControlSize); else ; end; aMaxSize := Max(GetControlConstraintsMaxSize, aMaxSize); NewSize := CalcNewSize(aMinSize, aMaxSize, Offset); if CheckOffset(Offset) and CheckNewSize(NewSize) then if not FSplitDragging or (ResizeStyle = nrsUpdate) then begin SetAlignControlSize(NewSize); end else DrawAlignControlSize(NewSize); end; end; procedure TntvCustomPanel.AlignControls(AControl: TControl; var Rect: TRect); begin if FResizeStyle > nrsNone then case Align of alLeft, alRight: begin if Align = alLeft then Rect.Right := Rect.Right - SplitterSize else Rect.Left := Rect.Left + SplitterSize; end; alTop, alBottom: begin if Align = alTop then Rect.Bottom := Rect.Bottom - SplitterSize else Rect.Top := Rect.Top + SplitterSize; end; else ; end; inherited AlignControls(AControl, Rect); end; procedure TntvCustomPanel.SetResizeBevel(AValue: TntvResizeBevel); begin if FResizeBevel <> AValue then begin FResizeBevel := AValue; Invalidate; end; end; procedure TntvCustomPanel.SetSplitterSize(AValue: Integer); begin if FSplitterSize <> AValue then begin FSplitterSize := AValue; ReAlign; end; end; procedure TntvCustomPanel.StartSplitterMove(const MousePos: TPoint); var NewRect: TRect; P: TPoint; Pattern: HBrush; begin if not FSplitDragging then begin FSplitDragging := True; FSplitterPoint := MousePos; P := GetSplitterRect.TopLeft; case Align of alLeft: P.x := P.x + SplitterSize; //alRight: P.x := P.x + SplitterSize; alTop: P.y := P.y + SplitterSize; //alBottom: P.y := P.y - SplitterSize; else ; end; FSplitterStartPoint := ClientToParent(P); if ResizeStyle in [nrsLine] then begin NewRect := GetSplitterRect; NewRect.TopLeft := ClientToScreen(NewRect.TopLeft); NewRect.BottomRight := ClientToScreen(NewRect.BottomRight); Pattern := GetStockObject(BLACK_BRUSH); FSplitterWindow := CreateRubberband(NewRect, Pattern); end; end; end; procedure TntvCustomPanel.StopSplitterMove(const MousePos: TPoint); var Offset: Integer; begin if FSplitDragging then begin Offset := CalcOffset(MousePos); FSplitDragging := False; if Offset <> 0 then MoveSplitter(Offset); if Assigned(OnMoved) then OnMoved(Self); if ResizeStyle in [nrsLine] then DestroyRubberBand(FSplitterWindow); end; end; function TntvCustomPanel.GetSplitterRect: TRect; begin Result := ClientRect; case Align of alLeft: Result.Left := Result.Right - SplitterSize; alRight: Result.Right := Result.Left + SplitterSize; alTop: Result.Top := Result.Bottom - SplitterSize; alBottom: Result.Bottom := Result.Top + SplitterSize; else Result := Rect(0, 0, 0, 0); end; end; procedure TntvCustomPanel.UpdateCursor(X, Y: Integer); var R: TRect; begin R := GetSplitterRect; if FSplitDragging or PtInRect(R, Point(x, y)) then case Align of alLeft: Cursor := crHSplit; alRight: Cursor := crHSplit; alBottom: Cursor := crVSplit; alTop: Cursor := crVSplit; else Cursor := crDefault; end else Cursor := crDefault; end; procedure TntvCustomPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MousePos: TPoint; begin inherited; // While resizing X, Y are not valid. Use absolute mouse position. if Button = mbLeft then begin MousePos := Point(X, Y); GetCursorPos(MousePos); StartSplitterMove(MousePos); end; end; procedure TntvCustomPanel.MouseMove(Shift: TShiftState; X, Y: Integer); var Offset: Integer; MousePos: TPoint; begin inherited; if FResizeStyle > nrsNone then UpdateCursor(x, y); if (FSplitDragging) and (ssLeft in Shift) and (Parent <> nil) then begin MousePos := Point(X, Y); // While resizing X, Y are not valid. Use the absolute mouse position. GetCursorPos(MousePos); Offset := CalcOffset(MousePos); if Offset <> 0 then MoveSplitter(Offset); end; end; procedure TntvCustomPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MousePos: TPoint; begin inherited; MousePos := Point(X, Y); GetCursorPos(MousePos); StopSplitterMove(MousePos); end; function TntvCustomPanel.CheckNewSize(var NewSize: Integer): Boolean; begin Result := True; if Assigned(OnCanResize) then OnCanResize(Self, NewSize, Result); end; function TntvCustomPanel.CheckOffset(var NewOffset: Integer): Boolean; begin Result := True; if Assigned(OnCanOffset) then OnCanOffset(Self, NewOffset, Result); end; function TntvCustomPanel.CalcOffset(MousePos: TPoint): Integer; begin case Align of alLeft: Result := (MousePos.X - FSplitterPoint.X) - (BoundsRect.Right - FSplitterStartPoint.X); alRight: Result := (MousePos.X - FSplitterPoint.X) - (BoundsRect.Left - FSplitterStartPoint.X); alTop: Result := (MousePos.Y - FSplitterPoint.Y) - (BoundsRect.Bottom - FSplitterStartPoint.Y); alBottom: Result := (MousePos.Y - FSplitterPoint.Y) - (BoundsRect.Top - FSplitterStartPoint.Y); else Result := 0; end; end; procedure TntvCustomPanel.Paint; var C1, C2: TColor; p: Integer; begin inherited; if FResizeStyle > nrsNone then begin case ResizeBevel of spsRaisedLine: begin {$ifdef USE_NTV_THEME} C1 := Theme.Separator.Foreground; C2 := Theme.Separator.Background; {$else} C1 := clBtnHiLight; C2 := clBtnShadow; {$endif} end; spsLoweredLine: begin {$ifdef USE_NTV_THEME} C1 := Theme.Separator.Foreground; C2 := Theme.Separator.Background; {$else} C1 := clBtnShadow; C2 := clBtnHiLight; {$endif} end; else begin inherited; exit; end; end; Canvas.Pen.Width := 1; with Canvas, ClientRect do case Align of alTop, alBottom: begin if Align = alBottom then p := Top + SplitterSize div 2 else p := Bottom - SplitterSize div 2; Pen.Color := C1; MoveTo(Left, p); LineTo(Right - 1, p); Pen.Color := C2; MoveTo(Left, p + 1); LineTo(Right - 1, p + 1); end; alLeft, alRight: begin if Align = alRight then p := Left + SplitterSize div 2 else p := Right - SplitterSize div 2; Pen.Color := C1; MoveTo(p, Top); LineTo(p, Bottom - 1); Pen.Color := C2; MoveTo(p + 1, Top); LineTo(p + 1, Bottom - 1); end; else ; end; end; end; procedure TntvCustomPanel.MouseEnter; begin inherited; if not (csDesigning in ComponentState) then begin if not FMouseInControl and Enabled and (GetCapture = 0) then begin FMouseInControl := True; invalidate; end; end; end; procedure TntvCustomPanel.MouseLeave; begin inherited; if not (csDesigning in ComponentState) then begin if FMouseInControl then begin FMouseInControl := False; Cursor := crDefault; invalidate; end; end; end; constructor TntvCustomPanel.Create(TheOwner: TComponent); begin inherited Create(TheOwner); ControlStyle := ControlStyle + [csAcceptsControls, csCaptureMouse, csClickEvents, csDoubleClicks, csReplicatable, csNoFocus, csAutoSize0x0, csParentBackground] - [csOpaque]; FResizeStyle := nrsNone; FSplitterSize := 8; FAutoSnap := False; FMouseInControl := False; FResizeBevel := spsLoweredLine; with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); end; procedure TntvCustomPanel.Loaded; begin inherited Loaded; end; end.