text
stringlengths
14
6.51M
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Core; const DEFAULT_BG = clDefault; DEFAULT_FG = clDefault; ALERT_BG = clRed; ALERT_FG = clWhite; type { TFormPomodoro } TFormPomodoro = class(TForm) LabelInfo: TLabel; LabelPendingTime: TLabel; PanelPomodoro: TPanel; PomodoroTimer: TTimer; procedure FormCreate(Sender: TObject); procedure OnTickHandler(Sender: TObject); procedure ResetClick(Sender: TObject); procedure SetLabelsAndTitle; procedure SetColors; private Pomodoro: TPomodoro; end; var FormPomodoro: TFormPomodoro; implementation {$R *.lfm} { TFormPomodoro } procedure TFormPomodoro.FormCreate(Sender: TObject); begin Pomodoro := TPomodoro.Create; SetLabelsAndTitle; end; procedure TFormPomodoro.ResetClick(Sender: TObject); begin if Pomodoro.GetPendingSeconds > 0 then Exit; Pomodoro.StartNewPomodoro; FormPomodoro.Color := DEFAULT_BG; LabelPendingTime.Font.Color := DEFAULT_FG; LabelInfo.Font.Color := DEFAULT_FG; end; procedure TFormPomodoro.OnTickHandler(Sender: TObject); begin if LabelPendingTime.Caption = Pomodoro.GetFormattedTime then Exit; SetLabelsAndTitle; SetColors; end; procedure TFormPomodoro.SetLabelsAndTitle; begin LabelPendingTime.Caption := Pomodoro.GetFormattedTime; LabelInfo.Caption := Pomodoro.GetStatus; Caption := Pomodoro.GetTitle; end; procedure TFormPomodoro.SetColors; var BgColor, FgColor: TColor; PendingSeconds: integer; begin PendingSeconds := Pomodoro.GetPendingSeconds; if PendingSeconds > 0 then Exit; BgColor := DEFAULT_BG; FgColor := DEFAULT_FG; if PendingSeconds mod 2 <> 0 then begin BgColor := ALERT_BG; FgColor := ALERT_FG; end; FormPomodoro.Color := BgColor; LabelPendingTime.Font.Color := FgColor; LabelInfo.Font.Color := FgColor; end; end.
unit uBase_G; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBase, Vcl.Grids, Vcl.DBGrids, SMDBGrid, Data.Win.ADODB, Data.DB, Vcl.ToolWin, Vcl.ComCtrls, Vcl.Menus, RxMenus, Vcl.ExtCtrls, uMainDataSet, System.Actions, Vcl.ActnList, Vcl.ImgList, uDMConnection, uBase_E, Datasnap.Provider; type TBase_G = class(TBase) MainDBGrid: TSMDBGrid; MainPopupMenu: TPopupMenu; procedure OnGridGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure acEditUpdate(Sender: TObject); procedure acDeleteUpdate(Sender: TObject); procedure acEditExecute(Sender: TObject); procedure acDeleteExecute(Sender: TObject); procedure MainDBGridDblClick(Sender: TObject); procedure acNewExecute(Sender: TObject); procedure acNewUpdate(Sender: TObject); private FActFieldName: string; FEditFormClass: TObject; FEditFormInstance: TBase_E; FDMConnection: TDMConnection; procedure SetGridCellsFormat; protected function AddMenuItem(const aAction: TBasicAction; const aCaption: string; const aIcon: TImage = nil): TMenuItem; override; function CanEdit: Boolean; virtual; procedure CreateBaseMenuDef; override; procedure DoPrepare; override; procedure DoShow; override; public constructor Create(AOwner: TComponent); overload; override; constructor Create(AOwner: TComponent; aMainDataSet: TMainDataSet); overload; override; destructor Destroy; override; property EditFormClass: TObject read FEditFormClass write FEditFormClass; property EditFormInstance: TBase_E read FEditFormInstance write FEditFormInstance; procedure SetGridReadOnly; virtual; procedure UnsetGridReadOnly; virtual; end; implementation uses uDialogUtils, Datasnap.DBClient; {$R *.dfm} { TBase_G } procedure TBase_G.acDeleteExecute(Sender: TObject); begin inherited; if (TDialogUtils.ShowDeleteDialog(True).ModalResult = mrYes) then begin MainDataSet.Delete; MainDataSet.ApplyUpdates(-1); end else Exit; end; procedure TBase_G.acDeleteUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled := MainDataSet.RecordCount > 0; end; procedure TBase_G.acEditExecute(Sender: TObject); var lActualRowId: Integer; lMainDataSet: TMainDataSet; const cId = 'id'; begin inherited; if Assigned(FEditFormInstance) then begin if (FEditFormInstance is TBase_E) then begin lActualRowId := MainDataSet.FieldByName(cId).AsInteger; lMainDataSet := TMainDataSet.Create(Self); try TMainDataSet.CopyDataSet(MainDataSet, lMainDataSet); if not lMainDataSet.Active then lMainDataSet.Open; lMainDataSet.Filter := '(' + cId + '=' + IntToStr(lActualRowId) + ')'; lMainDataSet.Filtered := True; FEditFormInstance.MainDataSet := lMainDataSet; FEditFormInstance.MainDataSet.Open; FEditFormInstance.MainDataSource.DataSet := FEditFormInstance.MainDataSet; FEditFormInstance.FormState := esEdit; FEditFormInstance.ShowModal; // Refresh DataSet after save if FEditFormInstance.FormSaved then acRefreshExecute(Self); finally lMainDataSet.Free; end; end else raise Exception.Create('acEditExecute: EditFormInstance is not descendant of TBase_E.') end; end; procedure TBase_G.acEditUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled := CanEdit; end; procedure TBase_G.acNewExecute(Sender: TObject); var lMainDataSet: TMainDataSet; begin inherited; lMainDataSet := TMainDataSet.Create(Self); try TMainDataSet.CopyDataSet(MainDataSet, lMainDataSet); if not lMainDataSet.Active then lMainDataSet.Open; FEditFormInstance.MainDataSet := lMainDataSet; FEditFormInstance.MainDataSet.Open; FEditFormInstance.MainDataSource.DataSet := FEditFormInstance.MainDataSet; FEditFormInstance.MainDataSet.Append; FEditFormInstance.FormState := esInsert; FEditFormInstance.ShowModal; // Refresh DataSet after save if FEditFormInstance.FormSaved then acRefreshExecute(Self); finally lMainDataSet.Free; end; // Refresh DataSet after save if FEditFormInstance.FormSaved then acRefreshExecute(Self); end; procedure TBase_G.acNewUpdate(Sender: TObject); begin inherited; (Sender as TAction).Enabled := Assigned(FEditFormInstance); end; function TBase_G.AddMenuItem(const aAction: TBasicAction; const aCaption: string; const aIcon: TImage): TMenuItem; begin (*** Create TMenuItem with caption -> aName and with icon -> aIcon ***) inherited; Result := TMenuItem.Create(Self); Result.Action := aAction; Result.Caption := aCaption; end; constructor TBase_G.Create(AOwner: TComponent); begin raise Exception.Create('Constructor ''Create(AOwner: TComponent);'' cannot be called directly!'); end; function TBase_G.CanEdit: Boolean; begin Result := (MainDataSet.RecordCount > 0) and Assigned(FEditFormInstance); end; constructor TBase_G.Create(AOwner: TComponent; aMainDataSet: TMainDataSet); begin inherited; end; procedure TBase_G.CreateBaseMenuDef; var lMenuItem: TMenuItem; begin (*** Create base toolbar for grid ***) inherited; lMenuItem := AddMenuItem(acNew, 'Nový'); MainMenuDef.Items.Add(lMenuItem); lMenuItem := AddMenuItem(acEdit, 'Editovat'); MainMenuDef.Items.Add(lMenuItem); lMenuItem := AddMenuItem(acRefresh, 'Obnovit'); MainMenuDef.Items.Add(lMenuItem); lMenuItem := AddMenuItem(acDelete, 'Smazat'); MainMenuDef.Items.Add(lMenuItem); end; destructor TBase_G.Destroy; begin inherited; FreeAndNil(FDMConnection); end; procedure TBase_G.DoPrepare; begin inherited; SetGridReadOnly; SetGridCellsFormat; MainDBGrid.DataSource := MainDataSource; MainDBGrid.ReadOnly := False; end; procedure TBase_G.DoShow; begin inherited; if Assigned(Self.Parent) and (Self.Parent is TPanel) then Self.Align := alClient; end; procedure TBase_G.MainDBGridDblClick(Sender: TObject); begin inherited; if CanEdit then acEditExecute(Sender); end; procedure TBase_G.OnGridGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin Text := MainDataSet.FieldByName(FActFieldName).AsString; end; procedure TBase_G.SetGridCellsFormat; var i: Integer; begin (*** Set DB grid cells format [e.g. memo (in DB text)] ***) for i := 0 to MainDataSet.FieldCount-1 do begin if (LowerCase(MainDataSet.Fields[i].Text) = '(memo)') then begin FActFieldName := MainDataSet.Fields[i].FieldName; MainDataSet.Fields[i].OnGetText := OnGridGetText; end; end; end; procedure TBase_G.SetGridReadOnly; begin (*** Set DB grid read only ***) MainDBGrid.ReadOnly := True; end; procedure TBase_G.UnsetGridReadOnly; begin (*** Unset DB grid read only***) MainDBGrid.ReadOnly := False; 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 OraTriger; interface uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable; type TTrigger = class(TObject) private FOWNER, FTRIGGER_NAME, FTRIGGER_TYPE, FTRIGGERING_EVENT, FTABLE_OWNER, FBASE_OBJECT_TYPE, FTABLE_NAME, FCOLUMN_NAME, FREFERENCING_NAMES, FWHEN_CLAUSE, FSTATUS, FDESCRIPTION, FACTION_TYPE, FTRIGGER_BODY : string; FOraSession: TOraSession; function GetTrigerDetail: String; function GetTriggerStatus: string; function GetTriggerErrors: TVirtualTable; function GetUsedByList: TVirtualTable; function GetUsesList: TVirtualTable; public property OWNER: String read FOwner write FOwner; property TRIGGER_NAME: String read FTRIGGER_NAME write FTRIGGER_NAME; property TRIGGER_TYPE: String read FTRIGGER_TYPE write FTRIGGER_TYPE; property TRIGGERING_EVENT: String read FTRIGGERING_EVENT write FTRIGGERING_EVENT; property TABLE_OWNER: String read FTABLE_OWNER write FTABLE_OWNER; property BASE_OBJECT_TYPE: String read FBASE_OBJECT_TYPE write FBASE_OBJECT_TYPE; property TABLE_NAME: String read FTABLE_NAME write FTABLE_NAME; property COLUMN_NAME: String read FCOLUMN_NAME write FCOLUMN_NAME; property REFERENCING_NAMES: String read FREFERENCING_NAMES write FREFERENCING_NAMES; property WHEN_CLAUSE: String read FWHEN_CLAUSE write FWHEN_CLAUSE; property STATUS: String read FSTATUS write FSTATUS; property DESCRIPTION: String read FDESCRIPTION write FDESCRIPTION; property ACTION_TYPE: String read FACTION_TYPE write FACTION_TYPE; property TRIGGER_BODY: String read FTRIGGER_BODY write FTRIGGER_BODY; property TriggerStatus: String read GetTriggerStatus; property TriggerErrors: TVirtualTable read GetTriggerErrors; property UsedByList: TVirtualTable read GetUsedByList; property UsesList: TVirtualTable read GetUsesList; property OraSession: TOraSession read FOraSession write FOraSession; constructor Create; destructor Destroy; override; procedure SetDDL; function GetDDL: string; function CreateTrigger(TriggerScript: string) : boolean; function DropTrigger: boolean; function EnableTrigger: boolean; function DisableTrigger: boolean; function CompileTrigger: boolean; end; function GetOraTriggers: string; function GetTriggers(OwnerName: string): string; implementation uses Util, frmSchemaBrowser, OraScripts, Languages; resourcestring strTriggerCompiled = 'Trigger %s has been compiled.'; strTriggerDisabled = 'Trigger %s has been disabled.'; strTriggerEnabled = 'Trigger %s has been enabled.'; strTriggerDropped = 'Trigger %s has been dropped.'; strTriggerCreated = 'Trigger %s has been created.'; {**************************** TTriger **************************************} function GetTriggerErrorsSQL: string; begin result := 'SELECT LINE,POSITION,TEXT FROM ALL_ERRORS ' +'WHERE NAME = :pName ' +' AND OWNER = :pOwner ' +' AND TYPE = ''TRIGGER'' ' +' ORDER BY LINE,POSITION '; end; //schema browser išin function GetTriggers(OwnerName: string): string; begin result := 'select * from ALL_TRIGGERS ' +' where OWNER = '+Str(OwnerName) +' order by trigger_name '; end; function GetOraTriggers: string; begin result := 'Select t.trigger_name, t.trigger_type, t.triggering_event, ' +' t.when_clause, t.status, t.description, t.trigger_body, ' +' t.owner, o.object_id, o.CREATED, o.LAST_DDL_TIME ' +'from ALL_OBJECTS o, ALL_TRIGGERS t ' +'WHERE o.object_type = ''TRIGGER'' ' +' and o.object_name = t.trigger_name ' +' and t.table_name = :pName ' +' and t.BASE_OBJECT_TYPE = :pType ' +' and o.owner = t.owner ' +' and O.OWNER = :pOwner '; end; constructor TTrigger.Create; begin inherited; end; destructor TTrigger.destroy; begin inherited; end; function TTrigger.GetTrigerDetail: String; begin Result := 'Select * from ALL_TRIGGERS ' +'WHERE TRIGGER_NAME = :pName ' +' AND OWNER = :pOwner '; end; function TTrigger.GetTriggerStatus: string; var q1: TOraQuery; begin q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetObjectStatusSQL; q1.ParamByName('pOName').AsString := FTRIGGER_NAME; q1.ParamByName('pOType').AsString := 'TRIGGER'; q1.ParamByName('pOwner').AsString := FOWNER; q1.Open; result := FTRIGGER_NAME+' ( Created: '+q1.FieldByName('CREATED').AsString +' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString +' Status: '+q1.FieldByName('STATUS').AsString +' )'; q1.Close; end; function TTrigger.GetTriggerErrors: TVirtualTable; var q1: TOraQuery; begin result := TVirtualTable.Create(nil); q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetTriggerErrorsSQL; q1.ParamByName('pName').AsString := FTRIGGER_NAME; q1.ParamByName('pOwner').AsString := FOWNER; q1.Open; CopyDataSet(q1, result); q1.Close; end; function TTrigger.GetUsedByList: TVirtualTable; var q1: TOraQuery; begin result := TVirtualTable.Create(nil); q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetObjectUsedSQL; q1.ParamByName('pName').AsString := FTRIGGER_NAME; q1.ParamByName('pOwner').AsString := FOWNER; q1.ParamByName('pType').AsString := 'TRIGGER'; q1.Open; CopyDataSet(q1, result); q1.Close; end; function TTrigger.GetUsesList: TVirtualTable; var q1: TOraQuery; begin result := TVirtualTable.Create(nil); q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetObjectUsesSQL; q1.ParamByName('pName').AsString := FTRIGGER_NAME; q1.ParamByName('pOwner').AsString := FOWNER; q1.ParamByName('pType').AsString := 'TRIGGER'; q1.Open; CopyDataSet(q1, result); q1.Close; end; procedure TTrigger.SetDDL; var q1: TOraQuery; begin if FTRIGGER_NAME = '' then exit; if FOWNER = '' then exit; q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetTrigerDetail; q1.ParamByName('pName').AsString := FTRIGGER_NAME; q1.ParamByName('pOwner').AsString := FOWNER; q1.Open; FTRIGGER_TYPE := q1.FieldByName('TRIGGER_TYPE').AsString; FTRIGGERING_EVENT := q1.FieldByName('TRIGGERING_EVENT').AsString; FTABLE_OWNER := q1.FieldByName('TABLE_OWNER').AsString; FBASE_OBJECT_TYPE := q1.FieldByName('BASE_OBJECT_TYPE').AsString; FTABLE_NAME := q1.FieldByName('TABLE_NAME').AsString; FCOLUMN_NAME := q1.FieldByName('COLUMN_NAME').AsString; FREFERENCING_NAMES := q1.FieldByName('REFERENCING_NAMES').AsString; FWHEN_CLAUSE := q1.FieldByName('WHEN_CLAUSE').AsString; FSTATUS := q1.FieldByName('STATUS').AsString; FDESCRIPTION := q1.FieldByName('DESCRIPTION').AsString; FACTION_TYPE := q1.FieldByName('ACTION_TYPE').AsString; FTRIGGER_BODY := q1.FieldByName('TRIGGER_BODY').AsString; Q1.close; end; function TTrigger.GetDDL: string; begin with self do begin result := 'CREATE OR REPLACE TRIGGER ' +FDESCRIPTION +FWHEN_CLAUSE+ln +FTRIGGER_BODY+ln; if FSTATUS = 'DISABLED' then result := result +ln+ 'ALTER TRIGGER '+FOWNER+'.'+FTRIGGER_NAME+' DISABLE;'; end; end; function TTrigger.CreateTrigger(TriggerScript: string) : boolean; begin result := false; if FTRIGGER_NAME = '' then exit; result := ExecSQL(TriggerScript, Format(ChangeSentence('strTriggerCreated',strTriggerCreated),[FTRIGGER_NAME]), FOraSession); end; function TTrigger.DropTrigger: boolean; var FSQL: string; begin result := false; if FTRIGGER_NAME = '' then exit; FSQL := 'drop trigger '+FOWNER+'.'+FTRIGGER_NAME; result := ExecSQL(FSQL, Format(ChangeSentence('strTriggerDropped',strTriggerDropped),[FTRIGGER_NAME]), FOraSession); end; function TTrigger.EnableTrigger: boolean; var FSQL: string; begin result := false; if FTRIGGER_NAME = '' then exit; FSQL := 'alter trigger '+FOWNER+'.'+FTRIGGER_NAME+' enable'; result := ExecSQL(FSQL, Format(ChangeSentence('strTriggerEnabled',strTriggerEnabled),[FTRIGGER_NAME]), FOraSession); end; function TTrigger.DisableTrigger: boolean; var FSQL: string; begin result := false; if FTRIGGER_NAME = '' then exit; FSQL := 'alter trigger '+FOWNER+'.'+FTRIGGER_NAME+' disable'; result := ExecSQL(FSQL, Format(ChangeSentence('strTriggerDisabled',strTriggerDisabled),[FTRIGGER_NAME]), FOraSession); end; function TTrigger.CompileTrigger: boolean; var FSQL: string; begin result := false; if FTRIGGER_NAME = '' then exit; FSQL := 'alter trigger '+FOWNER+'.'+FTRIGGER_NAME+' compile'; result := ExecSQL(FSQL, Format(ChangeSentence('strTriggerCompiled',strTriggerCompiled),[FTRIGGER_NAME]), FOraSession); end; end.
unit uScaleControls; interface {$i jedi.inc} {$i BaseForms.inc} {$ifndef SUPPORTS_ENHANCED_RECORDS} {$define TIntScalerIsClass} {$endif} {$ifdef HAS_UNITSCOPE} uses System.Types, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Forms; {$else} uses Types, Classes, Graphics, Controls, StdCtrls, ComCtrls, Forms; {$endif} type TNCSize = record Width: Integer; Height: Integer; end; {$ifdef TIntScalerIsClass} TIntScaler = class {$else} TIntScaler = record {$endif} private FNewPPI: Integer; FOldPPI: Integer; public procedure Init(const ANewPPI, AOldPPI: Integer); {$ifdef SUPPORTS_INLINE}inline;{$endif} function Scale(const AValue: Integer): Integer; {$ifdef SUPPORTS_INLINE}inline;{$endif} function ScaleRect(const ARect: TRect): TRect; {$ifdef SUPPORTS_INLINE}inline;{$endif} function Upscaling: Boolean; {$ifdef SUPPORTS_INLINE}inline;{$endif} function Downscaling: Boolean; {$ifdef SUPPORTS_INLINE}inline;{$endif} property NewPPI: Integer read FNewPPI; property OldPPI: Integer read FOldPPI; end; TScaleCallbackProc = procedure (AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean); TScaleCallbackMethod = procedure (AControl: TControl; const AScaler: TIntScaler; var AHandled: Boolean) of object; PCLItem = ^TCLItem; TCLItem = record Method: TMethod; Next: PCLItem; end; TScaleControls = class private class function CastProcAsMethod(AProc: TScaleCallbackProc): TScaleCallbackMethod; {$ifdef SUPPORTS_INLINE}inline;{$endif} class procedure ProcessCallbacks(AControl: TControl; const AScaler: TIntScaler); private class procedure ScaleControlFont(AControl: TControl; const AScaler: TIntScaler); class procedure ScaleControlConstraints(AControl: TControl; const AScaler: TIntScaler); {$ifdef Controls_TMargins} class procedure ScaleControlMargins(AControl: TControl; const AScaler: TIntScaler); {$endif} {$ifdef Controls_OriginalParentSize} class procedure ScaleControlOriginalParentSize(AControl: TControl; const AScaler: TIntScaler); {$endif} class procedure ScaleControl(AControl: TControl; const AScaler: TIntScaler); class procedure ScaleWinControlDesignSize(AWinControl: TWinControl; const AScaler: TIntScaler); {$ifdef Controls_TPadding} class procedure ScaleWinControlPadding(AWinControl: TWinControl; const AScaler: TIntScaler); {$endif} class procedure ScaleWinControl(AWinControl: TWinControl; const AScaler: TIntScaler); class procedure ScaleScrollBars(AControl: TScrollingWinControl; const AScaler: TIntScaler); class procedure ScaleScrollingWinControl(AControl: TScrollingWinControl; const AScaler: TIntScaler); class procedure ScaleConstraintWithDelta(var AValue: TConstraintSize; const AScaler: TIntScaler; AOldCD, ANewCD: Integer); class procedure ScaleCustomFormConstraints(AConstraints: TSizeConstraints; const AScaler: TIntScaler; const AOldNCSize, ANewNCSize: TNCSize); class procedure ScaleCustomForm(ACustomForm: TCustomForm; const AScaler: TIntScaler); class procedure ScaleWinControlEx(AWinControl: TWinControl; const AScaler: TIntScaler); public class procedure RegisterScaleCallback(AProc: TScaleCallbackProc); overload; class procedure RegisterScaleCallback(AMethod: TScaleCallbackMethod); overload; class procedure UnregisterScaleCallback(AProc: TScaleCallbackProc); overload; class procedure UnregisterScaleCallback(AMethod: TScaleCallbackMethod); overload; class procedure Scale(AControl: TControl; const AScaler: TIntScaler); overload; class procedure Scale(AControl: TControl; ANewPPI, AOldPPI: Integer); overload; end; implementation uses {$ifdef HAS_UNITSCOPE} System.SysUtils, Winapi.Windows, {$else} SysUtils, Windows, {$endif} BaseForms; {$i BaseFormsFrndHackTypes.inc} type TFriendlyBaseForm = class(TBaseForm); { TIntScaler } procedure TIntScaler.Init(const ANewPPI, AOldPPI: Integer); begin FNewPPI := ANewPPI; FOldPPI := AOldPPI; end; function TIntScaler.Scale(const AValue: Integer): Integer; begin //Result := MulDiv(AValue, NewPPI, OldPPI); // <-- так inline не работает Result := (AValue * NewPPI) div OldPPI; end; function TIntScaler.ScaleRect(const ARect: TRect): TRect; begin Result.Left := Scale(ARect.Left); Result.Right := Scale(ARect.Right); Result.Top := Scale(ARect.Top); Result.Bottom := Scale(ARect.Bottom); end; function TIntScaler.Upscaling: Boolean; begin Result := NewPPI > OldPPI; end; function TIntScaler.Downscaling: Boolean; begin Result := NewPPI < OldPPI; end; { TScaleControls } var FCallbacksList: PCLItem; procedure FreeCallbacksList; var LCurItem, LNextItem: PCLItem; begin LCurItem := FCallbacksList; FCallbacksList := nil; while Assigned(LCurItem) do begin LNextItem := LCurItem.Next; Dispose(LCurItem); LCurItem := LNextItem; end; end; class function TScaleControls.CastProcAsMethod(AProc: TScaleCallbackProc): TScaleCallbackMethod; begin TMethod(Result).Code := nil; TMethod(Result).Data := @AProc; end; class procedure TScaleControls.RegisterScaleCallback(AProc: TScaleCallbackProc); begin RegisterScaleCallback(CastProcAsMethod(AProc)); end; class procedure TScaleControls.RegisterScaleCallback(AMethod: TScaleCallbackMethod); var LItem: PCLItem; begin New(LItem); LItem.Method := TMethod(AMethod); LItem.Next := FCallbacksList; FCallbacksList := LItem; end; class procedure TScaleControls.UnregisterScaleCallback(AProc: TScaleCallbackProc); begin UnregisterScaleCallback(CastProcAsMethod(AProc)); end; class procedure TScaleControls.UnregisterScaleCallback(AMethod: TScaleCallbackMethod); var LPrevItem, LCurItem: PCLItem; begin LPrevItem := nil; LCurItem := FCallbacksList; while Assigned(LCurItem) do begin //if LCurItem.Method = TMethod(AMethod) then if (LCurItem.Method.Code = TMethod(AMethod).Code) and (LCurItem.Method.Data = TMethod(AMethod).Data) then begin if not Assigned(LPrevItem) then // root item FCallbacksList := LCurItem.Next else // all others LPrevItem.Next := LCurItem.Next; Dispose(LCurItem); Exit; end; LPrevItem := LCurItem; LCurItem := LCurItem.Next; end; end; class procedure TScaleControls.ProcessCallbacks(AControl: TControl; const AScaler: TIntScaler); var LHandled: Boolean; LItem: PCLItem; begin LHandled := False; LItem := FCallbacksList; while Assigned(LItem) do begin if LItem.Method.Code = nil then TScaleCallbackProc(LItem.Method.Data)(AControl, AScaler, LHandled) else TScaleCallbackMethod(LItem.Method)(AControl, AScaler, LHandled); if LHandled then Exit; LItem := LItem.Next; end; end; class procedure TScaleControls.ScaleControlFont(AControl: TControl; const AScaler: TIntScaler); begin //EXIT; if TFriendlyControl(AControl).ParentFont then Exit; if (AControl is TCustomStatusBar) and TCustomStatusBar(AControl).UseSystemFont then Exit; with TFriendlyControl(AControl) do Font.Height := AScaler.Scale(Font.Height); end; class procedure TScaleControls.ScaleControlConstraints(AControl: TControl; const AScaler: TIntScaler); begin with THackSizeConstraints(AControl.Constraints) do begin FMaxHeight := AScaler.Scale(FMaxHeight); FMaxWidth := AScaler.Scale(FMaxWidth); FMinHeight := AScaler.Scale(FMinHeight); FMinWidth := AScaler.Scale(FMinWidth); end; //TFriendlySizeConstraints(Control.Constraints).Change; end; {$ifdef Controls_TMargins} class procedure TScaleControls.ScaleControlMargins(AControl: TControl; const AScaler: TIntScaler); begin with THackMargins(AControl.Margins) do begin FLeft := AScaler.Scale(FLeft); FTop := AScaler.Scale(FTop); FRight := AScaler.Scale(FRight); FBottom := AScaler.Scale(FBottom); end; //TFriendlyMargins(Control.Margins).Change; end; {$endif} {$ifdef Controls_OriginalParentSize} class procedure TScaleControls.ScaleControlOriginalParentSize(AControl: TControl; const AScaler: TIntScaler); begin with TFriendlyControl(AControl) do begin // scale OriginalParentSize - parent control size with it's padding bounds FOriginalParentSize.X := AScaler.Scale(FOriginalParentSize.X); FOriginalParentSize.Y := AScaler.Scale(FOriginalParentSize.Y); end; end; {$endif} class procedure TScaleControls.ScaleControl(AControl: TControl; const AScaler: TIntScaler); var LNewLeft, LNewTop, LNewWidth, LNewHeight: Integer; begin LNewLeft := AScaler.Scale(AControl.Left); LNewTop := AScaler.Scale(AControl.Top); if not (csFixedWidth in AControl.ControlStyle) then LNewWidth := AScaler.Scale(AControl.Left + AControl.Width) - LNewLeft else LNewWidth := AControl.Width; if not (csFixedHeight in AControl.ControlStyle) then LNewHeight := AScaler.Scale(AControl.Top + AControl.Height) - LNewTop else LNewHeight := AControl.Height; ScaleControlConstraints(AControl, AScaler); {$ifdef Controls_TMargins} ScaleControlMargins(AControl, AScaler); {$endif} ProcessCallbacks(AControl, AScaler); // apply new bounds (with check constraints and margins) AControl.SetBounds(LNewLeft, LNewTop, LNewWidth, LNewHeight); {$ifdef Controls_OriginalParentSize} ScaleControlOriginalParentSize(AControl, AScaler); {$endif} ScaleControlFont(AControl, AScaler); end; class procedure TScaleControls.ScaleWinControlDesignSize(AWinControl: TWinControl; const AScaler: TIntScaler); begin with TFriendlyWinControl(AWinControl) do begin FDesignSize.X := AScaler.Scale(FDesignSize.X); FDesignSize.Y := AScaler.Scale(FDesignSize.Y); end; end; {$ifdef Controls_TPadding} class procedure TScaleControls.ScaleWinControlPadding(AWinControl: TWinControl; const AScaler: TIntScaler); begin with THackPadding(AWinControl.Padding) do begin FLeft := AScaler.Scale(FLeft); FTop := AScaler.Scale(FTop); FRight := AScaler.Scale(FRight); FBottom := AScaler.Scale(FBottom); end; TFriendlyPadding(AWinControl.Padding).Change; end; {$endif} class procedure TScaleControls.ScaleWinControl(AWinControl: TWinControl; const AScaler: TIntScaler); begin ScaleControl(AWinControl, AScaler); ScaleWinControlDesignSize(AWinControl, AScaler); {$ifdef Controls_TPadding} ScaleWinControlPadding(AWinControl, AScaler); {$endif} end; class procedure TScaleControls.ScaleScrollBars(AControl: TScrollingWinControl; const AScaler: TIntScaler); begin with TFriendlyScrollingWinControl(AControl) do if not AutoScroll then begin with HorzScrollBar do begin Position := 0; Range := AScaler.Scale(Range); end; with VertScrollBar do begin Position := 0; Range := AScaler.Scale(Range); end; end; end; class procedure TScaleControls.ScaleScrollingWinControl(AControl: TScrollingWinControl; const AScaler: TIntScaler); begin ScaleScrollBars(AControl, AScaler); ScaleWinControl(AControl, AScaler); end; class procedure TScaleControls.ScaleConstraintWithDelta(var AValue: TConstraintSize; const AScaler: TIntScaler; AOldCD, ANewCD: Integer); var LResult: Integer; begin if AValue > 0 then begin LResult := AScaler.Scale(AValue - AOldCD) + ANewCD; if LResult < 0 then AValue := 0 else AValue := LResult; end; end; class procedure TScaleControls.ScaleCustomFormConstraints(AConstraints: TSizeConstraints; const AScaler: TIntScaler; const AOldNCSize, ANewNCSize: TNCSize); begin // при масштабировании констрейнтов формы, надо учитывать разницу // между внешними размерами и размерами клиентской области with THackSizeConstraints(AConstraints) do begin ScaleConstraintWithDelta(FMaxWidth, AScaler, AOldNCSize.Width, ANewNCSize.Width); ScaleConstraintWithDelta(FMinWidth, AScaler, AOldNCSize.Width, ANewNCSize.Width); ScaleConstraintWithDelta(FMaxHeight, AScaler, AOldNCSize.Height, ANewNCSize.Height); ScaleConstraintWithDelta(FMinHeight, AScaler, AOldNCSize.Height, ANewNCSize.Height); end; //TFriendlySizeConstraints(Constraints).Change; end; class procedure TScaleControls.ScaleCustomForm(ACustomForm: TCustomForm; const AScaler: TIntScaler); var LOldNCSize, LNewNCSize: TNCSize; LNewWidth, LNewHeight: Integer; begin LOldNCSize.Width := 0; LOldNCSize.Height := 0; LNewNCSize.Width := ACustomForm.Width - ACustomForm.ClientWidth; LNewNCSize.Height := ACustomForm.Height - ACustomForm.ClientHeight; if ACustomForm is TBaseForm then begin LOldNCSize.Width := TFriendlyBaseForm(ACustomForm).FNCWidth; LOldNCSize.Height := TFriendlyBaseForm(ACustomForm).FNCHeight; end; if LOldNCSize.Width = 0 then LOldNCSize.Width := LNewNCSize.Width; if LOldNCSize.Height = 0 then LOldNCSize.Height := LNewNCSize.Height; ScaleControlFont(ACustomForm, AScaler); LNewWidth := AScaler.Scale(ACustomForm.ClientWidth) + LNewNCSize.Width; LNewHeight := AScaler.Scale(ACustomForm.ClientHeight) + LNewNCSize.Height; ScaleWinControlDesignSize(ACustomForm, AScaler); ScaleScrollBars(ACustomForm, AScaler); ScaleCustomFormConstraints(ACustomForm.Constraints, AScaler, LOldNCSize, LNewNCSize); // При уменьшении размера иногда (пока не разбирался почему) новые размеры не применяются // Наращивание ширины и высоты на 1 пиксель помогает обойти такую проблему if AScaler.Downscaling then begin inc(LNewWidth); inc(LNewHeight); end; // apply new bounds (with check constraints and margins) with ACustomForm do SetBounds(Left, Top, LNewWidth, LNewHeight); end; class procedure TScaleControls.ScaleWinControlEx(AWinControl: TWinControl; const AScaler: TIntScaler); var LSavedAnchors: array of TAnchors; i: Integer; begin with AWinControl do begin // disable anchors of child controls: SetLength(LSavedAnchors, ControlCount); for i := 0 to ControlCount - 1 do begin LSavedAnchors[i] := Controls[i].Anchors; Controls[i].Anchors := [akLeft, akTop]; end; DisableAlign; try // scale itself: if AWinControl is TCustomForm then ScaleCustomForm(TCustomForm(AWinControl), AScaler) else if AWinControl is TScrollingWinControl then ScaleScrollingWinControl(TScrollingWinControl(AWinControl), AScaler) else ScaleWinControl(AWinControl, AScaler); // scale child controls: for i := 0 to ControlCount - 1 do Scale(Controls[i], AScaler); finally EnableAlign; // enable anchors of child controls: for i := 0 to ControlCount - 1 do Controls[i].Anchors := LSavedAnchors[i]; end; end; end; class procedure TScaleControls.Scale(AControl: TControl; const AScaler: TIntScaler); begin if AControl is TWinControl then ScaleWinControlEx(TWinControl(AControl), AScaler) else ScaleControl(AControl, AScaler); end; class procedure TScaleControls.Scale(AControl: TControl; ANewPPI, AOldPPI: Integer); var LScaler: TIntScaler; begin {$ifdef TIntScalerIsClass} LScaler := TIntScaler.Create; try {$endif} LScaler.Init(ANewPPI, AOldPPI); Scale(AControl, LScaler); {$ifdef TIntScalerIsClass} finally LScaler.Free; end; {$endif} end; initialization finalization FreeCallbacksList; end.
unit AMixer; // NO! (nearly impossible) : Support for control on/off (alternative for mute) - this is present on Audigy 2 interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, MMSystem; (* * TAudioMixer v1.70 (FREEWARE component) * ----------------- * Released 6 Jun 2005 * * This component can cache data from audio mixer. It has direct support for * getting/setting volume of any control (It can set also set state of that * "Selected" CheckBox in standard Windows Volume Control program). You can * better use other features of mixer, but that's more difficult than volume * setting and you must know something about audio mixer. * * The mixer has following structure (as it is in this component) : * * Destinations (destinations should be for example: Playback, Recording and Voice commands) * | * |--Destination[0] (if you want to get volume of this call GeVolume (<ThisDestinationNum>,-1,...)) * | | (=0) ---- * | |--Data:TMixerLine * | |--Controls (controls of the line, ex: Master volume, master mute) * | | | * | | |--Control[0] * | | |--Control[1] * | | |--Control[..] * | | * | |--Connections (ex: Wave, MIDI, CD Audio, Line-In,...) * | | * | |--Connection[0] (GetVolume (<ThisDestinationNum>,<ThisConnectionNum>,...)) * | | | (=0) (=0) * | | |--Data:TMixerLine * | | |--Controls (here can be volume and mute) * | | | * | | |--Control[0] * | | |--Control[1] * | | |--Control[..] * | | * | |--Connection[1] * | |--Connection[..] * | * |--Destination[1] * |--Destination[..] * * * There are many types of controls - checkbox, list, slider,... they are * described in Windows help. Common ones are volume slider, mute checkbox or * volume meter. * * This component is universal, so you can work with all controls through it, * but this is difficult. You can simply get/set volume level by procedures * GetVolume or SetVolume (description is near their declaration; use - see * example program). * * * What's New * ---------- * 1.70 (6 Jun 2005) * - fix: In the GetPeak method the allocated memory doesn't get released if the soundcard * doesn't support peak levels. * (by Thaddy de Koning - http://members.chello.nl/t.koning8/kolindex.htm ) * - new : Example now shows if connection is stereo or mono * - fix: Problem with connections that have both "mute" and "selected" control, for example * Conexant AMC Audio. Now the "selected" control is preffered over "mute", which * is the opposite behaviour when compared to the previous version. * Hopefully it will still work on other soundcards :-) * (big thanks to Mike Versteeg, again :-) ) * 1.60 (18 Nov 2001) * - destinations will not be nil, when there is no mixer in the system * (Mike Versteeg) * - if mixerOpen function fails, it will try to call it again without * (not needed) MIXER_OBJECTF_MIXER flag and if this will not work either, * the component will call it once more without setting callback * (we will lose [volume,...] change notification, but at least there * is a possibility that it will work) * (Mike Versteeg) * - stereo mute is now working correctly (this was often problem * on Windows XP) (Big thanks to Miroslav Flesko and several users of his * program Radiator who informed me about an error and then helped me * to find the solution) * 1.51 (6 May 2001) * - corrected problem with infinite cycle and many small bugs, * which could cause to report some control as "without mute" * although they have it (this bug probably arose when * I tried to correct SetVolume, GetVolume, ...) * 1.50 (not released, I knew there were some errors) * - corrected SetVolume, GetVolume, SetMute, GetMute * - added parameter in GetVolume - MuteIsSelect (by Ing. Ladislav Dolezel) * 1.43 (23 Oct 2000) * - changes in example - now it fully supports multiple sound cards * and it has better bass/treble dialog (by Hans-Georg Joepgen) * 1.42 (16 Oct 2000) * - example corrections (there was an exception when closing Form4 and * wrong text on one of the buttons) (by Hans-Georg Joepgen) * 1.41 (12 Jul 2000) * - the component is more safe (you can query for destination * number 100000 and you will receive nil insead of exception :-) ) * (by Sergey Kuzmin) * - specifying wrong mixer number will cause procedure SetMixerID to fail * instead finding nearest mixer * (also thanks goes to Sergey Kuzmin) * 1.4 (2 Jun 2000) * - added some examples * - great improvements by Fabrice Fouqet : * - added properties FDriverVersion, FManufacturer, FProductId, * FNumberOfLine and FProductName * - added functions GetMute/SetMute and GetPeak * - changed function GetVolume (also returns if selected control * is stereo or mono) * 1.16 (20 May 1999) * - made compatible with Delphi 2.0 (this was done by Tom Lisjac) * 1.15 (17 May 1999) * - corrected "Windows couldn't be shut down while TAudioMixer is being used" problem * (many thanks to Jean Carlo Solis Ubago, who fixed this) * - added example showing how to set bass / treble * 1.12 (24 Mar 1999) * - corrected setting "selected" state * 1.11 (4 Jan 1999) * - now it supports also MIXERCONTROL_CONTROLTYPE_MUX flag * (I got SB Live! for Christmas (:-)) and my component didn't work * properly, this corrects that problem) * 1.1 (16 Nov 1998) * - made compatible with Delphi 4 * - corrected memory leaks (by Ishida Wataru) * - some another minor changes (by Ishida Wataru) * - added another example * - added AMixer.dcr * 1.0 (18 Aug 1998) * - initial version * * * You can use this component freely in your programs. But if you do so, please * send me an e-mail. I would like to know if it is useful. * * (C) Vit Kovalcik * * e-mail: vit.kovalcik@volny.cz * WWW: http://www.fi.muni.cz/~xkovalc * (if it will not work try http://www.geocities.com/vkovalcik ) *) type TAudioMixer=class; TPListFreeItemNotify=procedure (Pntr:Pointer) of object; TMixerChange=procedure (Sender:TObject;MixerH:HMixer;ID:Integer) of object; {MixerH is handle of mixer, which sent this message. ID is ID of changed item (line or control).} TPointerList=class(TObject) private FOnFreeItem:TPListFreeItemNotify; Items:Tlist; protected function GetPointer (Ind:Integer):Pointer; function GetCount :integer; public constructor Create; destructor Destroy; override; procedure Clear; procedure Add (Pntr:Pointer); property Count:Integer read GetCount; property Pointer[Ind:Integer]:Pointer read GetPointer; default; property OnFreeItem:TPListFreeItemNotify read FOnFreeItem write FOnFreeItem; end; TMixerControls=class(TObject) private heap:pointer; FControls:TPointerList; protected function GetControl (Ind:Integer):PMixerControl; function GetCount:Integer; public constructor Create (AMixer:TAudioMixer; AData:TMixerLine); destructor Destroy; override; property Control[Ind:Integer]:PMixerControl read GetControl; default; property Count:Integer read GetCount; end; TMixerConnection=class(TObject) private XMixer:TAudioMixer; FData:TMixerLine; FControls:TMixerControls; public constructor Create (AMixer:TAudioMixer; AData:TMixerLine); destructor Destroy; override; property Controls:TMixerControls read FControls; property Data:TMixerLine read FData; end; TMixerConnections=class(TObject) private XMixer:TAudioMixer; FConnections:TPointerList; protected procedure DoFreeItem (Pntr:Pointer); function GetConnection (Ind:Integer):TMixerConnection; function GetCount:Integer; public constructor Create (AMixer:TAudioMixer; AData:TMixerLine); destructor Destroy; override; property Connection[Ind:Integer]:TMixerConnection read GetConnection; default; property Count:Integer read GetCount; end; TMixerDestination=class(TObject) private XMixer:TAudioMixer; FData:TMixerLine; FControls:TMixerControls; FConnections:TMixerConnections; public constructor Create (AMixer:TAudioMixer; AData:TMixerLine); destructor Destroy; override; property Connections:TMixerConnections read FConnections; property Controls:TMixerControls read FControls; property Data:TMixerLine read FData; end; TMixerDestinations=class(TObject) private FDestinations:TPointerList; protected function GetDestination (Ind:Integer):TMixerDestination; procedure DoFreeItem (Pntr:Pointer); function GetCount:Integer; public constructor Create (AMixer:TAudioMixer); destructor Destroy; override; property Count:Integer read GetCount; property Destination[Ind:Integer]:TMixerDestination read GetDestination; default; end; TAudioMixer = class(TComponent) private XWndHandle:HWnd; FDestinations:TMixerDestinations; FMixersCount:Integer; FMixerHandle:HMixer; FMixerId:Integer; FMixerCaps:TMixerCaps; FDriverVersion: MMVERSION; FManufacturer: String; FProductId: Word; FNumberOfLine: Integer; FProductName: String; FOnLineChange:TMixerChange; FOnControlChange:TMixerChange; protected procedure SetMixerId (Value:Integer); procedure MixerCallBack (var Msg:TMessage); procedure CloseMixer; published constructor Create (AOwner:TComponent); override; destructor Destroy; override; property DriverVersion: MMVERSION read FDriverVersion; property ProductId: WORD read FProductId; property NumberOfLine: Integer read FNumberOfLine; property Manufacturer: string read FManufacturer; property ProductName: string read FProductName; property MixerId:Integer read FMixerId write SetMixerId; {Opened mixer - value must be in range 0..MixersCount-1 If no mixer is opened this value is -1} property OnLineChange:TMixerChange read FOnLineChange write FOnLineChange; property OnControlChange:TMixerChange read FOnControlChange write FOnControlChange; public function GetVolume (ADestination, AConnection:Integer; var LeftVol, RightVol, Mute:Integer; var Stereo, VolDisabled, MuteDisabled, MuteIsSelect:Boolean):Boolean; {This function return volume of selected Destination and Connection. ADestination must be from range 0..Destinations.Count-1 AConnection must be in range 0..Destinations[ADestination].Connections.Count-1 If you want to read master volume of some Destination, you have to set AConnection to -1. If LeftVol, RightVol or Mute is not supported by queried connection, it's return value will be -1. LeftVol and RightVol are in range 0..65536 If Mute is non-zero then the connection is silent (or vice-versa - see MuteIsSelect parameter) If specified line is recording source then Mute specifies if programs will record from this connection (it is copy of "Select" Checkbox in standard Windows Volume Control program) Stereo is true, then this control is stereo. VolDisabled or MuteDisabled is True when you cannot apply settings to this control (but can read it). MuteIsSelect returns True is "mute" work here as select - opposite of mute. Return value of the function is True if no error has occured, otherwise it returns False.} function SetVolume (ADestination, AConnection:Integer; LeftVol, RightVol, Mute:Integer):Boolean; {This function sets volume. If you set RightVol to -1 and connection is stereo then LeftVol will be copied to RightVol. If LeftVol or Mute is -1 then this value will not be set. Note that "Mute" can be "select" (which is reversed mute) - see function GetVolume, parameter MuteIsSelect. Return value is True if ADestination and AConnection are correct, otherwise False.} function GetPeak(ADestination, AConnection:Integer; var LeftPeak, RightPeak:Integer):Boolean; function GetMute(ADestination, AConnection:Integer; var Mute:Boolean):Boolean; function SetMute(ADestination, AConnection:Integer; Mute:Boolean):Boolean; property Destinations:TMixerDestinations read FDestinations; {Ind must be in range 0..DestinationsCount-1} property MixerCaps:TMixerCaps read FMixerCaps; property MixerCount:Integer read FMixersCount; {Number of mixers present in system; mostly 1} property MixerHandle:HMixer read FMixerHandle; {Handle of opened mixer} end; procedure Register; implementation uses UPrincipale; {------------} {TPointerList} {------------} constructor TPointerList.Create; begin Items := TList.Create; end; destructor TPointerList.Destroy; begin Clear; Items.Free; end; procedure TPointerList.Add (Pntr:Pointer); begin Items.Add (Pntr); end; function TPointerList.GetPointer (Ind:Integer):Pointer; begin Result := nil; If (Ind < Count) then Result := Items[Ind]; end; procedure TPointerList.Clear; var I:Integer; begin for I := 0 to Items.Count-1 do begin If Assigned (FOnFreeItem) then FOnFreeItem (Items[I]) end; Items.Clear; end; function TPointerList.GetCount:Integer; begin Result := Items.Count; end; {--------------} {TMixerControls} {--------------} constructor TMixerControls.Create (AMixer:TAudioMixer; AData:TMixerLine); var MLC:TMixerLineControls; A,B:Integer; P:PMixerControl; begin FControls := TPointerList.Create; GetMem (P, SizeOf(TMixerControl)*AData.cControls); heap := P; MLC.cbStruct := SizeOf(MLC); MLC.dwLineID := AData.dwLineID; MLC.cbmxctrl := SizeOf(TMixerControl); MLC.cControls := AData.cControls; MLC.pamxctrl := P; A := MixerGetLineControls(AMixer.MixerHandle, @MLC, MIXER_GETLINECONTROLSF_ALL); If A = MMSYSERR_NOERROR then begin For B := 0 to AData.cControls-1 do begin FControls.Add (P); P := PMixerControl (DWORD(P) + sizeof (TMixerControl)); end; end; end; destructor TMixerControls.Destroy; begin FControls.free; freemem(heap); inherited; end; function TMixerControls.GetControl (Ind:Integer):PMixerControl; begin Result := FControls.Pointer[Ind]; end; function TMixerControls.GetCount:Integer; begin Result := FControls.Count; end; {----------------} {TMixerConnection} {----------------} constructor TMixerConnection.Create (AMixer:TAudioMixer; AData:TMixerLine); begin FData := AData; XMixer := AMixer; FControls := TMixerControls.Create (AMixer, AData); end; destructor TMixerConnection.Destroy; begin FControls.Free; inherited; end; {-----------------} {TMixerConnections} {-----------------} constructor TMixerConnections.Create (AMixer:TAudioMixer; AData:TMixerLine); var A,B:Integer; ML:TMixerLine; begin XMixer := AMixer; FConnections := TPointerList.Create; FConnections.OnFreeItem := Dofreeitem; ML.cbStruct := SizeOf(TMixerLine); ML.dwDestination := AData.dwDestination; For A := 0 to AData.cConnections-1 do begin ML.dwSource := A; B := MixerGetLineInfo (AMixer.MixerHandle, @ML, MIXER_GETLINEINFOF_SOURCE); If B = MMSYSERR_NOERROR then FConnections.Add (Pointer(TMixerConnection.Create (XMixer, ML))); end; end; destructor TMixerConnections.Destroy; begin FConnections.Free; inherited; end; procedure TMixerConnections.DoFreeItem (Pntr:Pointer); begin TMixerConnection(Pntr).Free; end; function TMixerConnections.GetConnection (Ind:Integer):TMixerConnection; begin Result := FConnections.Pointer[Ind]; end; function TMixerConnections.GetCount:Integer; begin Result := FConnections.Count; end; {-----------------} {TMixerDestination} {-----------------} constructor TMixerDestination.Create (AMixer:TAudioMixer; AData:TMixerLine); begin FData := AData; XMixer := AMixer; FConnections := TMixerConnections.Create (XMixer, FData); FControls := TMixerControls.Create (XMixer, AData); end; destructor TMixerDestination.Destroy; begin Fcontrols.Free; FConnections.Free; inherited; end; {------------------} {TMixerDestinations} {------------------} constructor TMixerDestinations.Create (AMixer:TAudioMixer); var A,B:Integer; ML:TMixerLine; begin FDestinations := TPointerList.Create; FDestinations.OnFreeItem := DoFreeItem; if (AMixer = nil) then Exit; For A := 0 to AMixer.MixerCaps.cDestinations-1 do begin ML.cbStruct := SizeOf(TMixerLine); ML.dwDestination := A; B := MixerGetLineInfo (AMixer.MixerHandle, @ML, MIXER_GETLINEINFOF_DESTINATION); If B = MMSYSERR_NOERROR then FDestinations.Add (Pointer(TMixerDestination.Create (AMixer, ML))); end; end; procedure TMixerDestinations.DoFreeItem (Pntr:Pointer); begin TMixerDestination(Pntr).Free; end; destructor TMixerDestinations.Destroy; begin FDestinations.Free; inherited; end; function TMixerDestinations.GetDestination (Ind:Integer):TMixerDestination; begin Result := nil; If (Assigned (FDestinations)) then Result := FDestinations.Pointer[Ind]; end; function TMixerDestinations.GetCount:Integer; begin Result := FDestinations.Count; end; {-----------} {TAudioMixer} {-----------} constructor TAudioMixer.Create (AOwner:TComponent); begin inherited Create (AOwner); XWndHandle := AllocateHWnd (MixerCallBack); FMixersCount := mixerGetNumDevs; FMixerId := -1; if (FMixersCount = 0) then FDestinations := TMixerDestinations.Create (nil) else begin FDestinations := nil; SetMixerId (0); end; end; destructor TAudioMixer.Destroy; begin CloseMixer; if XWndHandle <> 0 then DeAllocateHwnd (XWndHandle); inherited; end; procedure TAudioMixer.CloseMixer; begin If FMixerId >= 0 then begin mixerClose (FMixerHandle); FMixerId := -1; end; FDestinations.Free; FDestinations := nil; end; procedure TAudioMixer.SetMixerId (Value:Integer); label AllOK; begin If (Value < 0) OR (Value >= FMixersCount) then Exit; CloseMixer; If mixerOpen (@FMixerHandle, Value, XWndHandle, 0, CALLBACK_WINDOW OR MIXER_OBJECTF_MIXER) = MMSYSERR_NOERROR then goto AllOK; // we will go here very rarely, but sometimes it could help If mixerOpen (@FMixerHandle, Value, XWndHandle, 0, CALLBACK_WINDOW) = MMSYSERR_NOERROR then goto AllOK; If mixerOpen (@FMixerHandle, Value, 0, 0, 0) = MMSYSERR_NOERROR then goto AllOK; // an error has occured FMixerId := -1; FDestinations := TMixerDestinations.Create (nil); Exit; AllOK: FMixerId := Value; mixerGetDevCaps (MixerId, @FMixerCaps, SizeOf (TMixerCaps)); if FMixerCaps.wMid = MM_MICROSOFT then FManufacturer := 'Microsoft' else FManufacturer := IntToStr(FMixerCaps.wMid) + ' = Unknown'; FDriverVersion := FMixerCaps.vDriverVersion; FProductId := FMixerCaps.wPid; FProductName := StrPas(FMixerCaps.szPName); FNumberOfLine := FMixerCaps.cDestinations; FDestinations := TMixerDestinations.Create (Self); end; procedure TAudioMixer.MixerCallBack (var Msg:TMessage); begin case Msg.Msg of MM_MIXM_LINE_CHANGE: If Assigned (OnLineChange) then OnLineChange (Self, Msg.wParam, Msg.lParam); MM_MIXM_CONTROL_CHANGE: If Assigned (OnControlChange) then OnControlChange (Self, Msg.wParam, Msg.lParam); else Msg.Result := DefWindowProc (XWndHandle, Msg.Msg, Msg.WParam, Msg.LParam); end; end; const MIXER_LONG_NAME_CHARS = 64; type MIXERCONTROLDETAILS_LISTTEXT = record dwParam1:DWORD; dwParam2:DWORD; szName:Array [0..MIXER_LONG_NAME_CHARS-1] of Char; end; type ListTextArray = array [0..1000] of MIXERCONTROLDETAILS_LISTTEXT; function TAudioMixer.GetVolume (ADestination,AConnection:Integer;var LeftVol, RightVol, Mute:Integer;var Stereo, VolDisabled, MuteDisabled, MuteIsSelect:Boolean):Boolean; var MD:TMixerDestination; MC:TMixerConnection; Cntrls:TMixerControls; MCD:TMixerControlDetails; Cntrl:PMixerControl; A,B:Integer; ML:TMixerLine; details:array [0..100] of Integer; ltext:^ListTextArray; MCDText:TMixerControlDetails; begin Result := False; If (not Assigned (FDestinations)) then Exit; Stereo := False; MuteDisabled := True; VolDisabled := True; LeftVol := -1; RightVol := -1; Mute := -1; MuteIsSelect := False; MD := Destinations[ADestination]; MC := nil; If AConnection <> -1 then MC := MD.Connections[AConnection]; If MD <> nil then begin Result := True; // If Mute = -1 then begin If AConnection <> -1 then begin Cntrls := MD.Controls; ML := MD.Data; If (MC <> nil) AND (Cntrls <> nil) then begin A := 0; while (Mute = -1) AND (A < Cntrls.Count) do begin Cntrl := Cntrls[A]; // If (Cntrl.dwControlType AND MIXERCONTROL_CONTROLTYPE_MIXER = MIXERCONTROL_CONTROLTYPE_MIXER) OR // (Cntrl.dwControlType AND MIXERCONTROL_CONTROLTYPE_MUX = MIXERCONTROL_CONTROLTYPE_MUX) then // If (Cntrl.dwControlType AND MIXERCONTROL_CT_CLASS_MASK = MIXERCONTROL_CT_CLASS_LIST) then If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX) then // Mux is similar to mixer, but only one line can be selected at a time begin MCD.cbStruct := SizeOf(TMixerControlDetails); MCD.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then MCD.cChannels := 1 else MCD.cChannels := ML.cChannels; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE = MIXERCONTROL_CONTROLF_MULTIPLE then MCD.cMultipleItems := Cntrl.cMultipleItems else MCD.cMultipleItems := 0; MCD.cbDetails := 4; MCD.paDetails := @Details; B := mixerGetControlDetails (FMixerHandle,@MCD,MIXER_GETCONTROLDETAILSF_VALUE); If B <> MMSYSERR_NOERROR then begin Inc (A); continue; end; MCDText.cbStruct := sizeof (MCDText); MCDText.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then MCDText.cChannels := 1 else MCDText.cChannels := ML.cChannels; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE = MIXERCONTROL_CONTROLF_MULTIPLE then MCDText.cMultipleItems := Cntrl.cMultipleItems else MCDText.cMultipleItems := 0; GetMem (ltext, MCDText.cChannels * MCDText.cMultipleItems * sizeof (MIXERCONTROLDETAILS_LISTTEXT)); MCDText.cbDetails := sizeof (MIXERCONTROLDETAILS_LISTTEXT); MCDText.paDetails := ltext; B := mixerGetControlDetails (FMixerHandle, @MCDText, MIXER_GETCONTROLDETAILSF_LISTTEXT); If B <> MMSYSERR_NOERROR then begin FreeMem (ltext); Inc (A); continue; end; B := MCD.cChannels - 1; while (B < integer(MCD.cMultipleItems)) do begin if (ltext[B].dwParam1 = MC.Data.dwLineID) then break; Inc (B, MCD.cChannels); end; FreeMem (ltext); If (B < integer (MCD.cMultipleItems)) then begin Mute := Details[B]; MuteDisabled := Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_DISABLED > 0; MuteIsSelect := True; break; end; end; Inc (A); end; end; end; end; If AConnection = -1 then begin Cntrls := MD.Controls; ML := MD.Data; end else begin If MC <> nil then begin Cntrls := MC.Controls; ML := MC.Data; end else Cntrls := nil; end; If Cntrls <> nil then begin A := 0; while ((LeftVol = -1) OR (Mute = -1)) AND (A < Cntrls.Count) do begin Cntrl := Cntrls[A]; If Cntrl <> nil then begin If ((Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME) OR ((Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE) AND (Mute = -1))) AND (Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE <> MIXERCONTROL_CONTROLF_MULTIPLE) then begin if (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE) then MCD.cbStruct := SizeOf(TMixerControlDetails) else MCD.cbStruct := SizeOf(TMixerControlDetails); MCD.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then MCD.cChannels := 1 else MCD.cChannels := ML.cChannels; MCD.cMultipleItems := 0; MCD.cbDetails := SizeOf(Integer); MCD.paDetails := @details; B := mixerGetControlDetails (FMixerHandle, @MCD, MIXER_GETCONTROLDETAILSF_VALUE); If B = MMSYSERR_NOERROR then begin If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME) AND (LeftVol = -1) then begin VolDisabled := Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_DISABLED > 0; LeftVol := details[0]; If MCD.cChannels > 1 then begin RightVol := Details[1]; Stereo := True; end else RightVol := LeftVol; end else If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE) AND (Mute = -1) then begin MuteDisabled := Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_DISABLED > 0; If Details[0] <> 0 then Mute := 1 else Mute := 0; end // NEW -> (* else If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_ONOFF) AND (Mute = -1) then begin MuteDisabled := Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_DISABLED > 0; If Details[0] <> 0 then Mute := 1 else Mute := 0; MuteIsSelect := True; end;*) // <- NEW end; end; end; Inc (A); end; { If LeftVol = -1 then VolDisabled := True; If Mute = -1 then MuteDisabled := True;} end; end; end; function TAudioMixer.SetVolume (ADestination, AConnection:Integer; LeftVol, RightVol, Mute:Integer):Boolean; var MD:TMixerDestination; MC:TMixerConnection; Cntrls:TMixerControls; MCD:TMixerControlDetails; Cntrl:PMixerControl; A,B:Integer; ML:TMixerLine; details:array [0..100] of Integer; VolSet,MuteSet:Boolean; ltext:^ListTextArray; MCDText:TMixerControlDetails; begin Result := False; If (not Assigned (FDestinations)) then Exit; MC := nil; MD := Destinations[ADestination]; If MD <> nil then begin If AConnection <> -1 then MC := MD.Connections[AConnection]; VolSet := LeftVol = -1; MuteSet := Mute = -1; Result := True; If not MuteSet then begin If AConnection <> -1 then begin Cntrls := MD.Controls; ML := MD.Data; If (MC <> nil) AND (Cntrls <> nil) then begin A := 0; while not MuteSet AND (A < Cntrls.Count) do begin Cntrl := Cntrls[A]; If (*(Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MIXER) OR*) (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX) then begin MCD.cbStruct := SizeOf(TMixerControlDetails); MCD.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then MCD.cChannels := 1 else MCD.cChannels := ML.cChannels; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE = MIXERCONTROL_CONTROLF_MULTIPLE then MCD.cMultipleItems := Cntrl.cMultipleItems else MCD.cMultipleItems := 0; MCD.cbDetails := 4; MCD.paDetails := @Details; MuteSet := True; mixerGetControlDetails (FMixerHandle, @MCD, MIXER_GETCONTROLDETAILSF_VALUE); if (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX) then For B := 0 to Cntrl.cMultipleItems-1 do Details[B] := 0; GetMem (ltext, MCD.cChannels * MCD.cMultipleItems * sizeof (MIXERCONTROLDETAILS_LISTTEXT)); MCDText.cbStruct := sizeof (MCDText); MCDText.dwControlID := Cntrl.dwControlID; MCDText.cChannels := MCD.cChannels; MCDText.cMultipleItems := MCD.cMultipleItems; MCDText.cbDetails := sizeof (MIXERCONTROLDETAILS_LISTTEXT); MCDText.paDetails := ltext; mixerGetControlDetails (FMixerHandle, @MCDText, MIXER_GETCONTROLDETAILSF_LISTTEXT); B := MCD.cChannels - 1; while (B < integer (MCD.cMultipleItems)) do begin if (ltext[B].dwParam1 = MC.Data.dwLineID) then break; Inc (B, MCD.cChannels); end; FreeMem (ltext); If (B < integer (MCD.cMultipleItems)) then begin Details[B] := Mute; mixerSetControlDetails (FMixerHandle, @MCD, MIXER_GETCONTROLDETAILSF_VALUE); break; end; end; Inc (A); end; end; end; end; If AConnection = -1 then begin Cntrls := MD.Controls; ML := MD.Data; end else begin If MC <> nil then begin Cntrls := MC.Controls; ML := MC.Data; end else Cntrls := nil; end; If Cntrls <> nil then begin A := 0; while (not VolSet OR not MuteSet) AND (A < Cntrls.Count) do begin Cntrl := Cntrls[A]; If Cntrl <> nil then begin If (((Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME) AND not VolSet) OR ((Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE) AND not MuteSet) (* NEW -> *) (*OR ((Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_ONOFF) AND not MuteSet)*) (* <- NEW *)) AND (Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE <> MIXERCONTROL_CONTROLF_MULTIPLE) then begin MCD.cbStruct := SizeOf(TMixerControlDetails); MCD.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then MCD.cChannels := 1 else MCD.cChannels := ML.cChannels; MCD.cMultipleItems := 0; MCD.cbDetails := SizeOf(Integer); MCD.paDetails := @Details; If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME) then begin Details[0] := LeftVol; If RightVol = -1 then Details[1] := LeftVol else Details[1] := RightVol; VolSet := True; end else if ((Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUTE) (* NEW -> *) (* OR (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_ONOFF) *) (* <- NEW *)) then begin For B := 0 to MCD.cChannels - 1 do Details[B] := Mute; MuteSet := True; end; mixerSetControlDetails (FMixerHandle, @MCD, MIXER_GETCONTROLDETAILSF_VALUE); end; end; Inc (A); end; end; end; end; function TAudioMixer.GetMute(ADestination, AConnection: Integer; var Mute: Boolean):Boolean; var MD : TMixerDestination; MC : TMixerConnection; mlcMixerLineControlsMute : TMIXERLINECONTROLS; mcdMixerDataMute : TMIXERCONTROLDETAILS; pmcMixerControlMute : PMIXERCONTROL; pmcdsMixerDataUnsignedMute : PMIXERCONTROLDETAILSBOOLEAN; mlMixerLine : TMixerLine; Cntrl:PMixerControl; Cntrls:TMixerControls; ML:TMixerLine; A,B:Integer; details:array [0..100] of Integer; ltext:^ListTextArray; MCDText:TMixerControlDetails; begin Result := False; If (not Assigned (FDestinations)) then Exit; MC := nil; Mute := False; MD := Destinations[ADestination]; if MD <> nil then begin if AConnection = -1 then mlMixerLine := MD.Data else begin MC := MD.Connections[AConnection]; if MC <> nil then mlMixerLine := MC.Data else Exit; end; GetMem(pmcMixerControlMute, SizeOf(TMIXERCONTROL)); GetMem(pmcdsMixerDataUnsignedMute, SizeOf(TMIXERCONTROLDETAILSBOOLEAN)); with mlcMixerLineControlsMute do begin cbStruct := SizeOf(TMIXERLINECONTROLS); dwLineID := mlMixerLine.dwLineID; dwControlType := MIXERCONTROL_CONTROLTYPE_MUTE; cControls := 1; cbmxctrl := SizeOf(TMIXERCONTROL); pamxctrl := pmcMixerControlMute; end; if (mixerGetLineControls(FMixerHandle, @mlcMixerLineControlsMute, MIXER_GETLINECONTROLSF_ONEBYTYPE) = MMSYSERR_NOERROR) then begin with mcdMixerDataMute do begin cbStruct := SizeOf(TMIXERCONTROLDETAILS); dwControlID := pmcMixerControlMute^.dwControlID; cChannels := 1; cMultipleItems := 0; cbDetails := SizeOf(TMIXERCONTROLDETAILSBOOLEAN); paDetails := pmcdsMixerDataUnsignedMute; end; if mixerGetControlDetails(FMixerHandle, @mcdMixerDataMute, MIXER_GETCONTROLDETAILSF_VALUE) = MMSYSERR_NOERROR then begin Mute := pmcdsMixerDataUnsignedMute^.fValue = 1; Result := True; end; end else begin If (AConnection <> -1) then begin Cntrls := MD.Controls; ML := MD.Data; If (MC <> nil) AND (Cntrls <> nil) then begin A := 0; while (Result = False) AND (A < Cntrls.Count) do begin Cntrl := Cntrls[A]; If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MIXER) OR (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX) then begin mcdMixerDataMute.cbStruct := SizeOf(TMixerControlDetails); mcdMixerDataMute.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then mcdMixerDataMute.cChannels := 1 else mcdMixerDataMute.cChannels := ML.cChannels; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE = MIXERCONTROL_CONTROLF_MULTIPLE then mcdMixerDataMute.cMultipleItems := Cntrl.cMultipleItems else mcdMixerDataMute.cMultipleItems := 0; mcdMixerDataMute.cbDetails := 4; mcdMixerDataMute.paDetails := @Details; mixerGetControlDetails (FMixerHandle, @mcdMixerDataMute, MIXER_GETCONTROLDETAILSF_VALUE); GetMem (ltext, mcdMixerDataMute.cChannels * mcdMixerDataMute.cMultipleItems * sizeof (MIXERCONTROLDETAILS_LISTTEXT)); MCDText.cbStruct := sizeof (MCDText); MCDText.dwControlID := Cntrl.dwControlID; MCDText.cChannels := mcdMixerDataMute.cChannels; MCDText.cMultipleItems := mcdMixerDataMute.cMultipleItems; MCDText.cbDetails := sizeof (MIXERCONTROLDETAILS_LISTTEXT); MCDText.paDetails := ltext; mixerGetControlDetails (FMixerHandle, @MCDText, MIXER_GETCONTROLDETAILSF_LISTTEXT); B := mcdMixerDataMute.cChannels - 1; while (B < integer (mcdMixerDataMute.cMultipleItems)) do begin if (ltext[B].dwParam1 = MC.Data.dwLineID) then break; Inc (B, mcdMixerDataMute.cChannels); end; FreeMem (ltext); If (B < integer (mcdMixerDataMute.cMultipleItems)) then begin Result := True; Mute := Details[B] <> 0; break; end; end; Inc (A); end; end; end; end; FreeMem(pmcdsMixerDataUnsignedMute); FreeMem(pmcMixerControlMute); end; end; function TAudioMixer.SetMute(ADestination, AConnection: Integer; Mute: Boolean):Boolean; var MD : TMixerDestination; MC : TMixerConnection; mlcMixerLineControlsMute : TMIXERLINECONTROLS; mcdMixerDataMute : TMIXERCONTROLDETAILS; pmcMixerControlMute : PMIXERCONTROL; pmcdsMixerDataUnsignedMute : PMIXERCONTROLDETAILSBOOLEAN; mlMixerLine : TMixerLine; Cntrl:PMixerControl; Cntrls:TMixerControls; ML:TMixerLine; A,B:Integer; details:array [0..100] of Integer; ltext:^ListTextArray; MCDText:TMixerControlDetails; begin Result := False; If (not Assigned (FDestinations)) then Exit; MC := nil; MD := Destinations[ADestination]; if MD <> nil then begin if AConnection = -1 then mlMixerLine := MD.Data else begin MC := MD.Connections[AConnection]; if MC <> nil then mlMixerLine := MC.Data else Exit; end; GetMem(pmcMixerControlMute, SizeOf(TMIXERCONTROL)); GetMem(pmcdsMixerDataUnsignedMute, SizeOf(TMIXERCONTROLDETAILSBOOLEAN)); with mlcMixerLineControlsMute do begin cbStruct := SizeOf(TMIXERLINECONTROLS); dwLineID := mlMixerLine.dwLineID; dwControlType := MIXERCONTROL_CONTROLTYPE_MUTE; cControls := 0; cbmxctrl := SizeOf(TMIXERCONTROL); pamxctrl := pmcMixerControlMute; end; if (mixerGetLineControls(FMixerHandle, @mlcMixerLineControlsMute, MIXER_GETLINECONTROLSF_ONEBYTYPE) = MMSYSERR_NOERROR) then begin with mcdMixerDataMute do begin cbStruct := SizeOf(TMixerControlDetails); dwControlID := pmcMixerControlMute^.dwControlID; cChannels := 1; cMultipleItems := 0; cbDetails := SizeOf(TMIXERCONTROLDETAILSBOOLEAN); paDetails := pmcdsMixerDataUnsignedMute; end; if Mute then pmcdsMixerDataUnsignedMute^.fValue := 1 else pmcdsMixerDataUnsignedMute^.fValue := 0; if (mixerSetControlDetails(FMixerHandle,@mcdMixerDataMute,MIXER_SETCONTROLDETAILSF_VALUE) = MMSYSERR_NOERROR) then Result := True; end else begin If (AConnection <> -1) then begin Cntrls := MD.Controls; ML := MD.Data; If (MC <> nil) AND (Cntrls <> nil) then begin A := 0; while (Result = False) AND (A < Cntrls.Count) do begin Cntrl := Cntrls[A]; If (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MIXER) OR (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX) then begin mcdMixerDataMute.cbStruct := SizeOf(TMixerControlDetails); mcdMixerDataMute.dwControlID := Cntrl.dwControlID; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_UNIFORM > 0 then mcdMixerDataMute.cChannels := 1 else mcdMixerDataMute.cChannels := ML.cChannels; If Cntrl.fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE = MIXERCONTROL_CONTROLF_MULTIPLE then mcdMixerDataMute.cMultipleItems := Cntrl.cMultipleItems else mcdMixerDataMute.cMultipleItems := 0; mcdMixerDataMute.cbDetails := 4; mcdMixerDataMute.paDetails := @Details; if (mixerGetControlDetails (FMixerHandle, @mcdMixerDataMute, MIXER_GETCONTROLDETAILSF_VALUE) <> MMSYSERR_NOERROR) then begin Inc (A); continue; end; if (Cntrl.dwControlType = MIXERCONTROL_CONTROLTYPE_MUX) then For B := 0 to Cntrl.cMultipleItems-1 do Details[B] := 0; If Mute then begin GetMem (ltext, mcdMixerDataMute.cChannels * mcdMixerDataMute.cMultipleItems * sizeof (MIXERCONTROLDETAILS_LISTTEXT)); MCDText.cbStruct := sizeof (MCDText); MCDText.dwControlID := Cntrl.dwControlID; MCDText.cChannels := mcdMixerDataMute.cChannels; MCDText.cMultipleItems := mcdMixerDataMute.cMultipleItems; MCDText.cbDetails := sizeof (MIXERCONTROLDETAILS_LISTTEXT); MCDText.paDetails := ltext; mixerGetControlDetails (FMixerHandle, @MCDText, MIXER_GETCONTROLDETAILSF_LISTTEXT); B := mcdMixerDataMute.cChannels - 1; while (B < integer (mcdMixerDataMute.cMultipleItems)) do begin if (ltext[B].dwParam1 = MC.Data.dwLineID) then break; Inc (B, mcdMixerDataMute.cChannels); end; FreeMem (ltext); If (B < integer (mcdMixerDataMute.cMultipleItems)) then Details[B] := 1; end; if (mixerSetControlDetails (FMixerHandle, @mcdMixerDataMute, MIXER_GETCONTROLDETAILSF_VALUE) = MMSYSERR_NOERROR) then begin Result := True; break; end; end; Inc (A); end; end; end; end; FreeMem(pmcdsMixerDataUnsignedMute); FreeMem(pmcMixerControlMute); end; end; function TAudioMixer.GetPeak (ADestination, AConnection:Integer; var LeftPeak, RightPeak:Integer): Boolean; var MD : TMixerDestination; MC : TMixerConnection; mcdMixerDataPeak : TMIXERCONTROLDETAILS; pmcMixerControlPeak : PMIXERCONTROL; { pmcdsMixerDataSignedPeak : PMIXERCONTROLDETAILSSIGNED;} mlMixerLine : TMixerLine; A:Integer; Cntrls:TMixerControls; Details:Array [1..100] of Integer; begin Result := False; If (not Assigned (FDestinations)) then Exit; LeftPeak := 0; RightPeak := 0; MD := Destinations[ADestination]; if MD <> nil then begin if AConnection = -1 then begin mlMixerLine := MD.Data; Cntrls := MD.Controls; end else begin MC := MD.Connections[AConnection]; if MC <> nil then begin mlMixerLine := MC.Data; Cntrls := MC.Controls; end else Exit; end; GetMem(pmcMixerControlPeak, SizeOf(TMIXERCONTROL)); A := 0; while (A < Cntrls.Count) do begin If (Cntrls[A].dwControlType AND MIXERCONTROL_CT_CLASS_MASK) = MIXERCONTROL_CT_CLASS_METER then break; Inc (A); end; If A = Cntrls.Count then begin FreeMem(pmcMixerControlPeak); Exit; end; with mcdMixerDataPeak do begin cbStruct := SizeOf(TMIXERCONTROLDETAILS); dwControlID := Cntrls[A].dwControlID; cChannels := mlMixerLine.cChannels; If (Cntrls[A].fdwControl AND MIXERCONTROL_CONTROLF_MULTIPLE) = MIXERCONTROL_CONTROLF_MULTIPLE then cMultipleItems:=Cntrls[A].cMultipleItems else cMultipleItems:=0; cbDetails := SizeOf(TMIXERCONTROLDETAILSSIGNED); paDetails := @Details; end; if (mixerGetControlDetails(FMixerHandle,@mcdMixerDataPeak,MIXER_GETCONTROLDETAILSF_VALUE) = MMSYSERR_NOERROR) then begin LeftPeak := Details[1]; if mlMixerLine.cChannels = 2 then RightPeak := Details[2] else RightPeak := LeftPeak; Result := True; end; FreeMem(pmcMixerControlPeak); end; end; procedure Register; begin RegisterComponents('Samples', [TAudioMixer]); 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 9:36:30 PM JPMugaas Updated ref. Rev 1.4 4/19/2004 5:05:26 PM JPMugaas Class rework Kudzu wanted. Rev 1.3 2004.02.03 5:45:20 PM czhower Name changes Rev 1.2 24/01/2004 19:20:06 CCostelloe Cleaned up warnings Rev 1.1 10/19/2003 2:27:14 PM DSiders Added localization comments. Rev 1.0 2/19/2003 02:02:12 AM JPMugaas Individual parsing objects for the new framework. } unit IdFTPListParseHellSoft; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListParseNovellNetware; { This parser works just like Novell Netware's except that the detection is different. HellSoft made a freeware FTP Server for Novell Netware in the early 1990's for Novell Netware 3 and 4. It is still somewhat in use in some Eastern parts of Europ. } type TIdHellSoftFTPListItem = class(TIdNovellNetwareFTPListItem); TIdFTPLPHellSoft = class(TIdFTPLPNovellNetware) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): 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 "IdFTPListParseHellSoft"'*) implementation uses IdException, IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPHellSoft } class function TIdFTPLPHellSoft.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; function IsHellSoftLine(const AData : String) : Boolean; var LPerms : String; begin Result := AData <> ''; if Result then begin Result := CharIsInSet(AData, 1, 'dD-'); {do not localize} if Result then begin //we have to be careful to distinguish between Hellsoft and //NetWare Print Services for UNIX, FTP File Transfer Service LPerms := ExtractNovellPerms(Copy(AData, 1, 12)); Result := (Length(LPerms) = 7) and IsValidNovellPermissionStr(LPerms); end; end; end; begin Result := False; if AListing.Count > 0 then begin if IsTotalLine(AListing[0]) then begin Result := (AListing.Count > 1) and IsHellSoftLine(AListing[1]); end else begin Result := IsHellSoftLine(AListing[0]); end; end; end; class function TIdFTPLPHellSoft.GetIdent: String; begin Result := 'Hellsoft'; {do not localize} end; class function TIdFTPLPHellSoft.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdHellSoftFTPListItem.Create(AOwner); end; initialization RegisterFTPListParser(TIdFTPLPHellSoft); finalization UnRegisterFTPListParser(TIdFTPLPHellSoft); end.
program odbc_multiresults; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, db, sqldb, sqldbex, CustApp { you can add units after this }; type { TMyApplication } TMyApplication = class(TCustomApplication) protected procedure DoRun; override; procedure TestDb(const sql: string); public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TMyApplication } procedure TMyApplication.DoRun; const sql1 = ' select name, id, xtype, crdate from sysobjects where id=4'#13#10 + 'select name, id, xtype, length, xprec, xscale, colid from syscolumns where id=4'; sql2 = ' exec sp_multiple_resultsets_test'; begin try TestDb(sql1); TestDb(sql2); except on E: Exception do Writeln(E.Message); end; readln; // stop program loop Terminate; end; procedure TMyApplication.TestDb(const sql: string); var ds: TExSQLQuery; oconn: TExODBCConnection; tran: TSQLTransaction; procedure dump; var s: string; i: Integer; begin ds.First; while not ds.EOF do begin s := ''; for i := 0 to ds.FieldCount-1 do s := s + ds.Fields[i].AsString + #9; writeln(s); ds.Next; end; end; begin ds := TExSQLQuery.Create(nil); oconn := TExODBCConnection.Create(nil); tran := TSQLtransaction.Create(nil); try oconn.Password:= 'a1234'; oconn.UserName:= 'test'; oconn.Driver:= 'SQL Server'; oconn.Params.Add('SERVER=localhost'); oconn.Params.Add('DATABASE=TradeMail'); oconn.Transaction := tran; ds.Database := oconn; ds.SQL.text := sql; ds.Open; Writeln('SQL: ' + sql); repeat dump; Writeln('================'); if not ds.NextResultSet then Break; until False; Writeln('No more results to dump.'); finally ds.Free; tran.Free; oconn.Free; end; end; constructor TMyApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TMyApplication.Destroy; begin inherited Destroy; end; procedure TMyApplication.WriteHelp; begin { add your help code here } writeln('Usage: ', ExeName, ' -h'); end; var Application: TMyApplication; begin Application:=TMyApplication.Create(nil); Application.Title:='My Application'; Application.Run; Application.Free; end.
unit CSVOptionsForms; {$mode objfpc}{$H+} {** * This file is part of the "Mini Library" * * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey <zaher, zaherdirkey> *} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, mnStreams, mncCSV; type { TCSVOptionsForm } TCSVOptionsForm = class(TForm) IgnoreEmptyLinesChk: TCheckBox; CancelBtn: TButton; ANSIFileChk: TCheckBox; SkipColumnEdit: TEdit; HeaderList: TComboBox; EOLCharList: TComboBox; Label1: TLabel; QuoteCharLbl: TLabel; QuoteCharLbl1: TLabel; QuoteCharLbl2: TLabel; QuoteCharLbl3: TLabel; QuoteCharList: TComboBox; OkBtn: TButton; DelimiterList: TComboBox; procedure FormCreate(Sender: TObject); procedure OkBtnClick(Sender: TObject); private public end; function ShowCSVOptions(Title: string; var vCSVIE: TmncCSVOptions): Boolean; implementation {$R *.lfm} function ShowCSVOptions(Title: string; var vCSVIE: TmncCSVOptions): Boolean; var s: string; c: Char; begin with TCSVOptionsForm.Create(Application) do begin Caption := Title; QuoteCharList.Text := vCSVIE.QuoteChar; if vCSVIE.DelimiterChar < #32 then DelimiterList.Text := '#'+IntToStr(ord(vCSVIE.DelimiterChar)) else DelimiterList.Text := vCSVIE.DelimiterChar; HeaderList.ItemIndex := Ord(vCSVIE.HeaderLine); ANSIFileChk.Checked := vCSVIE.ANSIContents; IgnoreEmptyLinesChk.Checked := vCSVIE.SkipEmptyLines; SkipColumnEdit.Text := IntToStr(vCSVIE.SkipColumn); if vCSVIE.EndOfLine = sWinEndOfLine then EOLCharList.ItemIndex := 0 else if vCSVIE.EndOfLine = sUnixEndOfLine then EOLCharList.ItemIndex := 1 else if vCSVIE.EndOfLine = sMacEndOfLine then EOLCharList.ItemIndex := 2 else if vCSVIE.EndOfLine = sGSEndOfLine then EOLCharList.ItemIndex := 3 else EOLCharList.ItemIndex := 0;// Result := ShowModal = mrOK; if Result then begin case HeaderList.ItemIndex of 0: vCSVIE.HeaderLine := hdrNone; 1: vCSVIE.HeaderLine := hdrSkip; 2: vCSVIE.HeaderLine := hdrNormal; end; s := DelimiterList.Text; if s = '' then c := #0 else if LeftStr(s, 1) = '#' then c := Char(StrToIntDef(Copy(s, 2, MaxInt), 0)) else c := s[1]; vCSVIE.DelimiterChar := c; s := QuoteCharList.Text; if s = '' then vCSVIE.QuoteChar := #0 else vCSVIE.QuoteChar := s[1]; if vCSVIE.QuoteChar < #32 then vCSVIE.QuoteChar := #0; case EOLCharList.ItemIndex of 1: vCSVIE.EndOfLine := sUnixEndOfLine; 2: vCSVIE.EndOfLine := sMacEndOfLine; 3: vCSVIE.EndOfLine := sGSEndOfLine; else vCSVIE.EndOfLine := sWinEndOfLine; end; vCSVIE.ANSIContents := ANSIFileChk.Checked; vCSVIE.SkipEmptyLines := IgnoreEmptyLinesChk.Checked; vCSVIE.SkipColumn := StrToIntDef(SkipColumnEdit.Text, 0); end; end; end; { TCSVOptionsForm } procedure TCSVOptionsForm.FormCreate(Sender: TObject); begin HeaderList.Items.Add('No Header'); HeaderList.Items.Add('Skip header'); HeaderList.Items.Add('Header contain fields'); HeaderList.ItemIndex := 0; DelimiterList.Items.Add(';'); DelimiterList.Items.Add(','); DelimiterList.Items.Add('|'); DelimiterList.Items.Add('#9'); DelimiterList.Items.Add('#29'); DelimiterList.Text := ';'; DelimiterList.ItemIndex := 0; EOLCharList.Items.Add('Windows'); EOLCharList.Items.Add('Unix'); EOLCharList.Items.Add('Mac'); EOLCharList.Items.Add('GS'); EOLCharList.ItemIndex := 0; QuoteCharList.Items.Add(''); QuoteCharList.Items.Add('"'); QuoteCharList.Items.Add(''''); QuoteCharList.ItemIndex := 0; end; procedure TCSVOptionsForm.OkBtnClick(Sender: TObject); begin end; end.
{ Skype Audio Manager (C) Copyright 2018 by James O. Dreher Right-click on the icon in the system tray to select audio device. For Skype for Business on Window 10 } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, Menus, WinAutoKey, LCLType, ShellApi; type { TForm1 } TForm1 = class(TForm) ButtonClose: TButton; Label1: TLabel; miStartSkype: TMenuItem; miCustomDevice: TMenuItem; miAbout: TMenuItem; miHeadset: TMenuItem; miSpeakerPhone: TMenuItem; miExit: TMenuItem; PopupMenu1: TPopupMenu; TrayIcon: TTrayIcon; procedure StartSkype; procedure CheckSelectedDevice(const Device: Word); procedure GetCurrentDeviceAsync(Data: PtrInt); procedure ChangeDeviceAsync(Data: PtrInt); procedure ButtonCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure miCustomDeviceClick(Sender: TObject); procedure miExitClick(Sender: TObject); procedure miHeadsetClick(Sender: TObject); procedure miAboutClick(Sender: TObject); procedure miSpeakerPhoneClick(Sender: TObject); procedure miStartSkypeClick(Sender: TObject); procedure TrayIconClick(Sender: TObject); private public end; const DS=DirectorySeparator; LE=LineEnding; WINDOW_TITLE='Skype for Business'; OPTIONS_TITLE='Skype for Business - Options'; SKYPE_EXE='"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\'+ 'Microsoft Office 2013\Skype for Business 2015.lnk"'; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.CheckSelectedDevice(const Device: Word); begin miHeadset.Checked:=False; miSpeakerPhone.Checked:=False; miCustomDevice.Checked:=False; Case Device of VK_H : miHeadset.Checked:=True; VK_E : miSpeakerPhone.Checked:=True; VK_C : miCustomDevice.Checked:=True; end; Case Device of VK_H : TrayIcon.Hint:='Headset'; VK_E : TrayIcon.Hint:='Speaker Phone'; VK_C : TrayIcon.Hint:='Custom Device'; end; Application.ProcessMessages; TrayIcon.BalloonHint:=TrayIcon.Hint+' selected.'; TrayIcon.ShowBalloonHint; end; procedure TForm1.StartSkype; begin ShellExecute(Handle, 'open', SKYPE_EXE, nil, nil, SW_SHOWNORMAL); miHeadset.Enabled:=true; miSpeakerPhone.Enabled:=true; miCustomDevice.Enabled:=true; end; procedure TForm1.ChangeDeviceAsync(Data: PtrInt); var hw, ho: HWND; begin hw:=WinGetHandle(WINDOW_TITLE); if hw=0 then begin StartSkype; Exit; end; if not WinActivate(hw) then begin ShowMessage('Error could not activate: '+WINDOW_TITLE); Exit; end; Send([VK_ALT_DN,VK_T,VK_ALT_UP]); // Tools Send(VK_V); // Audio DeVice ho:=WinWait(OPTIONS_TITLE,'','',2); if ho=0 then begin ShowMessage('Timeout waiting for: '+OPTIONS_TITLE); Exit; end; ControlFocus(hCtl(ho,'','',148)); //ComboBox1 Send(Data); //Headphones, Echo Speakerphone, or Custom ControlFocus(hCtl(ho,'OK')); //OK button Send(VK_RETURN); CheckSelectedDevice(Data); end; procedure TForm1.GetCurrentDeviceAsync(Data: PtrInt); var TextList: TStringList; hw, ho: HWND; CurrentDevice: Word; begin TextList:=TStringList.Create; hw:=WinGetHandle(WINDOW_TITLE); if hw=0 then begin StartSkype; end; hw:=WinWait(WINDOW_TITLE,'Find someone or dial a number','',15); if hw=0 then begin ShowMessage('Error timeout waiting for window: '+WINDOW_TITLE); Exit; end; if not WinActivate(hw) then begin ShowMessage('Error could not activate: '+WINDOW_TITLE); Exit; end; { currently selected device } Send([VK_ALT_DN,VK_T,VK_ALT_UP]); // Tools Send(VK_V); // Audio DeVice ho:=WinWait(OPTIONS_TITLE,'','',2); if ho=0 then begin ShowMessage('Timeout waiting for: '+OPTIONS_TITLE); Exit; end; TextList.Text:=WinGetText(ho); Send(VK_ESCAPE); Application.ProcessMessages; CurrentDevice:=Ord(UpperCase(TextList[4])[1]); CheckSelectedDevice(CurrentDevice); FreeAndNil(TextList); end; procedure TForm1.ButtonCloseClick(Sender: TObject); begin Form1.Hide; end; procedure TForm1.miStartSkypeClick(Sender: TObject); begin Application.QueueAsyncCall(@GetCurrentDeviceAsync,0); end; procedure TForm1.miHeadsetClick(Sender: TObject); begin if not miHeadset.Checked then Application.QueueAsyncCall(@ChangeDeviceAsync,VK_H); end; procedure TForm1.miSpeakerPhoneClick(Sender: TObject); begin if not miSpeakerPhone.Checked then Application.QueueAsyncCall(@ChangeDeviceAsync,VK_E); end; procedure TForm1.miCustomDeviceClick(Sender: TObject); begin if not miCustomDevice.Checked then Application.QueueAsyncCall(@ChangeDeviceAsync,VK_C); end; procedure TForm1.miAboutClick(Sender: TObject); begin Form1.Show; end; procedure TForm1.miExitClick(Sender: TObject); begin Form1.Close; end; procedure TForm1.TrayIconClick(Sender: TObject); begin Form1.Show; end; procedure TForm1.FormCreate(Sender: TObject); begin Application.ShowMainForm:=False; TrayIcon.Hint:='Skype Audio Manager'; TrayIcon.BalloonTitle:=TrayIcon.Hint; TrayIcon.Visible:=True; SetTitleMatchMode(mtExact); SetTextMatchMode(mtStartsWith); SetKeyDelay(10); //default 5ms SetWinDelay(200); //default 100ms //don't auto start skype Application.QueueAsyncCall(@GetCurrentDeviceAsync,0); miHeadset.Enabled:=false; miSpeakerPhone.Enabled:=false; miCustomDevice.Enabled:=false; end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); var h: HWND; Reply: integer; begin h:=hWin(WINDOW_TITLE); if WinExists(h) then begin Reply:=Application.MessageBox('Exit '+WINDOW_TITLE+'?', PChar(Application.Title), MB_ICONQUESTION + MB_YESNO); if Reply=IDYES then begin WinActivate(h); Send([VK_ALT_DN,VK_F,VK_ALT_UP,VK_X]); end else CloseAction:=caHide end; end; end.
unit Benjamim.Header; interface uses {$IF DEFINED(FPC)} fpjson, Classes, SysUtils, {$ELSE} System.JSON, System.Classes, System.SysUtils, {$ENDIF} Benjamim.Utils, Benjamim.Header.Interfaces; type THeader = class(TInterfacedObject, iHeader) class function New: iHeader; constructor Create; destructor Destroy; override; strict private FHeader: TJwtAlgorithm; public function Algorithm: string; overload; function Algorithm(const aAlgorithm: TJwtAlgorithm): iHeader; overload; function AsJson(const AsBase64: boolean = false): string; function AsJsonObject: TJSONObject; end; implementation { THeader } class function THeader.New: iHeader; begin Result := Self.Create; end; constructor THeader.Create; begin FHeader := TJwtAlgorithm.HS256; end; destructor THeader.Destroy; begin inherited; end; function THeader.Algorithm(const aAlgorithm: TJwtAlgorithm): iHeader; begin FHeader := aAlgorithm; Result := Self; end; function THeader.AsJson(const AsBase64: boolean = false): string; begin Result := Format('{"alg":"%s","typ":"JWT"}', [FHeader.AsString]); if AsBase64 then Result := Result.AsBase64url.ClearLineBreak; end; function THeader.AsJsonObject: TJSONObject; begin Result := AsJson(false).ClearLineBreak.AsJsonObject; end; function THeader.Algorithm: string; begin Result := FHeader.AsString; end; end.
unit TestBezierAnimationMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Edit, System.UIConsts, // FMX.Graphics.INativeCanvas, // FMX.Graphics.NativeCanvas, FMX.BezierAnimation, FMX.Layouts, FMX.BezierPanel, FMX.Ani; type TSelectionPoint = class(FMX.Objects.TSelectionPoint) private FSelectedFillColor: TAlphaColor; procedure SetSelectedFillColor(const Value: TAlphaColor); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; published property SelectedFillColor: TAlphaColor read FSelectedFillColor write SetSelectedFillColor; end; TCubicBezierAnimationMainForm = class(TForm) pbCanvas: TPaintBox; SelectionPoint1: TSelectionPoint; SelectionPoint2: TSelectionPoint; Label1: TLabel; edtEqation: TEdit; LayoutPanels: TLayout; edtEqation2: TEdit; LayoutTop: TLayout; LayoutRunners: TLayout; Layout1: TLayout; Layout2: TLayout; BezierPanel1: TFMXBezierPanel; BezierPanel2: TFMXBezierPanel; BezierAnimation1: TFMXBezierAnimation; BezierAnimation2: TFMXBezierAnimation; Layout3: TLayout; btnRun: TButton; trckbrDuration: TTrackBar; lblDuration: TLabel; procedure FormCreate(Sender: TObject); procedure edtEqationEnter(Sender: TObject); procedure pbCanvasPaint(Sender: TObject; Canvas: TCanvas); procedure SelectionPoint1Track(Sender: TObject; var X, Y: Single); procedure SelectionPoint2Track(Sender: TObject; var X, Y: Single); procedure Button1Click(Sender: TObject); procedure btnRunClick(Sender: TObject); procedure trckbrDurationChange(Sender: TObject); private { Private declarations } p1x, p1y, p2x, p2y: Single; FChanging: Boolean; FPanels: TArray<TBezierPanelSelector>; function GetPoint(x, y: Single): TPointF; procedure SetBezier(p1x, p1y, p2x, p2y: Single); procedure UpdateEquation; function CreatePanel(AParent: TControl; State: Boolean): TFMXBezierPanel; function CreateSelector(AParent: TControl; Offset, p1x, p1y, p2x, p2y: Single; text: string): TBezierPanelSelector; procedure SetSelectedPanel(APanel: TBezierPanelSelector); procedure OnSelectorClick(Sender: TObject); public { Public declarations } end; var CubicBezierAnimationMainForm: TCubicBezierAnimationMainForm; implementation {$R *.fmx} { TForm11 } procedure TCubicBezierAnimationMainForm.edtEqationEnter(Sender: TObject); begin // end; procedure TCubicBezierAnimationMainForm.FormCreate(Sender: TObject); CONST PW = 125; begin SelectionPoint1.SelectedFillColor := $FFFF0088; SelectionPoint2.SelectedFillColor := $FF00AABB; FPanels := TArray<TBezierPanelSelector>.Create( CreateSelector(LayoutPanels, PW * 0, 0.25, 0.10, 0.25, 1.00, 'ease'), CreateSelector(LayoutPanels, PW * 1, 0.00, 0.00, 1.00, 1.00, 'linear'), CreateSelector(LayoutPanels, PW * 2, 0.42, 0.00, 1.00, 1.00, 'ease-in'), CreateSelector(LayoutPanels, PW * 3, 0.00, 0.00, 0.58, 1.00, 'ease-out'), CreateSelector(LayoutPanels, PW * 4, 0.42, 0.00, 0.58, 1.00, 'ease-in-out') ); SetSelectedPanel(FPanels[0]); FChanging := False; SetBezier(0, 0, 1, 1); end; function TCubicBezierAnimationMainForm.GetPoint(x, y: Single): TPointF; begin Result.x := pbCanvas.Width * x; Result.y := pbCanvas.Height * (1 - y); end; procedure TCubicBezierAnimationMainForm.OnSelectorClick(Sender: TObject); begin SetSelectedPanel(Sender as TBezierPanelSelector); end; procedure TCubicBezierAnimationMainForm.pbCanvasPaint(Sender: TObject; Canvas: TCanvas); const POINT_SIZE = 18; procedure DrawPoint(Canvas: TCanvas; x, y: Single); var p: TPointF; begin p := GetPoint(x, y); Canvas.FillEllipse(TRectF.Create(PointF(p.x - POINT_SIZE / 2, p.y - POINT_SIZE / 2), POINT_SIZE, POINT_SIZE), 1); Canvas.DrawEllipse(TRectF.Create(PointF(p.x - POINT_SIZE / 2, p.y - POINT_SIZE / 2), POINT_SIZE, POINT_SIZE), 1); end; var R: TRectF; // ICanvas: INativeCanvas; path: TPathData; I: Integer; bezier: TBezier; x, y, y1, y2: Single; begin R := pbCanvas.LocalRect; // ICanvas := Canvas.ToNativeCanvas(TDrawMethod.Native); // Canvas.BeginNativeDraw(R); Canvas.Fill.Kind := TBrushKind.Solid; Canvas.Fill.Color := TAlphaColors.White; Canvas.FillRect(R, 0, 0, AllCorners, 1, Canvas.Fill); for I := 1 to 7 do begin y2 := I * R.Height / 7; y1 := y2 - R.Height / 14; Canvas.Fill.Color := $FFF0F0F0; Canvas.FillRect(RectF(0, y1, R.Right, y2), 0,0,AllCorners, 1); end; Canvas.Stroke.Kind := TBrushKind.Solid; // Canvas.Stroke.Color := TAlphaColors.Lightgray; Canvas.Stroke.Color := TAlphaColors.Black; Canvas.Stroke.Thickness := 8; Canvas.DrawLine(GetPoint(0,0), GetPoint(1,1), 0.1); Canvas.Stroke.Color := TAlphaColors.Black; Canvas.Stroke.Thickness := 3; Canvas.DrawLine(GetPoint(0,0), GetPoint(p1x,p1y), 1); Canvas.DrawLine(GetPoint(1,1), GetPoint(p2x,p2y), 1); Canvas.Stroke.Thickness := 8; path := TPathData.Create; bezier := TBezier.Create(p1x, p1y, p2x, p2y); try path.MoveTo(GetPoint(0, 0)); for I := 1 to 100 do begin x := I / 100; y := bezier.Solve(x, TBezier.epsilon); path.LineTo(GetPoint(x, y)); end; Canvas.Stroke.Color := TAlphaColors.Black; Canvas.DrawPath(path, 1); finally bezier.Free; path.Free; end; Canvas.Stroke.Thickness := 1; Canvas.Stroke.Color := TAlphaColors.Lightblue; DrawPoint(Canvas, 0, 0); DrawPoint(Canvas, 1, 1); // Canvas.EndNativeDraw; end; procedure TCubicBezierAnimationMainForm.SelectionPoint1Track(Sender: TObject; var X, Y: Single); begin if not FChanging then begin p1x := SelectionPoint1.Position.Point.x / pbCanvas.Width; p1y := (pbCanvas.Height - SelectionPoint1.Position.Point.y) / pbCanvas.Height; BezierPanel1.P1X := p1x; BezierPanel1.P1Y := p1y; UpdateEquation; pbCanvas.Repaint; end; end; procedure TCubicBezierAnimationMainForm.SelectionPoint2Track(Sender: TObject; var X, Y: Single); begin if not FChanging then begin p2x := SelectionPoint2.Position.Point.x / pbCanvas.Width; p2y := (pbCanvas.Height - SelectionPoint2.Position.Point.y) / pbCanvas.Height; BezierPanel1.P2X := p2x; BezierPanel1.P2Y := p2y; UpdateEquation; pbCanvas.Repaint; end; end; procedure TCubicBezierAnimationMainForm.SetBezier(p1x, p1y, p2x, p2y: Single); begin Self.p1x := p1x; Self.p1y := p1y; Self.p2x := p2x; Self.p2y := p2y; Self.SelectionPoint1.Position.Point := GetPoint(p1x, p1y); Self.SelectionPoint2.Position.Point := GetPoint(p2x, p2y); UpdateEquation; end; procedure TCubicBezierAnimationMainForm.SetSelectedPanel( APanel: TBezierPanelSelector); var I: Integer; begin for I := 0 to High(FPanels) do begin FPanels[I].IsSelected := FPanels[I] = APanel; end; BezierPanel2.P1X := APanel.Panel.P1X; BezierPanel2.P1Y := APanel.Panel.P1Y; BezierPanel2.P2X := APanel.Panel.P2X; BezierPanel2.P2Y := APanel.Panel.P2Y; edtEqation2.Text := Format('%.2f,%.2f,%.2f,%.2f', [BezierPanel2.p1x, BezierPanel2.p1y, BezierPanel2.p2x, BezierPanel2.p2y]); end; procedure TCubicBezierAnimationMainForm.trckbrDurationChange(Sender: TObject); begin lblDuration.Text := trckbrDuration.Value.ToString; end; procedure TCubicBezierAnimationMainForm.UpdateEquation; begin FChanging := True; edtEqation.Text := Format('%.2f,%.2f,%.2f,%.2f', [p1x, p1y, p2x, p2y]); FChanging := False; end; procedure TCubicBezierAnimationMainForm.btnRunClick(Sender: TObject); begin BezierAnimation1.Duration := trckbrDuration.Value; BezierAnimation2.Duration := trckbrDuration.Value; with BezierPanel1 do BezierAnimation1.SetData(P1X, P1Y, P2X, P2Y); with BezierPanel2 do BezierAnimation2.SetData(P1X, P1Y, P2X, P2Y); BezierAnimation1.Start; BezierAnimation2.Start; end; procedure TCubicBezierAnimationMainForm.Button1Click(Sender: TObject); begin edtEqation.Text := Format('%.2f,%.2f,%.2f,%.2f', [p1x, p1y, p2x, p2y]); end; function TCubicBezierAnimationMainForm.CreatePanel(AParent: TControl; State: Boolean): TFMXBezierPanel; begin Result := TFMXBezierPanel.Create(Self); Result.Position.Point := PointF(0, 0); Result.Height := AParent.Height; Result.Width := Result.Height; Result.IsSelected := State; Result.Parent := AParent; end; function TCubicBezierAnimationMainForm.CreateSelector(AParent: TControl; Offset, p1x, p1y, p2x, p2y: Single; text: string): TBezierPanelSelector; begin Result := TBezierPanelSelector.Create(Self); Result.Position.Point := PointF(Offset, 0); Result.Height := AParent.Height; Result.Width := AParent.Height - 40; Result.SetBezier(p1x, p1y, p2x, p2y); Result.Text := text; Result.OnClick := OnSelectorClick; Result.Parent := AParent; end; { TSelectionPoint } constructor TSelectionPoint.Create(AOwner: TComponent); begin inherited; FSelectedFillColor := TAlphaColors.Red; end; procedure TSelectionPoint.Paint; var Fill: TBrush; Stroke: TStrokeBrush; StrokeColor: TAlphaColor; begin Canvas.Stroke.Thickness := 1; Canvas.Stroke.Kind := TBrushKind.Solid; if IsMouseOver then StrokeColor := TAlphaColors.Yellow else StrokeColor := TAlphaColors.Darkgray; Canvas.Stroke.Color := StrokeColor; Canvas.Fill.Kind := TBrushKind.Solid; Stroke := TStrokeBrush.Create(TBrushKind.Solid, StrokeColor); try Fill := TBrush.Create(TBrushKind.Solid, SelectedFillColor); try Canvas.FillEllipse(TRectF.Create(-GripSize, -GripSize, GripSize, GripSize), AbsoluteOpacity, Fill); Canvas.DrawEllipse(TRectF.Create(-GripSize, -GripSize, GripSize, GripSize), AbsoluteOpacity, Stroke); finally Fill.Free; end; finally Stroke.Free; end; end; procedure TSelectionPoint.SetSelectedFillColor(const Value: TAlphaColor); begin if FSelectedFillColor <> Value then begin FSelectedFillColor := Value; Repaint; end; end; end.
unit DaoIBX; interface uses Base, Rtti, Atributos, system.SysUtils, System.Classes, IBX.IB, IBX.IBQuery, IBX.IBDatabase; type TDaoIbx = class(TDaoBase) private // conexao com o banco de dados FDatabase: TIBDatabase; // transação para crud FTransaction: TIbTransaction; // transação para consultas FTransQuery: TIBTransaction; protected // métodos responsáveis por setar os parâmetros procedure QryParamInteger(ARecParams: TRecParams); override; procedure QryParamString(ARecParams: TRecParams); override; procedure QryParamDate(ARecParams: TRecParams); override; procedure QryParamCurrency(ARecParams: TRecParams); override; procedure QryParamVariant(ARecParams: TRecParams); override; //métodos para setar os variados tipos de campos procedure SetaCamposInteger(ARecParams: TRecParams); override; procedure SetaCamposString(ARecParams: TRecParams); override; procedure SetaCamposDate(ARecParams: TRecParams); override; procedure SetaCamposCurrency(ARecParams: TRecParams); override; function ExecutaQuery: Integer; override; procedure FechaQuery; override; public //query para execução dos comandos crud Qry: TIBQuery; constructor Create(ADatabaseName: string); function Inserir(ATabela: TTabela): Integer; override; function Salvar(ATabela: TTabela): Integer; override; function Excluir(ATabela: TTabela): Integer; override; function Buscar(ATabela:TTabela): Integer; override; function InTransaction: Boolean; override; procedure StartTransaction; override; procedure Commit; override; procedure RollBack; override; end; implementation { TDaoIbx } uses Vcl.forms, dialogs, System.TypInfo; constructor TDaoIbx.Create(ADatabaseName: string); begin inherited Create; FDatabase := TIBDatabase.Create(Application); //configurações iniciais da conexão with FDatabase do begin DatabaseName := ADatabaseName; Params.Add('user_name=sysdba'); Params.Add('password=masterkey'); LoginPrompt := false; Connected := True; end; //configurações iniciais da transacao para consultas FTransQuery := TIBTransaction.Create(Application); with FTransQuery do begin DefaultDatabase := FDatabase; Params.Add('read_committed'); Params.Add('rec_version'); Params.Add('nowait'); end; FDatabase.DefaultTransaction := FTransQuery; //configurações iniciais da transacao para crud FTransaction := TIBTransaction.Create(Application); with FTransaction do begin DefaultDatabase := FDatabase; Params.Add('read_committed'); Params.Add('rec_version'); Params.Add('nowait'); end; Qry := TIBQuery.Create(Application); Qry.DataBase := FDatabase; Qry.Transaction := FTransaction; end; procedure TDaoIbx.QryParamCurrency(ARecParams: TRecParams); begin inherited; with ARecParams do begin TIBQuery(Qry).ParamByName(Campo).AsCurrency := Prop.GetValue(Tabela).AsCurrency; end; end; procedure TDaoIbx.QryParamDate(ARecParams: TRecParams); begin inherited; with ARecParams do begin TIBQuery(Qry).ParamByName(Campo).AsDateTime := Prop.GetValue(Tabela).AsType<TDateTime>; end; end; procedure TDaoIbx.QryParamInteger(ARecParams: TRecParams); begin inherited; with ARecParams do begin TIBQuery(Qry).ParamByName(Campo).AsInteger := Prop.GetValue(Tabela).AsInteger; end; end; procedure TDaoIbx.QryParamString(ARecParams: TRecParams); begin inherited; with ARecParams do begin TIBQuery(Qry).ParamByName(Campo).AsString := Prop.GetValue(Tabela).AsString; end; end; procedure TDaoIbx.QryParamVariant(ARecParams: TRecParams); begin inherited; with ARecParams do begin TIBQuery(Qry).ParamByName(Campo).Value := Prop.GetValue(Tabela).AsVariant; end; end; procedure TDaoIbx.SetaCamposCurrency(ARecParams: TRecParams); begin inherited; with ARecParams do begin Prop.SetValue(Tabela, TIBQuery(Qry).FieldByName(Campo).AsCurrency); end; end; procedure TDaoIbx.SetaCamposDate(ARecParams: TRecParams); begin inherited; with ARecParams do begin Prop.SetValue(Tabela, TIBQuery(Qry).FieldByName(Campo).AsDateTime); end; end; procedure TDaoIbx.SetaCamposInteger(ARecParams: TRecParams); begin inherited; with ARecParams do begin Prop.SetValue(Tabela, TIBQuery(Qry).FieldByName(Campo).AsInteger); end; end; procedure TDaoIbx.SetaCamposString(ARecParams: TRecParams); begin inherited; with ARecParams do begin Prop.SetValue(Tabela, TIBQuery(Qry).FieldByName(Campo).AsString); end; end; function TDaoIbx.InTransaction: Boolean; begin Result := FTransaction.InTransaction; end; procedure TDaoIbx.StartTransaction; begin FTransaction.StartTransaction; end; procedure TDaoIbx.RollBack; begin FTransaction.RollBack; end; procedure TDaoIbx.Commit; begin FTransaction.Commit; end; procedure TDaoIbx.FechaQuery; begin Qry.Close; Qry.SQL.Clear; end; function TDaoIbx.ExecutaQuery: Integer; begin with Qry do begin Prepare(); ExecSQL; Result := RowsAffected; end; end; function TDaoIbx.Excluir(ATabela: TTabela): Integer; var Comando: TFuncReflexao; begin //crio uma variável do tipo TFuncReflexao - um método anônimo Comando := function(ACampos: TCamposAnoni): Integer var Campo: string; PropRtti: TRttiProperty; begin FechaQuery; with Qry do begin sql.Add('Delete from ' + ACampos.NomeTabela); sql.Add('Where'); //percorrer todos os campos da chave primária ACampos.Sep := ''; for Campo in ACampos.PKs do begin sql.Add(ACampos.Sep+ Campo + '= :' + Campo); ACampos.Sep := ' and '; // setando os parâmetros for PropRtti in ACampos.TipoRtti.GetProperties do if CompareText(PropRtti.Name, Campo) = 0 then begin ConfiguraParametro(PropRtti, Campo, ATabela, Qry); end; end; end; Result := ExecutaQuery; end; //reflection da tabela e execução da query preparada acima. Result := ReflexaoSQL(ATabela, Comando); end; function TDaoIbx.Inserir(ATabela: TTabela): Integer; var Comando: TFuncReflexao; begin Comando := function(ACampos: TCamposAnoni): Integer var Campo: string; PropRtti: TRttiProperty; begin FechaQuery; with Qry do begin sql.Add('Insert into ' + ACampos.NomeTabela); sql.Add('('); //campos da tabela ACampos.Sep := ''; for PropRtti in ACampos.TipoRtti.GetProperties do begin SQL.Add(ACampos.Sep + PropRtti.Name); ACampos.Sep := ','; end; sql.Add(')'); //parâmetros sql.Add('Values ('); ACampos.Sep := ''; for PropRtti in ACampos.TipoRtti.GetProperties do begin SQL.Add(ACampos.Sep + ':' + PropRtti.Name); ACampos.Sep := ','; end; sql.Add(')'); //valor dos parâmetros for PropRtti in ACampos.TipoRtti.GetProperties do begin Campo := PropRtti.Name; ConfiguraParametro(PropRtti, Campo, ATabela, Qry); end; end; Result := ExecutaQuery; end; //reflection da tabela e execução da query preparada acima. Result := ReflexaoSQL(ATabela, Comando); end; function TDaoIbx.Salvar(ATabela: TTabela): Integer; var Comando: TFuncReflexao; begin Comando := function(ACampos: TCamposAnoni): Integer var Campo: string; PropRtti: TRttiProperty; begin FechaQuery; with Qry do begin sql.Add('Update ' + ACampos.NomeTabela); sql.Add('set'); //campos da tabela ACampos.Sep := ''; for PropRtti in ACampos.TipoRtti.GetProperties do begin SQL.Add(ACampos.Sep + PropRtti.Name + '=:'+PropRtti.Name); ACampos.Sep := ','; end; sql.Add('where'); //parâmetros da cláusula where ACampos.Sep := ''; for Campo in ACampos.PKs do begin sql.Add(ACampos.Sep+ Campo + '= :' + Campo); ACampos.Sep := ' and '; end; //valor dos parâmetros for PropRtti in ACampos.TipoRtti.GetProperties do begin Campo := PropRtti.Name; ConfiguraParametro(PropRtti, Campo, ATabela, Qry); end; end; Result := ExecutaQuery; end; //reflection da tabela e execução da query preparada acima. Result := ReflexaoSQL(ATabela, Comando); end; function TDaoIbx.Buscar(ATabela: TTabela): Integer; var Comando: TFuncReflexao; Dados: TIBQuery; begin Dados := TIBQuery.Create(nil); try //crio uma variável do tipo TFuncReflexao - um método anônimo Comando := function(ACampos: TCamposAnoni): Integer var Campo: string; PropRtti: TRttiProperty; begin with Dados do begin Database := FDatabase; sql.Add('select * from ' + ACampos.NomeTabela); sql.Add('Where'); //percorrer todos os campos da chave primária ACampos.Sep := ''; for Campo in ACampos.PKs do begin sql.Add(ACampos.Sep+ Campo + '= :' + Campo); ACampos.Sep := ' and '; // setando os parâmetros for PropRtti in ACampos.TipoRtti.GetProperties do if CompareText(PropRtti.Name, Campo) = 0 then begin ConfiguraParametro(PropRtti, Campo, ATabela, Dados, True); end; end; Open; Result := RecordCount; if Result > 0 then begin for PropRtti in ACampos.TipoRtti.GetProperties do begin Campo := PropRtti.Name; SetaDadosTabela(PropRtti, Campo, ATabela, Dados); ACampos.Sep := ','; end; end; end; end; //reflection da tabela e abertura da query preparada acima. Result := ReflexaoSQL(ATabela, Comando); finally Dados.Free; end; end; end.
unit HashTables; interface uses SysUtils, Classes, Math, Windows; const EMPTY = Pointer(-1); DELETED = Pointer(-2); type THashTable = class(TObject) private Alpha: Double; FTable: PPointerList; FCount: Integer; FCapacity: Integer; FMaximumFillRatio: Double; FPosition: Integer; FCollisions: Integer; FInsertions: Integer; function GetAverageCollision: Real; procedure SetMaximumFillRatio(Value: Double); protected procedure Error(const msg: string); function Get(Key: Integer): Pointer; virtual; function GetIndex(Key: Integer): Integer; procedure Grow; virtual; function Hash(Key: Integer): Integer; virtual; procedure Put(Key: Integer; Item: Pointer); virtual; procedure Rehash(OldTable: PPointerList; OldCount: Integer); procedure SetCapacity(NewCapacity: Integer); public constructor Create; destructor Destroy; override; procedure Clear; virtual; function Current: Pointer; virtual; function DeleteCurrent: Pointer; function First: Pointer; virtual; function Insert(Key: Integer; Item: Pointer): Pointer; virtual; function Next: Pointer; virtual; function NextSame(Key: Integer): Pointer; function Remove(Key: Integer): Pointer; virtual; procedure Pack; property Capacity: Integer read FCapacity write SetCapacity; property Count: Integer read FCount; property MaximumFillRatio: Double read FMaximumFillRatio write SetMaximumFillRatio; property Items[Key: Integer]: Pointer read Get write Put; default; property AverageCollisions: Real read GetAverageCollision; end; TStringTableNode = record FKey: string; FObject: TObject; end; PStringTableNode = ^TStringTableNode; TStringTable = class(THashTable) private function ConvertKey(const Key: string): Integer; function FindKey(const Key: string; var Node: PStringTableNode): Boolean; protected function Get(const Key: string): TObject; reintroduce; procedure Put(const Key: string; Item: TObject); reintroduce; public destructor Destroy; override; procedure Clear; override; function Current: TObject; reintroduce; function CurrentKey: string; reintroduce; function First: TObject; reintroduce; function Insert(const Key: string; Item: TObject): Pointer; reintroduce; function Next: TObject; reintroduce; function Remove(const Key: string): TObject; reintroduce; property Items[const Key: string]: TObject read Get write Put; default; end; EHashTableError = class(Exception); implementation constructor THashTable.Create; begin Alpha := (Sqrt(5.0) - 1) / 2.0; FMaximumFillRatio := 0.8; SetCapacity(256); end; destructor THashTable.Destroy; begin FreeMem(FTable, FCapacity * (SizeOf(Pointer) * 2)); end; procedure THashTable.Clear; begin FCount := 0; FPosition := -2; FillChar(FTable^, FCapacity * (SizeOf(Pointer) * 2), Char(EMPTY)); end; function THashTable.Current: Pointer; begin if (FPosition >= 0) and (FPosition < FCapacity) and (FTable[FPosition] <> EMPTY) and (FTable[FPosition] <> DELETED) then Result := FTable[FPosition + 1] else Result := nil; end; function THashTable.DeleteCurrent: Pointer; begin FTable[FPosition] := DELETED; Result := FTable[FPosition + 1]; Dec(FCount); end; procedure THashTable.Error(const msg: string); begin raise EHashTableError.Create(msg); end; function THashTable.First: Pointer; begin FPosition := -2; Result := Next; end; function THashTable.Get(Key: Integer): Pointer; begin FPosition := GetIndex(Key); if Integer(FTable[FPosition]) = Key then Result := FTable[FPosition + 1] else Result := nil; end; function THashTable.GetAverageCollision: Real; begin if FInsertions = 0 then Result := 0.0 else Result := FCollisions / FInsertions; end; function THashTable.GetIndex(Key: Integer): Integer; var I: Integer; begin Result := Hash(Key) * 2; I := 0; while (I < FCapacity) and (FTable[Result] <> Pointer(Key)) and (FTable[Result] <> EMPTY) do begin Inc(Result, 2); Inc(I); Result := Result mod (FCapacity * 2); end; end; procedure THashTable.Grow; begin SetCapacity(FCapacity * 2); end; function THashTable.Hash(Key: Integer): Integer; begin if Key < 0 then Error('Keys must be positive'); Result := Trunc(FCapacity * Frac(Alpha * Key)); end; function THashTable.Insert(Key: Integer; Item: Pointer): Pointer; begin if (FCount + 1) >= Round(FCapacity * FMaximumFillRatio) then Grow; Inc(FCount); FPosition := Hash(Key) * 2; while (FTable[FPosition] <> EMPTY) and (FTable[FPosition] <> DELETED) do begin Inc(FCollisions); Inc(FPosition, 2); FPosition := FPosition mod (FCapacity * 2); end; FTable[FPosition] := Pointer(Key); FTable[FPosition + 1] := Item; Result := @FTable[FPosition + 1]; Inc(FInsertions) end; function THashTable.Next: Pointer; begin Inc(FPosition, 2); while (FPosition < (FCapacity * 2)) and ((FTable[FPosition] = EMPTY) or (FTable[FPosition] = DELETED)) do Inc(FPosition, 2); if FPosition < (FCapacity * 2) then Result := FTable[FPosition + 1] else Result := nil; end; function THashTable.NextSame(Key: Integer): Pointer; var oldpos: Integer; begin oldpos := FPosition; Inc(FPosition, 2); while (FPosition <> oldpos) and (FTable[FPosition] <> EMPTY) and (FTable[FPosition] <> Pointer(Key)) do begin Inc(FPosition, 2); FPosition := FPosition mod (FCapacity * 2); end; if FTable[FPosition] = Pointer(Key) then Result := FTable[FPosition + 1] else Result := nil; end; procedure THashTable.Pack; begin SetCapacity(Round(FCount * (1 / FMaximumFillRatio)) + 2); end; procedure THashTable.Put(Key: Integer; Item: Pointer); begin FPosition := GetIndex(Key); if Integer(FTable[FPosition]) = Key then FTable[FPosition + 1] := Item else Insert(Key, Item); end; function THashTable.Remove(Key: Integer): Pointer; begin FPosition := GetIndex(Key); if Integer(FTable[FPosition]) = Key then begin FTable[FPosition] := DELETED; Result := FTable[FPosition + 1]; Dec(FCount); end else Result := nil; end; procedure THashTable.Rehash(OldTable: PPointerList; OldCount: Integer); var I: Integer; begin I := 0; while FCount < OldCount do begin while (OldTable[I] = EMPTY) or (OldTable[I] = DELETED) do Inc(I, 2); Insert(Integer(OldTable[I]), OldTable[I + 1]); Inc(I, 2); end; end; procedure THashTable.SetCapacity(NewCapacity: Integer); var OldTable: Pointer; OldCapacity, OldCount: Integer; begin if (FCount >= Round(NewCapacity * FMaximumFillRatio)) or (NewCapacity > (MaxListSize div 2)) then Error('Invalid capacity'); if NewCapacity <> FCapacity then begin OldTable := FTable; FTable := AllocMem(NewCapacity * (SizeOf(Pointer) * 2)); OldCapacity := FCapacity; FCapacity := NewCapacity; OldCount := FCount; FPosition := -1; Clear; ReHash(OldTable, OldCount); FreeMem(OldTable, OldCapacity * (SizeOf(Pointer) * 2)); end; end; procedure THashTable.SetMaximumFillRatio(Value: Double); begin if (Value < 0.5) or (Value > 1.0) then Error('Maximum fill ratio must be between 0.5 and 1.0'); FMaximumFillRatio := Value; if FCount > Round(FCapacity * FMaximumFillRatio) then Grow; end; { TStringTable } procedure TStringTable.Clear; var pt: PStringTableNode; begin pt := PStringTableNode(inherited First); while pt <> nil do begin Dispose(pt); pt := inherited Next; end; inherited Clear; end; function TStringTable.ConvertKey(const Key: string): Integer; var i: Integer; begin Result := 0; for i := 1 to Length(Key) do Result := (131 * Result) + Ord(Key[i]); Result := Abs(Result); end; function TStringTable.Current: TObject; var pt: PStringTableNode; begin pt := inherited Current; if pt <> nil then Result := pt^.FObject else Result := nil; end; function TStringTable.CurrentKey: string; var pt: PStringTableNode; begin pt := inherited Current; if pt <> nil then Result := pt^.FKey else Result := ''; end; destructor TStringTable.Destroy; begin Clear; inherited Destroy; end; function TStringTable.FindKey(const Key: string; var Node: PStringTableNode): Boolean; var k: Integer; begin k := ConvertKey(Key); Node := inherited Get(k); while (Node <> nil) and (Node^.FKey <> Key) do NextSame(k); Result := (Node <> nil); end; function TStringTable.First: TObject; var pt: PStringTableNode; begin pt := inherited First; if pt <> nil then Result := pt^.FObject else Result := nil; end; function TStringTable.Get(const Key: string): TObject; var pt: PStringTableNode; begin if FindKey(Key, pt) then Result := pt^.FObject else Result := nil; end; function TStringTable.Insert(const Key: string; Item: TObject): Pointer; var pt: PStringTableNode; begin New(pt); pt^.FKey := Key; pt^.FObject := Item; inherited Insert(ConvertKey(Key), pt); Result := @(pt^.FObject); end; function TStringTable.Next: TObject; var pt: PStringTableNode; begin pt := inherited Next; if pt <> nil then Result := pt^.FObject else Result := nil; end; procedure TStringTable.Put(const Key: string; Item: TObject); var pt: PStringTableNode; begin if FindKey(Key, pt) then pt^.FObject := Item else Insert(Key, Item); end; function TStringTable.Remove(const Key: string): TObject; var pt: PStringTableNode; begin if FindKey(Key, pt) then begin DeleteCurrent; Result := pt^.FObject; Dispose(pt); end else Result := nil; end; end.
{ This is a personal project that I give to community under this licence: Copyright 2016 Eric Buso (Alias Caine_dvp) 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 USQLite3; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses windows,SysUtils ; type TSql = class(Tobject) public function Update (const tables, sets, where: String;Var Count : Integer): Integer; function insert(const tables,columns,values : String ): Integer; function LastRowId(const table,where : String; Var RowId : Integer ): Integer; function closeDatabase:integer; function CountSelect(const Table,Where: String):integer; function CountDistinct(const Table,Columns,Where : String): Integer; function Select(const Table,columns,where: String; var Count : Integer):integer; procedure Fetch(var Row : Array of TVarRec); constructor Create(const Database: String;Var Error : Integer; Var ErrorMsg : String); destructor Destroy;override; private sqlerror : Integer; DB : Pointer; Stmt : Pointer; FErrorMsg : String; public property ErrorMsg : String Read FErrorMsg; end; Implementation const DLLSqlite = '.\sqlite3.dll'; SQLITE_OK = 0; // Successful result SQLITE_ERROR = 1; // SQL error or missing database SQLITE_INTERNAL = 2; // An internal logic error in SQLite SQLITE_PERM = 3; // Access permission denied SQLITE_ABORT = 4; // Callback routine requested an abort SQLITE_BUSY = 5; // The database file is locked SQLITE_LOCKED = 6; // A table in the database is locked SQLITE_NOMEM = 7; // A malloc() failed SQLITE_READONLY = 8; // Attempt to write a readonly database SQLITE_INTERRUPT = 9; // Operation terminated by sqlite3_interrupt() SQLITE_IOERR = 10; // Some kind of disk I/O error occurred SQLITE_CORRUPT = 11; // The database disk image is malformed SQLITE_NOTFOUND = 12; // (Internal Only) Table or record not found SQLITE_FULL = 13; // Insertion failed because database is full SQLITE_CANTOPEN = 14; // Unable to open the database file SQLITE_PROTOCOL = 15; // Database lock protocol error SQLITE_EMPTY = 16; // Database is empty SQLITE_SCHEMA = 17; // The database schema changed SQLITE_TOOBIG = 18; // Too much data for one row of a table SQLITE_CONSTRAINT = 19; // Abort due to contraint violation SQLITE_MISMATCH = 20; // Data type mismatch SQLITE_MISUSE = 21; // Library used incorrectly SQLITE_NOLFS = 22; // Uses OS features not supported on host SQLITE_AUTH = 23; // Authorization denied SQLITE_FORMAT = 24; // Auxiliary database format error SQLITE_RANGE = 25; // 2nd parameter to sqlite3_bind out of range SQLITE_NOTADB = 26; // File opened that is not a database file SQLITE_ROW = 100; // sqlite3_step() has another row ready SQLITE_DONE = 101; // sqlite3_step() has finished executing SQLITE_INTEGER = 1; SQLITE_FLOAT = 2; SQLITE_TEXT = 3; SQLITE_BLOB = 4; SQLITE_NULL = 5; SQLITE_OPEN_READONLY = $00000001; SQLITE_OPEN_READWRITE = $00000002; { int sqlite3_open_v2( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb, /* OUT: SQLite db handle */ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); } function sqlite3_open_v2(DBName : pchar;Var DB : pointer; Flags : Integer; Vfs : Pointer): integer; cdecl; external DLLSqlite name 'sqlite3_open_v2'; { int sqlite3_close(sqlite3 *); } function sqlite3_close(DB : Pointer) : integer; cdecl; external DLLSqlite name 'sqlite3_close'; {int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); } function sqlite3_exec(DB: Pointer; Sql : pchar; Callback : Pointer; FirstParam : Pointer; Var Error : pchar): integer;cdecl;external DLLSqlite name 'sqlite3_exec'; { int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); } function sqlite3_prepare_v2 (DB : Pointer; Sql : pchar; Bytes : Integer; Var Statement : Pointer; Var Tail : pchar) : Integer; cdecl; external DLLSqlite name 'sqlite3_prepare_v2'; { int sqlite3_step(sqlite3_stmt*); } function sqlite3_step(Statement: Pointer) : Integer;cdecl; external DLLSQLite name 'sqlite3_step'; { int sqlite3_column_count(sqlite3_stmt *pStmt); } function sqlite3_column_count(Statement : Pointer) : Integer;cdecl;external DLLSQLite name 'sqlite3_column_count'; { int sqlite3_column_int(sqlite3_stmt*, int iCol); } function sqlite3_column_int(Statement : Pointer; iCol: Integer):Integer;cdecl;external DLLSQLite name 'sqlite3_column_int'; { int sqlite3_column_bytes(sqlite3_stmt*, int iCol); } function sqlite3_column_bytes(Statement : Pointer; iCol: Integer): Integer;cdecl;external DLLSQLite name 'sqlite3_column_bytes'; { const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); } function sqlite3_column_text(Statement : Pointer; iCol: Integer): pchar;cdecl;external DLLSQLite name 'sqlite3_column_text'; {const char *sqlite3_errmsg(sqlite3*);} function sqlite3_errmsg(DB : Pointer):pchar;cdecl;external DLLSQLite name 'sqlite3_errmsg'; { int sqlite3_column_type(sqlite3_stmt*, int iCol); } { int sqlite3_finalize(sqlite3_stmt *pStmt); } function sqlite3_finalize(Statement : Pointer) : Integer;cdecl;external DLLSQLite name 'sqlite3_finalize'; { void sqlite3_free(void*); } procedure sqlite3_free(SLObject : Pointer);cdecl;external DLLSQLite name 'sqlite3_free'; { TSql } function TSql.closeDatabase: integer; begin if Assigned(DB) then Begin sqlerror := sqlite3_close(DB); DB := nil; End; Result := sqlerror; end; function TSql.CountDistinct(const Table, Columns, Where: String): Integer; const Sql = ' select count(*) from (select %s from %s %s);'; Var tail : pchar; Select : String; begin Result := -1; If Where = EmptyStr Then Select := Format(Sql,[Columns,Table,Where]) Else Select := Format(Sql,[Columns,Table,Format('where %s',[Where])]); sqlerror := sqlite3_prepare_v2(DB,pchar(Select),-1,Stmt,tail); if (sqlerror = SQLITE_OK) Then Begin sqlerror := sqlite3_step(Stmt); if (sqlerror = SQLITE_ROW) Then Begin Result := sqlite3_column_int(Stmt,0); sqlerror := sqlite3_step(Stmt); End; End; if (sqlerror = SQLITE_DONE) Then Begin sqlite3_finalize(Stmt); Stmt := nil; sqlerror := SQLITE_OK; End; end; function TSql.CountSelect(const Table,Where: String): integer; const Sql = 'select count(*) from %s %s;'; Var tail : pchar; Select : String; begin Result := -1; If Where = EmptyStr Then Select := Format(Sql,[Table,Where]) Else Select := Format(Sql,[Table,Format('where %s',[Where])]); sqlerror := sqlite3_prepare_v2(DB,pchar(Select),-1,Stmt,tail); if (sqlerror = SQLITE_OK) Then Begin sqlerror := sqlite3_step(Stmt); if (sqlerror = SQLITE_ROW) Then Begin Result := sqlite3_column_int(Stmt,0); sqlerror := sqlite3_step(Stmt); End; End; if (sqlerror = SQLITE_DONE) Then Begin sqlite3_finalize(Stmt); Stmt := nil; sqlerror := SQLITE_OK; End; end; constructor TSql.Create(const Database: String;Var Error : Integer; Var ErrorMsg : String); begin DB := Nil; sqlerror := sqlite3_open_v2(pchar(Database),&DB,SQLITE_OPEN_READWRITE,nil); Error := sqlerror; if (sqlerror <> SQLITE_OK) Then Begin ErrorMsg := sqlite3_errmsg(DB); sqlite3_close(DB); // le pointeur assigné par la Dll Sqlite ne peut être libéré que par ses soins. // Sa valeur n'a plus de sens après le CLose. Mise à Nil préventive. DB := nil; End end; destructor TSql.Destroy; begin if (Stmt <> nil ) Then sqlite3_finalize(Stmt); closeDatabase; end; procedure TSql.Fetch(var Row: array of TVarRec); Var C,I,Sz : Integer; Text : pchar; begin if Stmt = nil then exit; C := sqlite3_column_count(Stmt); If Length(Row) < C Then Exit; For I := 0 To C-1 Do case Row[I].VType of VtInteger: Row[I].VInteger := sqlite3_column_int(Stmt,I); vtPChar: Begin Text := sqlite3_column_text(Stmt,I); Sz := sqlite3_column_bytes(Stmt,I); Row[I].vPChar := StrNew(Text); End; { VtInt64 : Row[I].VInt64 := } end; //Préparer la row suivante ou finaliser si aucune row. sqlerror := sqlite3_step(Stmt); if (sqlerror = SQLITE_DONE) Then Begin sqlite3_finalize(Stmt); Stmt := nil; sqlerror := SQLITE_OK; End; end; function TSql.insert(const tables, columns, values: String): Integer; Const InsertStmt = 'insert into "%s" (%s) values (%s);'; Var Insert : String; Error : pchar; begin Result := sqlerror; if (sqlerror <> SQLITE_OK) Then Exit; Insert := Format(InsertStmt,[tables,columns,values] ); sqlerror := sqlite3_exec(DB,pchar(Insert),nil,nil,Error); If sqlerror <> SQLITE_OK Then FErrorMsg := sqlite3_errmsg(DB); Result := sqlerror; sqlite3_free(Error); end; function TSql.LastRowId(const table, Where: String;Var RowId : Integer): Integer; Const RowIDStmt = 'select into "%s" where %s;'; Var Request : String; Error : pchar; begin Result := sqlerror; if (sqlerror <> SQLITE_OK) Then Exit; Request := Format(RowIDStmt,[table,Where] ); sqlerror := sqlite3_exec(DB,pchar(Request),nil,nil,Error); Result := sqlerror; sqlite3_free(Error); if (sqlerror = SQLITE_ROW) Then Begin RowId := sqlite3_column_int(Stmt,0); sqlerror := sqlite3_step(Stmt); Result := sqlerror; End; end; function TSql.Select(const Table, columns, where: String; var Count : Integer): integer; Const SelectStmt = 'select %s from %s %s;'; var Select : String; Tail : pchar; I: Integer; begin Count := -1; //Une requête en cours Result := SQLITE_BUSY; if (Stmt <> nil) Then Exit; //Une erreur précédente. Result := sqlerror; if (sqlerror <> SQLITE_OK) Then Exit; If Pos('distinct',columns) > 0 Then Count := CountDistinct(Table,columns,where) Else Count := CountSelect(table,where); Result := SQLITE_OK; if count <= 0 then exit; If Where = EmptyStr Then Select := Format(SelectStmt,[columns,Table,Where]) Else Select := Format(SelectStmt,[columns,Table,Format('where %s',[Where])]); sqlerror := sqlite3_prepare_v2(DB,pchar(Select),-1,Stmt,tail); if (sqlerror = SQLITE_OK) Then Begin sqlerror := sqlite3_step(Stmt); case sqlerror of SQLITE_ROW: Begin Result := SQLITE_OK; End; SQLITE_DONE: Begin Count := 0; Result := SQLITE_OK; End; end; End; if Result <> SQLITE_OK then result := -sqlerror; end; function TSql.Update(const tables, sets, where: String;Var Count : Integer): Integer; const UPdateStmt = 'update %s set %s where %s'; Var Select : String; tail : pchar; begin // Count := -1; //Une requête en cours Result := SQLITE_BUSY; if (Stmt <> nil) Then Exit; //Une erreur précédente. Result := sqlerror; if (sqlerror <> SQLITE_OK) Then Exit; Count := CountSelect(tables,where); Result := -1; if count <= 0 then exit; Select := Format(UPdateStmt,[tables,sets,where]); sqlerror := sqlite3_prepare_v2(DB,pchar(Select),-1,Stmt,tail); if (sqlerror = SQLITE_OK) Then Begin sqlerror := sqlite3_step(Stmt); case sqlerror of SQLITE_ROW: Begin Result := SQLITE_OK; End; SQLITE_DONE: Begin Count := 0; sqlite3_finalize(Stmt); Stmt := nil; sqlerror := SQLITE_OK; Result := SQLITE_OK; End; end; End; if Result <> SQLITE_OK then result := -sqlerror; end; End.
{ Mark Sattolo 428500 } { CSI1100A DGD-1 Chris Lankester } { Test program for Assignment#4 Question#2 } program GetSmallest (input, output); { This program takes an array X with N positive numbers, and a second array Y with M positive numbers, and gives the smallest number that appears in both arrays as the result "Smallest", or sets Smallest to -1 if there is no common element in the two arrays. } { Data Dictionary GIVENS: X, N - X is an array of N positive integers. Y, M - Y is an array of M positive integers. RESULTS: Smallest - the smallest value in both arrays, or -1 if there is no common element. INTERMEDIATES: K - an index in the prompt for values. Count - a counter to keep track of the # of passes through the top module. SmallX - the current smallest value of X. USES: FindSmallX, Compare } type Markarray = array[1..66] of integer; { Need to declare an array type to pass the array to a procedure properly. } var N, M, K, Smallest, Count, SmallX : integer; X, Y : Markarray; DataFile, OutputFile : string; { Datafile and Data are parameters used for input. } Data, Output : text; { OutputFile and Output are used to write the output. } {key : integer;} { controls the # of passes through the outer loop. } {**********************************************************************************} procedure TestX(X : Markarray; N, Previous : integer; var SmallX, I : integer); begin while ((I < (N-1)) and (SmallX <= Previous)) do begin I := I + 1; SmallX := X[I+1] end { while } end; { procedure TestX } {**********************************************************************************} procedure FindSmallX(N : integer; X : Markarray; var SmallX : integer); var I, Previous : integer; begin { FindSmallX } I := 0; Previous := SmallX; SmallX := X[1]; TestX(X, N, Previous, SmallX, I); while (I < (N-1)) do begin I := I + 1; if ((X[I+1] < SmallX) and (X[I+1] > Previous)) then SmallX := X[I+1] else { do nothing } end { while } end; { procedure FindSmallX } {***********************************************************************************} procedure Compare(Y: Markarray; M, SmallX : integer; var Smallest : integer); var J : integer; begin J := 0; while ((J < M) and (Smallest < 0)) do begin J := J + 1; if (Y[J] = SmallX) then Smallest := SmallX else { do nothing} end { while } end; { procedure Compare } {*************************************************************************************} begin { main program } { data input } {write('Enter # of loops: '); read(key); while key > 0 do begin } { set input and output files } {writeln; readln;} write('Enter the name of the input file? '); readln(DataFile); assign(Data, DataFile); reset(Data); write('Enter the name of the output file: '); readln(OutputFile); assign(Output, OutputFile); rewrite(Output); { read the data } read(Data, N); for K := 1 to N do read(Data, X[K]); read(Data, M); for K := 1 to M do read(Data, Y[K]); Close(Data); { initialize the loop } Count := 0; Smallest := -1; SmallX := 0; { start the loop} while ((Count < N) and (Smallest < 0)) do begin FindSmallX(N, X, SmallX); Compare(Y, M, SmallX, Smallest); Count := Count + 1 end; { while } { Print out the results. } writeln(Output); writeln(Output, '*************************************'); writeln(Output, 'Mark Sattolo 428500'); writeln(Output, 'CSI1100A DGD-1 Chris Lankester'); writeln(Output, 'Assignment 4, Question 2'); writeln(Output, '*************************************'); writeln(Output); write(Output, 'The values of X are: '); for K := 1 to N do write(Output, X[K]:3); writeln(Output); writeln(Output); write(Output, 'The values of Y are: '); for K := 1 to M do write(Output, Y[K]:3); writeln(Output); writeln(Output); writeln(Output, 'The value of Smallest is ',Smallest,'.'); writeln(Output); writeln('--------------------------------------------'); writeln('The data has been written to ', OutputFile); writeln('Press CMD-Q to close this window.'); Close(Output); {key := key-1; end } { outer loop } end. { program }
unit csImport; interface uses Classes, csProcessTask, DT_types, l3Base, csMessageManager; type TcsImportTaskItem = class(TddProcessTask) private f_DeleteIncluded: Boolean; f_IsAnnotation: Boolean; f_IsRegion: Boolean; f_MessageManager: TcsMessageManager; f_SourceDir: AnsiString; f_SourceFiles: TStrings; procedure LoadSourceFolderFrom(aStream: TStream); procedure pm_SetSourceFiles(const Value: TStrings); procedure SaveSourceFolderTo(aStream: TStream); protected procedure Cleanup; override; function GetDescription: AnsiString; override; procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override; procedure pm_SetTaskFolder(const Value: AnsiString); override; public constructor Create(aOwner: TObject; aUserID: TUserID); override; procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override; property DeleteIncluded: Boolean read f_DeleteIncluded write f_DeleteIncluded; property IsAnnotation: Boolean read f_IsAnnotation write f_IsAnnotation; property IsRegion: Boolean read f_IsRegion write f_IsRegion; property MessageManager: TcsMessageManager read f_MessageManager write f_MessageManager; property SourceDir: AnsiString read f_SourceDir write f_SourceDir; property SourceFiles: TStrings read f_SourceFiles write pm_SetSourceFiles; published end; TcsAACImport = class(TcsImportTaskItem) public constructor Create(aOwner: TObject; aUserID: TUserID); override; end; implementation uses csTaskTypes, SysUtils, l3FileUtils, ddUtils, StrUtils, l3Types, l3Stream, ddFileIterator; { ****************************** TcsImportTaskItem ******************************* } constructor TcsImportTaskItem.Create(aOwner: TObject; aUserID: TUserID); begin inherited; f_SourceFiles := TStringList.Create; TaskType := cs_ttImport; end; procedure TcsImportTaskItem.Cleanup; begin l3Free(f_SourceFiles); inherited; end; function TcsImportTaskItem.GetDescription: AnsiString; var i: Integer; l_Mask, l_Descript: AnsiString; l_Total, l_Count: Int64; begin if (SourceFiles.Count > 0) and (f_Description = '') then begin case CheckFileType(SourceFiles, IsAnnotation) of dd_itGarant: begin l_Descript:= 'гарант'; l_Mask := '*.nsr'; end; dd_itEverest, dd_itEverestInternal: begin l_Descript:= 'эверест'; l_Mask := '*.evd'; end; dd_itRTFAnnotation : begin l_Descript := 'ms word'; // ddDocReader l_Mask := '*.doc'; end; dd_itTXTAnnotation : begin l_Descript := 'текст'; // evPlainText l_Mask := '*.txt'; end; else begin l_Descript := 'формат неизвестен'; l_Mask := '*.*'; end; end; l_Count:= 0; l_Total:= 0; for i := 0 to Pred(SourceFiles.Count) do begin Inc(l_Total, SizeofFile(SourceFiles.Strings[i])); Inc(l_Count); end; Result:= Format('Импорт файлов %s: %d (%s)', [l_Descript, l_Count, Bytes2Str(l_Total)]); end else Result:= f_Description; end; procedure TcsImportTaskItem.LoadFrom(aStream: TStream; aIsPipe: Boolean); begin inherited; aStream.Read(F_DeleteIncluded, SizeOf(Boolean)); aStream.Read(F_IsAnnotation, SizeOf(Boolean)); aStream.Read(F_IsRegion, SizeOf(Boolean)); ReadString(aStream, f_SourceDir); if aIsPipe then LoadSourceFolderFrom(aStream); end; procedure TcsImportTaskItem.LoadSourceFolderFrom(aStream: TStream); var i, l_Count: Integer; begin aStream.Read(l_Count, SizeOf(Integer)); for i:= 0 to Pred(l_Count) do ReadFileFrom(aStream, TaskFolder); // Заполнить список with TddFileIterator.Make(TaskFolder, '*.*') do try SourceFiles:= FileList; finally Free; end; end; procedure TcsImportTaskItem.pm_SetSourceFiles(const Value: TStrings); begin if f_SourceFiles <> Value then begin f_SourceFiles.Assign(Value); end; end; procedure TcsImportTaskItem.pm_SetTaskFolder(const Value: AnsiString); begin f_TaskFolder := GetUniqFileName(Value, 'Import', ''); end; procedure TcsImportTaskItem.SaveSourceFolderTo(aStream: TStream); var i, l_Count, j: Integer; l_FileName, l_LocalFile, l_LocalFolder: AnsiString; begin l_Count := SourceFiles.Count; aStream.Write(l_Count, SizeOf(Integer)); for i:= 0 to Pred(SourceFiles.Count) do begin l_FileName := SourceFiles.Strings[i]; if AnsiStartsText('###', l_FileName) then begin Delete(l_FileName, 1, 3); l_LocalFile := ExtractFileName(l_FileName); l_LocalFolder := ExtractFilePath(l_FileName); j:= Pred(Length(l_LocalFolder)); while (j > 0) and (l_LocalFolder[j] <> '\') do Dec(j); Delete(l_LocalFolder, 1, j); l_LocalFile := ConcatDirName(l_LocalFolder, l_LocalFile); end else l_LocalFile := ''; WriteFileTo(aStream, l_FileName, l_LocalFile); end; end; procedure TcsImportTaskItem.SaveTo(aStream: TStream; aIsPipe: Boolean); begin inherited; aStream.Write(F_DeleteIncluded, SizeOf(Boolean)); aStream.Write(F_IsAnnotation, SizeOf(Boolean)); aStream.Write(F_IsRegion, SizeOf(Boolean)); WriteString(aStream, f_SourceDir); if aIsPipe then SaveSourceFolderTo(aStream); end; { ****************************** TcsAACImport ******************************* } constructor TcsAACImport.Create(aOwner: TObject; aUserID: TUserID); begin inherited; TaskType := cs_ttAACImport; end; end.
unit MainModule; interface uses uniGUIMainModule, SysUtils, Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, frxClass, frxDBSet, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.Win.ADODB, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Phys.SQLiteVDataSet, FireDAC.DApt, FireDAC.Stan.StorageJSON, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.Phys.IBBase, FireDAC.Comp.UI, FireDAC.Stan.StorageBin; type TUniMainModule = class(TUniGUIMainModule) confd: TFDConnection; fdphysfbdrvrlnkOne: TFDPhysFBDriverLink; fdtrnsctnRead: TFDTransaction; fdtrnsctnWrite: TFDTransaction; fdgxwtcrsrUser: TFDGUIxWaitCursor; fdmtblTripType: TFDMemTable; intgrfldTripTypeID: TIntegerField; strngfldTripTypeTripType: TStringField; dsTripType: TDataSource; fdqryUsers: TFDQuery; lrgntfldUsersID: TLargeintField; strngfldUsersNAME: TStringField; dsUsersAll: TDataSource; fdmtblStatus: TFDMemTable; fdmtblBlock: TFDMemTable; dsStatus: TDataSource; dsBlock: TDataSource; intgrfldStatusValue: TIntegerField; strngfldStatusVString: TStringField; procedure UniGUIMainModuleCreate(Sender: TObject); procedure UniGUIMainModuleDestroy(Sender: TObject); private { Private declarations } public { Public declarations } BlockPost: Boolean; UserPassword: string; SuperUser: Integer; UserID: Integer; end; function UniMainModule: TUniMainModule; implementation {$R *.dfm} uses UniGUIVars, ServerModule, uniGUIApplication, FRegistration; function UniMainModule: TUniMainModule; begin Result := TUniMainModule(UniApplication.UniMainModule); end; procedure TUniMainModule.UniGUIMainModuleCreate(Sender: TObject); begin UserID := 0; SuperUser := 0; UserPassword := ''; // Заполняем таблицу Комондировка-Больничный fdmtblTripType.Active := True; fdmtblTripType.Insert; fdmtblTripType.Fields[0].AsInteger := 0; fdmtblTripType.Fields[1].AsString := 'Командировка'; fdmtblTripType.Post; fdmtblTripType.Insert; fdmtblTripType.Fields[0].AsInteger := 1; fdmtblTripType.Fields[1].AsString := 'Больничный'; fdmtblTripType.Post; //************************************************** //Заполняем таблицу Статус //Заполняем таблицу Статус fdmtblStatus.Active := True; fdmtblStatus.Insert; fdmtblStatus.Fields[0].AsInteger := 0; fdmtblStatus.Fields[1].AsString := 'User'; fdmtblStatus.Post; fdmtblStatus.Insert; fdmtblStatus.Fields[0].AsInteger := 1; fdmtblStatus.Fields[1].AsString := 'Admin'; fdmtblStatus.Post; //**************************************************** //Заполняем таблицу Блокировка fdmtblBlock.Active := True; fdmtblBlock.Insert; fdmtblBlock.Fields[0].AsInteger := 0; fdmtblBlock.Fields[1].AsString := 'Нет'; fdmtblBlock.Post; fdmtblBlock.Insert; fdmtblBlock.Fields[0].AsInteger := 1; fdmtblBlock.Fields[1].AsString := 'Да'; fdmtblBlock.Post; //**************************************************** // Подключаемся к БД fdtrnsctnRead.Options.AutoStart := False; confd.Connected := true; // стартуем Read транзакцию. Она так и будет все время запущена fdtrnsctnRead.StartTransaction; // Код заполнения таблицы fdmtblTripType end; procedure TUniMainModule.UniGUIMainModuleDestroy(Sender: TObject); begin self.fdtrnsctnRead.Commit; self.confd.Connected := false; end; { fdmtblTripType.Active := True; fdmtblTripType.Insert; fdmtblTripType.Fields[0].AsInteger := 0; fdmtblTripType.Fields[1].AsString := 'Командировка'; fdmtblTripType.Post; } initialization RegisterMainModuleClass(TUniMainModule); end.
unit EmailOrdering.Views.MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, EmailOrdering.Controllers.MainControllerInt, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Menus, Vcl.AppEvnts, Vcl.ExtCtrls; type TMainForm = class(TForm) TrayIcon1: TTrayIcon; ApplicationEvents1: TApplicationEvents; PopupMenu1: TPopupMenu; e1: TMenuItem; N2: TMenuItem; Exit2: TMenuItem; procedure TrayIcon1DblClick(Sender: TObject); procedure e1Click(Sender: TObject); procedure Exit2Click(Sender: TObject); procedure ShowBalloonMessage(title, hint: string; flags: TBalloonFlags; orderId:integer); procedure TrayIcon1BalloonClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FOrderID: integer; public { Public declarations } Controller: IMainController; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.e1Click(Sender: TObject); begin controller.ShowMessageForm; end; procedure TMainForm.Exit2Click(Sender: TObject); begin Application.Terminate; end; procedure TMainForm.FormCreate(Sender: TObject); begin self.TrayIcon1.BalloonTitle := 'AviMark Email Ordering'; self.TrayIcon1.BalloonHint := 'Application is running in the system tray'; self.TrayIcon1.ShowBalloonHint; end; procedure TMainForm.ShowBalloonMessage(title, hint: string; flags: TBalloonFlags; orderId:integer); begin self.TrayIcon1.BalloonHint := ''; self.TrayIcon1.BalloonTitle := title; self.TrayIcon1.BalloonHint := hint; self.TrayIcon1.BalloonFlags := flags; self.TrayIcon1.BalloonTimeout := 99999999; self.TrayIcon1.ShowBalloonHint; self.FOrderID := orderId; end; procedure TMainForm.TrayIcon1BalloonClick(Sender: TObject); begin if self.TrayIcon1.BalloonTitle = 'AviMark Email Ordering' then controller.ShowMessageForm else if self.TrayIcon1.BalloonTitle = 'Failure' then self.Controller.OpenFailure else if self.TrayIcon1.BalloonTitle = 'Order successful' then self.Controller.OpenSuccess; end; procedure TMainForm.TrayIcon1DblClick(Sender: TObject); begin controller.ShowMessageForm; end; end.
{ This file is part of the Free Pascal run time library. Copyright (c) 1999-2014 by Maciej Izak aka hnb (NewPascal project) See the file COPYING.FPC, included in this distribution, for details about the copyright. 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. **********************************************************************} unit SmartPtr; {$MODE DELPHI} interface type TSmartPtr<T> = record // similar as overloading [] operators for property x[v: string]: integer read gx write sx; default; Instance: T default; // default keyword for non property. RefCount: PLongint; procedure SmartFinalize(); class operator Initialize(var aRec: TSmartPtr<T>); class operator Finalize(var aRec: TSmartPtr<T>); class operator AddRef(var aRec: TSmartPtr<T>); class operator Copy(constref aSource: TSmartPtr<T>; var aDest: TSmartPtr<T>); // implicit or explicit operator should be used before "default" field class operator Implicit(aValue: T): TSmartPtr<T>; procedure Assign(const aValue: T); end; implementation { TSmartPtr } procedure TSmartPtr<T>.SmartFinalize(); begin if RefCount <> nil then if InterLockedDecrement(RefCount^)=0 then begin FreeMem(RefCount); Dispose(Instance); end; end; class operator TSmartPtr<T>.Initialize(var aRec: TSmartPtr<T>); begin aRec.RefCount := nil; end; class operator TSmartPtr<T>.Finalize(var aRec: TSmartPtr<T>); begin aRec.SmartFinalize(); end; class operator TSmartPtr<T>.AddRef(var aRec: TSmartPtr<T>); begin if aRec.RefCount <> nil then InterLockedIncrement(aRec.RefCount^); end; class operator TSmartPtr<T>.Copy(constref aSource: TSmartPtr<T>; var aDest: TSmartPtr<T>); begin if aDest.RefCount <> nil then aDest.SmartFinalize(); if aSource.RefCount <> nil then InterLockedIncrement(aSource.RefCount^); aDest.RefCount := aSource.RefCount; aDest.Instance := aSource.Instance; end; class operator TSmartPtr<T>.Implicit(aValue: T): TSmartPtr<T>; begin Result.Assign(aValue); end; procedure TSmartPtr<T>.Assign(const aValue: T); begin if RefCount <> nil then SmartFinalize(); GetMem(RefCount, SizeOf(Longint)); RefCount^ := 0; InterLockedIncrement(RefCount^); Instance := aValue; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit Pedidos; interface uses SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QGrids, QDBGrids, QButtons, QExtCtrls, QcurrEdit, Inifiles, DB; type TfrmPedidos = class(TForm) grdListado: TDBGrid; grpBusqueda: TGroupBox; chkCliente: TCheckBox; txtCliente: TEdit; chkPedido: TCheckBox; chkFecha: TCheckBox; txtDiaIni: TEdit; txtMesIni: TEdit; txtAnioIni: TEdit; lblDiagMes1: TLabel; lblDiagDia1: TLabel; btnBuscar: TBitBtn; btnSeleccionar: TBitBtn; btnLimpiar: TBitBtn; rdgOrden: TRadioGroup; txtPedido: TcurrEdit; txtRegistros: TcurrEdit; txtDiaFin: TEdit; txtMesFin: TEdit; txtAnioFin: TEdit; lblDiagMes2: TLabel; lblDiagDia2: TLabel; lblAl: TLabel; Label1: TLabel; procedure btnBuscarClick(Sender: TObject); procedure chkClienteClick(Sender: TObject); procedure chkFechaClick(Sender: TObject); procedure chkPedidoClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnLimpiarClick(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnSeleccionarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FClaveVenta : integer; function VerificaDatos: boolean; procedure RecuperaConfig; public property ClaveVenta: integer read FClaveVenta; end; var frmPedidos: TfrmPedidos; implementation uses dm; {$R *.xfm} procedure TfrmPedidos.btnBuscarClick(Sender: TObject); begin if(VerificaDatos) then begin dmDatos.cdsCliente.Active := false; with dmDatos.qryListados do begin Close; SQL.Clear; SQL.Add('SELECT c.venta, c.caja, c.numero, l.nombre, c.fecha, v.hora, v.iva, v.total '); SQL.Add('FROM comprobantes c LEFT JOIN clientes l ON c.cliente = l.clave'); SQL.Add('LEFT JOIN ventas v ON c.venta = v.clave WHERE c.tipo = ''P'' AND v.estatus = ''A'''); if(chkCliente.Checked) then SQL.Add('AND c.cliente IN (SELECT clave FROM clientes WHERE nombre LIKE ''%' + txtCliente.Text + '%'')'); if(chkFecha.Checked) then begin SQL.Add('AND c.fecha >= ''' + txtMesIni.Text + '/' + txtDiaIni.Text + '/' + txtAnioIni.Text + ''''); SQL.Add('AND c.fecha <= ''' + txtMesFin.Text + '/' + txtDiaFin.Text + '/' + txtAnioFin.Text + ''''); end; if(chkPedido.Checked) then SQL.Add('AND c.numero = ' + txtPedido.Text); case rdgOrden.ItemIndex of 0: SQL.Add('ORDER BY l.nombre, c.numero'); 1: SQL.Add('ORDER BY c.fecha, c.numero'); 2: SQL.Add('ORDER BY c.numero'); end; Open; with dmDatos.cdsCliente do begin Active := true; txtRegistros.Value := RecordCount; FieldByName('caja').DisplayLabel := 'Caja'; FieldByName('caja').DisplayWidth := 4; FieldByName('numero').DisplayLabel := 'Remisión'; FieldByName('numero').DisplayWidth := 8; FieldByName('nombre').DisplayLabel := 'Cliente'; FieldByName('nombre').DisplayWidth := 35; FieldByName('fecha').DisplayLabel := 'Fecha'; FieldByName('fecha').DisplayWidth := 10; FieldByName('hora').DisplayLabel := 'Hora'; FieldByName('hora').DisplayWidth := 7; // FieldByName('estatus').DisplayLabel := 'Estatus'; // FieldByName('estatus').DisplayWidth := 7; // FieldByName('subtotal').DisplayLabel := 'Subtotal'; // FieldByName('subtotal').DisplayWidth := 10; // (FieldByName('subtotal') as TNumericField).DisplayFormat := '#,##0.00'; FieldByName('iva').DisplayLabel := 'I.V.A.'; FieldByName('iva').DisplayWidth := 10; (FieldByName('iva') as TNumericField).DisplayFormat := '#,##0.00'; FieldByName('total').DisplayLabel := 'Total'; FieldByName('total').DisplayWidth := 10; (FieldByName('total') as TNumericField).DisplayFormat := '#,##0.00'; // FieldByName('cliente').Visible := false; // FieldByName('usuario').Visible := false; FieldByName('venta').Visible := False; end; grdListado.SetFocus; end; end; end; procedure TfrmPedidos.chkClienteClick(Sender: TObject); begin txtCliente.Visible := chkCliente.Checked; if(chkCliente.Checked) then txtCliente.SetFocus; end; procedure TfrmPedidos.chkFechaClick(Sender: TObject); begin txtDiaIni.Visible := chkFecha.Checked; txtMesIni.Visible := chkFecha.Checked; txtAnioIni.Visible := chkFecha.Checked; lblDiagDia1.Visible := chkFecha.Checked; lblDiagMes1.Visible := chkFecha.Checked; txtDiaFin.Visible := chkFecha.Checked; txtMesFin.Visible := chkFecha.Checked; txtAnioFin.Visible := chkFecha.Checked; lblDiagDia2.Visible := chkFecha.Checked; lblDiagMes2.Visible := chkFecha.Checked; lblAl.Visible := chkFecha.Checked; if(txtDiaIni.Visible) then txtDiaIni.SetFocus; end; procedure TfrmPedidos.chkPedidoClick(Sender: TObject); begin txtPedido.Visible := chkPedido.Checked; if(chkPedido.Checked) then txtPedido.SetFocus; end; procedure TfrmPedidos.FormShow(Sender: TObject); begin RecuperaConfig; chkClienteClick(Sender); chkFechaClick(Sender); chkPedidoClick(Sender); if(dmDatos.cdsCliente.Active) then txtRegistros.Value := dmDatos.cdsCliente.RecordCount; end; function TfrmPedidos.VerificaDatos: boolean; var dteFecha: TDateTime; begin Result:= true; if(not TryStrToDate(txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text, dteFecha)) and (chkfecha.Checked) then begin Application.MessageBox('Introduzca una fecha inicial válida','Error',[smbOk]); txtDiaIni.SetFocus; Result:= false; end else if(not TryStrToDate(txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text, dteFecha)) and (chkfecha.Checked) then begin Application.MessageBox('Introduzca una fecha final válida','Error',[smbOk]); txtDiaFin.SetFocus; Result:= false; end; end; procedure TfrmPedidos.btnLimpiarClick(Sender: TObject); begin txtCliente.Clear; txtDiaIni.Clear; txtMesIni.Clear; txtAnioIni.Clear; txtDiaFin.Clear; txtMesFin.Clear; txtAnioFin.Clear; txtPedido.Value:= 0; end; procedure TfrmPedidos.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmPedidos.btnSeleccionarClick(Sender: TObject); begin if(txtRegistros.Value > 0) then begin FClaveVenta:= dmDatos.cdsCliente.FieldByName('venta').AsInteger; ModalResult:= mrOk; end; end; procedure TfrmPedidos.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('Pedidos', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('Pedidos', 'Posx', IntToStr(Left)); //Registra el valor de los botones de radio de orden WriteString('Pedidos', 'Orden', IntToStr(rdgOrden.ItemIndex)); if(chkCliente.Checked) then WriteString('Pedidos', 'Cliente', 'S') else WriteString('Pedidos', 'Cliente', 'N'); if(chkFecha.Checked) then WriteString('Pedidos', 'Fecha', 'S') else WriteString('Pedidos', 'Fecha', 'N'); if(chkPedido.Checked) then WriteString('Pedidos', 'Pedido', 'S') else WriteString('Pedidos', 'Pedido', 'N'); Free; end; dmDatos.qryListados.Close; dmDatos.cdsCliente.Active := false; end; procedure TfrmPedidos.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba, sValor : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('Pedidos', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('Pedidos', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; //Recupera el valor de los botones de radio de orden sValor := ReadString('Pedidos', 'Orden', ''); if (Length(sValor) > 0) then rdgOrden.ItemIndex := StrToInt(sValor); sValor := ReadString('Pedidos', 'Cliente', ''); if (sValor = 'S') then chkCliente.Checked := true else chkCliente.Checked := false; sValor := ReadString('Pedidos', 'Fecha', ''); if (sValor = 'S') then chkFecha.Checked := true else chkFecha.Checked := false; sValor := ReadString('Pedidos', 'Pedido', ''); if (sValor = 'S') then chkPedido.Checked := true else chkPedido.Checked := false; Free; end; end; end.
namespace Sugar.Collections; interface uses {$IF ECHOES} System.Linq, {$ELSEIF COOPER} com.remobjects.elements.linq, {$ELSEIF TOFFEE} RemObjects.Elements.Linq, {$ENDIF} Sugar; type List<T> = public class (sequence of T) mapped to {$IF COOPER}java.util.ArrayList<T>{$ELSEIF ECHOES}System.Collections.Generic.List<T>{$ELSEIF TOFFEE}Foundation.NSMutableArray where T is class;{$ENDIF} private public method SetItem(&Index: Integer; Value: T); method GetItem(&Index: Integer): T; constructor; mapped to constructor(); constructor(Items: List<T>); constructor(anArray: array of T); method &Add(anItem: T); method AddRange(Items: List<T>); method AddRange(Items: array of T); method Clear; method Contains(anItem: T): Boolean; method Exists(Match: Predicate<T>): Boolean; method FindIndex(Match: Predicate<T>): Integer; method FindIndex(StartIndex: Integer; Match: Predicate<T>): Integer; method FindIndex(StartIndex: Integer; aCount: Integer; Match: Predicate<T>): Integer; method Find(Match: Predicate<T>): T; method FindAll(Match: Predicate<T>): List<T>; method TrueForAll(Match: Predicate<T>): Boolean; method ForEach(Action: Action<T>); method IndexOf(anItem: T): Integer; method Insert(&Index: Integer; anItem: T); method InsertRange(&Index: Integer; Items: List<T>); method InsertRange(&Index: Integer; Items: array of T); method LastIndexOf(anItem: T): Integer; method &Remove(anItem: T): Boolean; method RemoveAt(&Index: Integer); method RemoveRange(&Index: Integer; aCount: Integer); method Sort(Comparison: Comparison<T>); method ToArray: array of T; {$IF COOPER}inline;{$ENDIF} property Count: Integer read {$IF COOPER}mapped.Size{$ELSEIF ECHOES}mapped.Count{$ELSEIF TOFFEE}mapped.count{$ENDIF}; property Item[i: Integer]: T read GetItem write SetItem; default; {$IF TOFFEE} operator Implicit(aArray: NSArray<T>): List<T>; {$ENDIF} end; Predicate<T> = public block (Obj: T): Boolean; Action<T> = public block (Obj: T); Comparison<T> = public block (x: T; y: T): Integer; {$IF TOFFEE} NullHelper = public static class public method ValueOf(Value: id): id; end; {$ENDIF} ListHelpers = public static class public method AddRange<T>(aSelf: List<T>; aArr: array of T); method FindIndex<T>(aSelf: List<T>;StartIndex: Integer; aCount: Integer; Match: Predicate<T>): Integer; method Find<T>(aSelf: List<T>;Match: Predicate<T>): T; method ForEach<T>(aSelf: List<T>;Action: Action<T>); method TrueForAll<T>(aSelf: List<T>;Match: Predicate<T>): Boolean; method FindAll<T>(aSelf: List<T>;Match: Predicate<T>): List<T>; method InsertRange<T>(aSelf: List<T>; &Index: Integer; Items: array oF T); {$IFDEF TOFFEE} method LastIndexOf<T>(aSelf: NSArray; aItem: T): Integer; method ToArray<T>(aSelf: NSArray): array of T; method ToArrayReverse<T>(aSelf: NSArray): array of T; {$ENDIF} {$IFDEF COOPER} method ToArrayReverse<T>(aSelf: java.util.Vector<T>; aDest: array of T): array of T; {$ENDIF} end; implementation constructor List<T>(Items: List<T>); begin {$IF COOPER} result := new java.util.ArrayList<T>(Items); {$ELSEIF ECHOES} exit new System.Collections.Generic.List<T>(Items); {$ELSEIF TOFFEE} result := new Foundation.NSMutableArray withArray(Items); {$ENDIF} end; constructor List<T>(anArray: array of T); begin {$IF COOPER} result := new java.util.ArrayList<T>(java.util.Arrays.asList(anArray)); {$ELSEIF ECHOES} exit new System.Collections.Generic.List<T>(anArray); {$ELSEIF TOFFEE} result := Foundation.NSMutableArray.arrayWithObjects(^id(@anArray[0])) count(length(anArray)); {$ENDIF} end; method List<T>.Add(anItem: T); begin {$IF COOPER OR ECHOES} mapped.Add(anItem); {$ELSEIF TOFFEE} mapped.addObject(NullHelper.ValueOf(anItem)); {$ENDIF} end; method List<T>.SetItem(&Index: Integer; Value: T); begin {$IF TOFFEE} mapped[&Index] := NullHelper.ValueOf(Value); {$ELSE} mapped[&Index] := Value; {$ENDIF} end; method List<T>.GetItem(&Index: Integer): T; begin {$IF TOFFEE} exit NullHelper.ValueOf(mapped.objectAtIndex(&Index)); {$ELSE} exit mapped[&Index]; {$ENDIF} end; method List<T>.AddRange(Items: List<T>); begin {$IF COOPER} mapped.AddAll(Items); {$ELSEIF ECHOES} mapped.AddRange(Items); {$ELSEIF TOFFEE} mapped.addObjectsFromArray(Items); {$ENDIF} end; method List<T>.AddRange(Items: array of T); begin ListHelpers.AddRange(self, Items); end; method List<T>.Clear; begin {$IF COOPER} mapped.Clear; {$ELSEIF ECHOES} mapped.Clear; {$ELSEIF TOFFEE} mapped.RemoveAllObjects; {$ENDIF} end; method List<T>.Contains(anItem: T): Boolean; begin {$IF COOPER} exit mapped.Contains(anItem); {$ELSEIF ECHOES} exit mapped.Contains(anItem); {$ELSEIF TOFFEE} exit mapped.ContainsObject(NullHelper.ValueOf(anItem)); {$ENDIF} end; method List<T>.Exists(Match: Predicate<T>): Boolean; begin exit self.FindIndex(Match) <> -1; end; method List<T>.FindIndex(Match: Predicate<T>): Integer; begin exit self.FindIndex(0, Count, Match); end; method List<T>.FindIndex(StartIndex: Integer; Match: Predicate<T>): Integer; begin exit self.FindIndex(StartIndex, Count - StartIndex, Match); end; method List<T>.FindIndex(StartIndex: Integer; aCount: Integer; Match: Predicate<T>): Integer; begin exit ListHelpers.FindIndex(self, StartIndex, aCount, Match); end; method List<T>.Find(Match: Predicate<T>): T; begin exit ListHelpers.Find(self, Match); end; method List<T>.FindAll(Match: Predicate<T>): List<T>; begin exit ListHelpers.FindAll(self, Match); end; method List<T>.TrueForAll(Match: Predicate<T>): Boolean; begin exit ListHelpers.TrueForAll(self, Match); end; method List<T>.ForEach(Action: Action<T>); begin ListHelpers.ForEach(self, Action); end; method List<T>.IndexOf(anItem: T): Integer; begin {$IF COOPER} exit mapped.IndexOf(anItem); {$ELSEIF ECHOES} exit mapped.IndexOf(anItem); {$ELSEIF TOFFEE} var lIndex := mapped.indexOfObject(NullHelper.ValueOf(anItem)); exit if lIndex = NSNotFound then -1 else Integer(lIndex); {$ENDIF} end; method List<T>.Insert(&Index: Integer; anItem: T); begin {$IF COOPER} mapped.Add(&Index, anItem); {$ELSEIF ECHOES} mapped.Insert(&Index, anItem); {$ELSEIF TOFFEE} mapped.insertObject(NullHelper.ValueOf(anItem)) atIndex(&Index); {$ENDIF} end; method List<T>.InsertRange(&Index: Integer; Items: List<T>); begin {$IF COOPER} mapped.AddAll(&Index, Items); {$ELSEIF ECHOES} mapped.InsertRange(&Index, Items); {$ELSEIF TOFFEE} mapped.insertObjects(Items) atIndexes(new NSIndexSet withIndexesInRange(NSMakeRange(&Index, Items.Count))); {$ENDIF} end; method List<T>.InsertRange(&Index: Integer; Items: array of T); begin ListHelpers.InsertRange(self, &Index, Items); end; method List<T>.LastIndexOf(anItem: T): Integer; begin {$IF COOPER} exit mapped.LastIndexOf(anItem); {$ELSEIF ECHOES} exit mapped.LastIndexOf(anItem); {$ELSEIF TOFFEE} exit ListHelpers.LastIndexOf(self, anItem); {$ENDIF} end; method List<T>.Remove(anItem: T): Boolean; begin {$IF COOPER} exit mapped.Remove(Object(anItem)); {$ELSEIF ECHOES} exit mapped.Remove(anItem); {$ELSEIF TOFFEE} var lIndex := IndexOf(anItem); if lIndex <> -1 then begin RemoveAt(lIndex); exit true; end; exit false; {$ENDIF} end; method List<T>.RemoveAt(&Index: Integer); begin {$IF COOPER} mapped.remove(&Index); {$ELSEIF ECHOES} mapped.RemoveAt(&Index); {$ELSEIF TOFFEE} mapped.removeObjectAtIndex(&Index); {$ENDIF} end; method List<T>.RemoveRange(&Index: Integer; aCount: Integer); begin {$IF COOPER} mapped.subList(&Index, &Index+aCount).clear; {$ELSEIF ECHOES} mapped.RemoveRange(&Index, aCount); {$ELSEIF TOFFEE} mapped.removeObjectsInRange(Foundation.NSMakeRange(&Index, aCount)); {$ENDIF} end; method List<T>.Sort(Comparison: Comparison<T>); begin {$IF COOPER} java.util.Collections.sort(mapped, new class java.util.Comparator<T>(compare := (x, y) -> Comparison(x, y))); {$ELSEIF ECHOES} mapped.Sort((x, y) -> Comparison(x, y)); {$ELSEIF TOFFEE} mapped.sortUsingComparator((x, y) -> begin var lResult := Comparison(x, y); exit if lResult < 0 then NSComparisonResult.NSOrderedAscending else if lResult = 0 then NSComparisonResult.NSOrderedSame else NSComparisonResult.NSOrderedDescending; end); {$ENDIF} end; method List<T>.ToArray: array of T; begin {$IF COOPER} exit mapped.toArray(new T[mapped.size()]); {$ELSEIF ECHOES} exit mapped.ToArray; {$ELSEIF TOFFEE} exit ListHelpers.ToArray<T>(self); {$ENDIF} end; {$IF TOFFEE} operator List<T>.Implicit(aArray: NSArray<T>): List<T>; begin if aArray is NSMutableArray then result := List<T>(aArray) else result := List<T>(aArray:mutableCopy); end; {$ENDIF} { NullHelper } {$IF TOFFEE} class method NullHelper.ValueOf(Value: id): id; begin exit if Value = NSNull.null then nil else if Value = nil then NSNull.null else Value; end; {$ENDIF} { ListHelpers } method ListHelpers.AddRange<T>(aSelf: List<T>; aArr: array of T); begin for i: Integer := 0 to length(aArr) - 1 do aSelf.Add(aArr[i]); end; method ListHelpers.FindIndex<T>(aSelf: List<T>;StartIndex: Integer; aCount: Integer; Match: Predicate<T>): Integer; begin if StartIndex > aSelf.Count then raise new SugarArgumentOutOfRangeException(ErrorMessage.ARG_OUT_OF_RANGE_ERROR, "StartIndex"); if (aCount < 0) or (StartIndex > aSelf.Count - aCount) then raise new SugarArgumentOutOfRangeException(ErrorMessage.ARG_OUT_OF_RANGE_ERROR, "Count"); if Match = nil then raise new SugarArgumentNullException("Match"); var Length := StartIndex + aCount; for i: Int32 := StartIndex to Length - 1 do if Match(aSelf[i]) then exit i; exit -1; end; method ListHelpers.Find<T>(aSelf: List<T>; Match: Predicate<T>): T; begin if Match = nil then raise new SugarArgumentNullException("Match"); for i: Integer := 0 to aSelf.Count-1 do begin if Match(aSelf[i]) then exit aSelf[i]; end; exit &default(T); end; method ListHelpers.FindAll<T>(aSelf: List<T>; Match: Predicate<T>): List<T>; begin if Match = nil then raise new SugarArgumentNullException("Match"); result := new List<T>(); for i: Integer := 0 to aSelf.Count-1 do begin if Match(aSelf[i]) then result.Add(aSelf[i]); end; end; method ListHelpers.TrueForAll<T>(aSelf: List<T>; Match: Predicate<T>): Boolean; begin if Match = nil then raise new SugarArgumentNullException("Match"); for i: Integer := 0 to aSelf.Count-1 do begin if not Match(aSelf[i]) then exit false; end; exit true; end; method ListHelpers.ForEach<T>(aSelf: List<T>; Action: Action<T>); begin if Action = nil then raise new SugarArgumentNullException("Action"); for i: Integer := 0 to aSelf.Count-1 do Action(aSelf[i]); end; method ListHelpers.InsertRange<T>(aSelf: List<T>; &Index: Integer; Items: array oF T); begin for i: Integer := length(Items) - 1 downto 0 do aSelf.Insert(&Index, Items[i]); end; {$IFDEF TOFFEE} method ListHelpers.LastIndexOf<T>(aSelf: NSArray; aItem: T): Integer; begin var o := NullHelper.ValueOf(aItem); for i: Integer := aSelf.count -1 downto 0 do if aSelf[i] = o then exit i; exit -1; end; method ListHelpers.ToArray<T>(aSelf: NSArray): array of T; begin result := new T[aSelf.count]; for i: Integer := 0 to aSelf.count - 1 do result[i] := aSelf[i]; end; method ListHelpers.ToArrayReverse<T>(aSelf: NSArray): array of T; begin result := new T[aSelf.count]; for i: Integer := aSelf.count - 1 downto 0 do result[aSelf.count - i - 1] := NullHelper.ValueOf(aSelf.objectAtIndex(i)); end; {$ENDIF} {$IFDEF COOPER} method ListHelpers.ToArrayReverse<T>(aSelf: java.util.Vector<T>; aDest: array of T): array of T; begin result := aDest; for i: Integer := aSelf.size - 1 downto 0 do result[aSelf.size - i - 1] := aSelf[i]; end; {$ENDIF} end.
unit InternationalizerComponent; interface uses Windows, SysUtils, Classes; type TInternationalizerComponent = class(TComponent) public constructor Create(Owner : TComponent); override; destructor Destroy; override; private fTransFilesPath : string; fLanguageId : integer; fModifyForm : boolean; fReadAll : boolean; procedure SetTransFilesPath(const path : string); procedure SetLanguageId(languageid : integer); procedure SetModifyForm(modifyform : boolean); private fPropertyNames : TStringList; protected procedure Loaded; override; public procedure GenerateLanguageFile; procedure ModifyProperties; published property TransFilesPath : string read fTransFilesPath write SetTransFilesPath; property ModifyForm : boolean read fModifyForm write SetModifyForm; property LanguageId : integer read fLanguageId write SetLanguageId; property ReadAll : boolean read fReadAll write fReadAll; end; procedure Register; procedure SetBasePath(const transfilespath : string); procedure SetLanguage(languageid : integer); implementation uses TypInfo, Forms, ComCtrls, VisualControls; const cDefaultLanguageId = 0; const cValidPropTypes = [tkString, tkLString, tkClass]; cSimplePropTypes = [tkString, tkLString]; const cDefPropertyCount = 7; const cDefaultProperties : array [1..cDefPropertyCount] of string = ( 'Text', 'Caption', 'Hint', 'Items', 'Lines', 'TabNames', 'Columns' ); // Utils procedure AssignObject(var Dest : TObject; const Source : TObject); begin Dest := Source; end; procedure GetObjectProp(Instance: TObject; PropInfo: PPropInfo; var Value : TObject); assembler; asm { -> EAX Pointer to instance } { EDX Pointer to property info } { ECX Pointer to result object } push esi push edi mov edi, edx mov edx, [edi].TPropInfo.Index { pass index in EDX } cmp edx, $80000000 jne @@hasIndex mov edx, ecx { pass value in EDX } @@hasIndex: mov esi, [edi].TPropInfo.GetProc cmp [edi].TPropInfo.GetProc.Byte[3],$FE ja @@isField jb @@isStaticMethod @@isVirtualMethod: movsx esi, si { sign extend slot offset } add esi, [eax] { vmt + slot offset } call DWORD PTR [esi] jmp @@exit @@isStaticMethod: call esi jmp @@exit @@isField: and esi, $00FFFFFF mov edx, [eax + esi] mov eax, ecx call AssignObject @@exit: pop edi pop esi end; var vInternationalizerComps : TList; vTransFilesPath : string = ''; vLanguageId : integer = 0; procedure RegisterInternationalizer(Internationalizer : TInternationalizerComponent); forward; // TInternationalizerComponent constructor TInternationalizerComponent.Create(Owner : TComponent); var i : integer; begin inherited; fPropertyNames := TStringList.Create; for i := 1 to cDefPropertyCount do fPropertyNames.Add(cDefaultProperties[i]); fLanguageId := cDefaultLanguageId; if csDesigning in ComponentState then if fModifyForm then ModifyProperties else GenerateLanguageFile; if not (csDesigning in ComponentState) then RegisterInternationalizer(Self); end; destructor TInternationalizerComponent.Destroy; begin fPropertyNames.Free; inherited; end; procedure TInternationalizerComponent.SetTransFilesPath(const path : string); begin fTransFilesPath := path; if (fTransFilesPath <> '') and (fTransFilesPath[length(fTransFilesPath)] <> '\') then fTransFilesPath := fTransFilesPath + '\'; end; procedure TInternationalizerComponent.SetLanguageId(languageid : integer); begin fLanguageId := languageid; if fModifyForm then ModifyProperties else if csDesigning in ComponentState then GenerateLanguageFile; end; procedure TInternationalizerComponent.SetModifyForm(modifyform : boolean); begin if fModifyForm <> modifyform then begin fModifyForm := modifyform; if fModifyForm then ModifyProperties else if csDesigning in ComponentState then GenerateLanguageFile; end; end; procedure TInternationalizerComponent.Loaded; begin inherited; end; procedure TInternationalizerComponent.GenerateLanguageFile; var StringFileLines : TStringList; function ReadSimpleProperty(Component : TComponent; PropInfo : PPropInfo) : string; begin if (PropInfo.PropType^.Kind = tkString) or (PropInfo.PropType^.Kind = tkLString) then Result := GetStrProp(Component, PropInfo) else Result := ''; end; procedure ReadStringsProperty(Component : TComponent; PropInfo : PPropInfo); var i : integer; Obj : TObject; Strings : TStrings; begin GetObjectProp(Component, PropInfo, Obj); Strings := TStrings(Obj); if (Strings <> nil) and (Strings.Count > 0) then begin StringFileLines.Add(Component.Name + '.' + PropInfo.Name + '=' + IntToStr(Strings.Count)); for i := 0 to pred(Strings.Count) do StringFileLines.Add(Component.Name + '.' + PropInfo.Name + '.' + IntToStr(i) + '=' + Strings[i]); end; end; procedure ReadListColumnsProperty(Component : TComponent; PropInfo : PPropInfo); var i : integer; Obj : TObject; Columns : TListColumns; begin GetObjectProp(Component, PropInfo, Obj); Columns := TListColumns(Obj); if (Columns <> nil) and (Columns.Count > 0) then begin StringFileLines.Add(Component.Name + '.' + PropInfo.Name + '=' + IntToStr(Columns.Count)); for i := 0 to pred(Columns.Count) do StringFileLines.Add(Component.Name + '.' + PropInfo.Name + '.' + IntToStr(i) + '=' + Columns[i].Caption); end; end; procedure ReadPropertyValues(Component : TComponent); var i : integer; typinfo : PTypeInfo; pc : integer; proplist : PPropList; begin typinfo := Component.ClassInfo; if typinfo <> nil then begin proplist := nil; pc := GetPropList(typinfo, cValidPropTypes, proplist); getmem(proplist, pc*sizeof(PPropInfo)); try GetPropList(typinfo, cValidPropTypes, proplist); for i := 0 to pred(pc) do begin if (fPropertyNames.IndexOf(proplist[i].Name) <> -1) or fReadAll then begin if proplist[i].PropType^.Kind in cSimplePropTypes then StringFileLines.Add(Component.Name + '.' + proplist[i].Name + '=' + ReadSimpleProperty(Component, proplist[i])) else if (proplist[i].PropType^.Kind = tkClass) then if proplist[i].PropType^.Name = 'TStrings' then ReadStringsProperty(Component, proplist[i]) else if proplist[i].PropType^.Name = 'TListColumns' then ReadListColumnsProperty(Component, proplist[i]); end; end; finally freemem(proplist); end; end; for i := 0 to pred(Component.ComponentCount) do ReadPropertyValues(Component.Components[i]); end; var Root : TComponent; begin try Root := Owner; if Root <> nil then begin while (Root.Owner <> nil) and not ((Root is TForm) or (Root is TVisualControl)) and (Root.Owner <> Application) do Root := Root.Owner; StringFileLines := TStringList.Create; try ReadPropertyValues(Root); if fTransFilesPath <> '' then StringFileLines.SaveToFile(fTransFilesPath + IntToStr(fLanguageId) + '\' + Root.Name + '.tln') else StringFileLines.SaveToFile(Root.Name + '.tln'); finally StringFileLines.Free; end; end; except end; end; procedure TInternationalizerComponent.ModifyProperties; var StringFileLines : TStringList; i : integer; compname : string; propname : string; propvalue : string; Root : TComponent; CurComponent : TComponent; PropInfo : PPropInfo; valuecount : integer; function FindComponentInTree(Root : TComponent; const Name : string) : TComponent; var i : integer; begin if Name = Root.Name then Result := Root else begin i := 0; Result := nil; while (Result = nil) and (i < Root.ComponentCount) do begin Result := FindComponentInTree(Root.Components[i], Name); inc(i); end; end; end; procedure ParseFileLine(const fileline : string; out compname, propname, propvalue : string); var tmp : string; begin tmp := fileline; compname := copy(tmp, 1, pos('.', tmp) - 1); delete(tmp, 1, pos('.', tmp)); propname := copy(tmp, 1, pos('=', tmp) - 1); delete(tmp, 1, pos('=', tmp)); propvalue := tmp; end; procedure WriteSimpleProperty(Component : TComponent; PropInfo : PPropInfo; const PropValue : string); begin case PropInfo.PropType^.Kind of tkString, tkLString: SetStrProp(Component, PropInfo, PropValue); end; end; procedure LoadStringsProperty(Component : TComponent; PropInfo : PPropInfo; curidx, strcount : integer); var Obj : TObject; Strings : TStrings; i : integer; begin try GetObjectProp(Component, PropInfo, Obj); Strings := TStrings(Obj); if Strings <> nil then begin Strings.Clear; for i := curidx to pred(curidx + strcount) do begin ParseFileLine(StringFileLines[i], compname, propname, propvalue); Strings.Add(propvalue); end; end; except end; end; procedure LoadColumnsProperty(Component : TComponent; PropInfo : PPropInfo; curidx, colcount : integer); var Obj : TObject; Columns : TListColumns; i, j : integer; begin try GetObjectProp(Component, PropInfo, Obj); Columns := TListColumns(Obj); if Columns <> nil then begin j := 0; for i := curidx to pred(curidx + colcount) do begin ParseFileLine(StringFileLines[i], compname, propname, propvalue); Columns[j].Caption := propvalue; inc(j); end; end; except end; end; begin try Root := Owner; if (Root <> nil) and FileExists(fTransFilesPath + IntToStr(fLanguageId) + '\' + Root.Name + '.tln') then begin while (Root.Owner <> nil) and not ((Root is TForm) or (Root is TVisualControl)) and (Root.Owner <> Application) do Root := Root.Owner; StringFileLines := TStringList.Create; try StringFileLines.LoadFromFile(fTransFilesPath + IntToStr(fLanguageId) + '\' + Root.Name + '.tln'); CurComponent := nil; i := 0; while i < StringFileLines.Count do begin ParseFileLine(StringFileLines[i], compname, propname, propvalue); if (CurComponent = nil) or (compname <> CurComponent.Name) then CurComponent := FindComponentInTree(Root, compname); if (CurComponent <> nil) and (CurComponent.ClassInfo <> nil) then begin PropInfo := GetPropInfo(CurComponent.ClassInfo, propname); if (PropInfo <> nil) then if PropInfo.PropType^.Kind in cSimplePropTypes then begin WriteSimpleProperty(CurComponent, PropInfo, propvalue); inc(i); end else begin valuecount := StrToInt(propvalue); if PropInfo.PropType^.Name = 'TStrings' then LoadStringsProperty(CurComponent, PropInfo, i + 1, valuecount) else if PropInfo.PropType^.Name = 'TListColumns' then LoadColumnsProperty(CurComponent, PropInfo, i + 1, valuecount); inc(i, valuecount + 1); end else inc(i); end else inc(i); end; finally StringFileLines.Free; end; end; except end; end; procedure Register; begin RegisterComponents('Samples', [TInternationalizerComponent]); end; procedure RegisterInternationalizer(Internationalizer : TInternationalizerComponent); begin Internationalizer.TransFilesPath := vTransFilesPath; Internationalizer.LanguageId := vLanguageId; if vTransFilesPath <> '' then Internationalizer.ModifyForm := true; vInternationalizerComps.Add(Internationalizer); end; procedure SetBasePath(const transfilespath : string); var i : integer; begin vTransFilesPath := transfilespath; for i := 0 to pred(vInternationalizerComps.Count) do TInternationalizerComponent(vInternationalizerComps[i]).TransFilesPath := transfilespath; end; procedure SetLanguage(languageid : integer); var i : integer; begin vLanguageId := languageid; for i := 0 to pred(vInternationalizerComps.Count) do begin TInternationalizerComponent(vInternationalizerComps[i]).LanguageId := languageid; if vTransFilesPath <> '' then TInternationalizerComponent(vInternationalizerComps[i]).ModifyForm := true; end; end; initialization vInternationalizerComps := TList.Create; finalization vInternationalizerComps.Free; end.
{ File: CMDeviceIntegration.p Contains: Color Management Device Interfaces - for MacOSX Version: Technology: ColorSync 3.1 Release: Universal Interfaces 3.4.2 Copyright: © 2000-2002 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CMDeviceIntegration; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CFDictionary,CMTypes,CMApplication,CMICCProfile,CFString; {$ALIGN MAC68K} {$ifc TARGET_API_MAC_OSX} { The current versions of the data structure containing information on registered devices. } const cmDeviceInfoVersion1 = $00010000; cmDeviceProfileInfoVersion1 = $00010000; cmCurrentDeviceInfoVersion = $00010000; cmCurrentProfileInfoVersion = $00010000; { Certain APIs require a device ID or profile ID. In some cases, a "default ID" can be used. } cmDefaultDeviceID = 0; cmDefaultProfileID = 0; { Possible values for device states accessible by the CMGetDeviceState() and CMSetDeviceState() APIs. } cmDeviceStateDefault = $00000000; cmDeviceStateOffline = $00000001; cmDeviceStateBusy = $00000002; cmDeviceStateForceNotify = $80000000; cmDeviceStateDeviceRsvdBits = $00FF0000; cmDeviceStateAppleRsvdBits = $FF00FFFF; { Possible values for flags passed to the CMIterateDeviceProfiles() API. "Factory" profiles are registered via the CMSetDeviceFactoryProfiles() API. "Custom" profiles are those which are meant to take the place of the factory profiles, as a result of customization or calibration. These profiles are registered via the CMSetDeviceProfiles() API. To retrieve all of the the former for all devices, use cmIterateFactoryDeviceProfiles as the flags value when calling CMIterateDeviceProfiles(). To retrieve only the latter for all devices, use the cmIterateCustomDeviceProfiles, as the flags value when calling CMIterateDeviceProfiles(). To get the profiles in use for all devices, use cmIterateCurrentDeviceProfiles as the flags value. This will replace the factory profiles with any overrides, yielding the currently used set. } cmIterateFactoryDeviceProfiles = $00000001; cmIterateCustomDeviceProfiles = $00000002; cmIterateCurrentDeviceProfiles = $00000003; cmIterateDeviceProfilesMask = $00000003; kMaxDeviceNameLength = 256; kMaxProfileNameLength = 256; { Errors returned by CMDeviceIntegration APIs } cmDeviceDBNotFoundErr = -4227; { Prefs not found/loaded } cmDeviceAlreadyRegistered = -4228; { Re-registration of device } cmDeviceNotRegistered = -4229; { Device not found } cmDeviceProfilesNotFound = -4230; { Profiles not found } cmInternalCFErr = -4231; { CoreFoundation failure } { Device state data. } type CMDeviceState = UInt32; { A CMDeviceID must be unique within a device's class. } CMDeviceID = UInt32; { A CMDeviceProfileID must only be unique per device. } CMDeviceProfileID = UInt32; { DeviceClass type. } const cmScannerDeviceClass = FourCharCode('scnr'); cmCameraDeviceClass = FourCharCode('cmra'); cmDisplayDeviceClass = FourCharCode('mntr'); cmPrinterDeviceClass = FourCharCode('prtr'); cmProofDeviceClass = FourCharCode('pruf'); type CMDeviceClass = OSType; { CMDeviceScope Structure specifying a device's or a device setting's scope. } CMDeviceScopePtr = ^CMDeviceScope; CMDeviceScope = record deviceUser: CFStringRef; { kCFPreferencesCurrentUser | _AnyUser } deviceHost: CFStringRef; { kCFPreferencesCurrentHost | _AnyHost } end; { CMDeviceInfo Structure containing information on a given device. } CMDeviceInfoPtr = ^CMDeviceInfo; CMDeviceInfo = record dataVersion: UInt32; { cmDeviceInfoVersion1 } deviceClass: CMDeviceClass; { device class } deviceID: CMDeviceID; { device ID } deviceScope: CMDeviceScope; { device's scope } deviceState: CMDeviceState; { Device State flags } defaultProfileID: CMDeviceProfileID; { Can change } deviceName: ^CFDictionaryRef; { Ptr to storage for CFDictionary of } { localized device names (could be nil) } profileCount: UInt32; { Count of registered profiles } reserved: UInt32; { Reserved for use by ColorSync } end; { CMDeviceProfileInfo Structure containing information on a device profile. } CMDeviceProfileInfoPtr = ^CMDeviceProfileInfo; CMDeviceProfileInfo = record dataVersion: UInt32; { cmProfileInfoVersion1 } profileID: CMDeviceProfileID; { The identifier for this profile } profileLoc: CMProfileLocation; { The profile's location } profileName: CFDictionaryRef; { CFDictionary of localized device names } reserved: UInt32; { Reserved for use by ColorSync } end; { CMDeviceProfileArray Structure containing the profiles for a device. } CMDeviceProfileArrayPtr = ^CMDeviceProfileArray; CMDeviceProfileArray = record profileCount: UInt32; { Count of profiles in array } profiles: array [0..0] of CMDeviceProfileInfo; { The profile info records } end; { Caller-supplied iterator functions } {$ifc TYPED_FUNCTION_POINTERS} CMIterateDeviceInfoProcPtr = function(const (*var*) deviceInfo: CMDeviceInfo; refCon: UnivPtr): OSErr; {$elsec} CMIterateDeviceInfoProcPtr = ProcPtr; {$endc} {$ifc TYPED_FUNCTION_POINTERS} CMIterateDeviceProfileProcPtr = function(const (*var*) deviceInfo: CMDeviceInfo; const (*var*) profileData: CMDeviceProfileInfo; refCon: UnivPtr): OSErr; {$elsec} CMIterateDeviceProfileProcPtr = ProcPtr; {$endc} { Device Registration } { * CMRegisterColorDevice() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMRegisterColorDevice(deviceClass: CMDeviceClass; deviceID: CMDeviceID; deviceName: CFDictionaryRef; const (*var*) deviceScope: CMDeviceScope): CMError; external name '_CMRegisterColorDevice'; { * CMUnregisterColorDevice() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMUnregisterColorDevice(deviceClass: CMDeviceClass; deviceID: CMDeviceID): CMError; external name '_CMUnregisterColorDevice'; { Default Device accessors } { * CMSetDefaultDevice() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMSetDefaultDevice(deviceClass: CMDeviceClass; deviceID: CMDeviceID): CMError; external name '_CMSetDefaultDevice'; { * CMGetDefaultDevice() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDefaultDevice(deviceClass: CMDeviceClass; var deviceID: CMDeviceID): CMError; external name '_CMGetDefaultDevice'; { Device Profile Registration & Access } { * CMSetDeviceFactoryProfiles() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMSetDeviceFactoryProfiles(deviceClass: CMDeviceClass; deviceID: CMDeviceID; defaultProfID: CMDeviceProfileID; const (*var*) deviceProfiles: CMDeviceProfileArray): CMError; external name '_CMSetDeviceFactoryProfiles'; { * CMGetDeviceFactoryProfiles() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDeviceFactoryProfiles(deviceClass: CMDeviceClass; deviceID: CMDeviceID; var defaultProfID: CMDeviceProfileID; var arraySize: UInt32; var deviceProfiles: CMDeviceProfileArray): CMError; external name '_CMGetDeviceFactoryProfiles'; { * CMSetDeviceProfiles() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMSetDeviceProfiles(deviceClass: CMDeviceClass; deviceID: CMDeviceID; const (*var*) profileScope: CMDeviceScope; const (*var*) deviceProfiles: CMDeviceProfileArray): CMError; external name '_CMSetDeviceProfiles'; { * CMGetDeviceProfiles() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDeviceProfiles(deviceClass: CMDeviceClass; deviceID: CMDeviceID; var arraySize: UInt32; var deviceProfiles: CMDeviceProfileArray): CMError; external name '_CMGetDeviceProfiles'; { * CMSetDeviceDefaultProfileID() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMSetDeviceDefaultProfileID(deviceClass: CMDeviceClass; deviceID: CMDeviceID; defaultProfID: CMDeviceProfileID): CMError; external name '_CMSetDeviceDefaultProfileID'; { * CMGetDeviceDefaultProfileID() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDeviceDefaultProfileID(deviceClass: CMDeviceClass; deviceID: CMDeviceID; var defaultProfID: CMDeviceProfileID): CMError; external name '_CMGetDeviceDefaultProfileID'; { * CMGetDeviceProfile() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDeviceProfile(deviceClass: CMDeviceClass; deviceID: CMDeviceID; profileID: CMDeviceProfileID; var deviceProfLoc: CMProfileLocation): CMError; external name '_CMGetDeviceProfile'; { * CMSetDeviceProfile() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMSetDeviceProfile(deviceClass: CMDeviceClass; deviceID: CMDeviceID; const (*var*) profileScope: CMDeviceScope; profileID: CMDeviceProfileID; const (*var*) deviceProfLoc: CMProfileLocation): CMError; external name '_CMSetDeviceProfile'; { Other Device State/Info accessors } { * CMSetDeviceState() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMSetDeviceState(deviceClass: CMDeviceClass; deviceID: CMDeviceID; deviceState: CMDeviceState): CMError; external name '_CMSetDeviceState'; { * CMGetDeviceState() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDeviceState(deviceClass: CMDeviceClass; deviceID: CMDeviceID; var deviceState: CMDeviceState): CMError; external name '_CMGetDeviceState'; { * CMGetDeviceInfo() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMGetDeviceInfo(deviceClass: CMDeviceClass; deviceID: CMDeviceID; var deviceInfo: CMDeviceInfo): CMError; external name '_CMGetDeviceInfo'; { Device Data & Profile Iterators } { * CMIterateColorDevices() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMIterateColorDevices(proc: CMIterateDeviceInfoProcPtr; var seed: UInt32; var count: UInt32; refCon: UnivPtr): CMError; external name '_CMIterateColorDevices'; { * CMIterateDeviceProfiles() * * Availability: * Non-Carbon CFM: not available * CarbonLib: not available * Mac OS X: in 3.1 and later } function CMIterateDeviceProfiles(proc: CMIterateDeviceProfileProcPtr; var seed: UInt32; var count: UInt32; flags: UInt32; refCon: UnivPtr): CMError; external name '_CMIterateDeviceProfiles'; {$endc} {TARGET_API_MAC_OSX} {$ALIGN MAC68K} end.
unit BorlndMM; interface {--------------------Start of options block-------------------------} {Set the following option to use the RTL MM instead of FastMM. Setting this option makes this replacement DLL almost identical to the default borlndmm.dll, unless the "FullDebugMode" option is also set.} {.$define UseRTLMM} {--------------------End of options block-------------------------} {$Include FastMM4Options.inc} {Cannot use the RTL MM with full debug mode} {$ifdef FullDebugMode} {$undef UseRTLMM} {$endif} function GetAllocMemCount: integer; function GetAllocMemSize: integer; procedure DumpBlocks; function HeapRelease: Integer; function HeapAddRef: Integer; function SysReallocMem(P: Pointer; Size: Integer): Pointer; function SysFreeMem(P: Pointer): Integer; function SysGetMem(Size: Integer): Pointer; function SysAllocMem(Size: Cardinal): Pointer; function ReallocMemory(P: Pointer; Size: Integer): Pointer; cdecl; function FreeMemory(P: Pointer): Integer; cdecl; function GetMemory(Size: Integer): Pointer; cdecl; function GetHeapStatus: THeapStatus; deprecated; platform; function RegisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; function UnregisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; implementation {$ifndef UseRTLMM} uses FastMM4; {$endif} {$OPTIMIZATION ON} {$STACKFRAMES OFF} {$RANGECHECKS OFF} {$OVERFLOWCHECKS OFF} {$ifdef NoDebugInfo} {$DEBUGINFO OFF} {$endif} //Export: GetAllocMemCount //Symbol: @Borlndmm@GetAllocMemCount$qqrv function GetAllocMemCount: integer; begin {Return stats for the RTL MM only} {$ifdef UseRTLMM} Result := System.AllocMemCount; {$else} Result := 0; {$endif} end; //Export: GetAllocMemSize //Symbol: @Borlndmm@GetAllocMemSize$qqrv function GetAllocMemSize: integer; begin {Return stats for the RTL MM only} {$ifdef UseRTLMM} Result := System.AllocMemSize; {$else} Result := 0; {$endif} end; //Export: DumpBlocks //Symbol: @Borlndmm@DumpBlocks$qqrv procedure DumpBlocks; begin {Do nothing} end; //Export: @Borlndmm@HeapRelease$qqrv //Symbol: @Borlndmm@HeapRelease$qqrv function HeapRelease: Integer; begin {Do nothing} Result := 2; end; //Export: @Borlndmm@HeapAddRef$qqrv //Symbol: @Borlndmm@HeapAddRef$qqrv function HeapAddRef: Integer; begin {Do nothing} Result := 2; end; //Export: GetHeapStatus //Symbol: @Borlndmm@GetHeapStatus$qqrv function GetHeapStatus: THeapStatus; deprecated; platform; begin {$ifndef UseRTLMM} Result := FastGetHeapStatus; {$else} Result := System.GetHeapStatus; {$endif} end; //Export: ReallocMemory //Symbol: @Borlndmm@ReallocMemory$qpvi function ReallocMemory(P: Pointer; Size: Integer): Pointer; cdecl; begin Result := System.ReallocMemory(P, Size); end; //Export: FreeMemory //Symbol: @Borlndmm@FreeMemory$qpv function FreeMemory(P: Pointer): Integer; cdecl; begin Result := System.FreeMemory(P); end; //Export: GetMemory //Symbol: @Borlndmm@GetMemory$qi function GetMemory(Size: Integer): Pointer; cdecl; begin Result := System.GetMemory(Size); end; //Export: @Borlndmm@SysReallocMem$qqrpvi //Symbol: @Borlndmm@SysReallocMem$qqrpvi function SysReallocMem(P: Pointer; Size: Integer): Pointer; begin {$ifndef UseRTLMM} {$ifndef FullDebugMode} Result := FastReallocMem(P, Size); {$else} Result := DebugReallocMem(P, Size); {$endif} {$else} Result := System.SysReallocMem(P, Size); {$endif} end; //Export: @Borlndmm@SysFreeMem$qqrpv //Symbol: @Borlndmm@SysFreeMem$qqrpv function SysFreeMem(P: Pointer): Integer; begin {$ifndef UseRTLMM} {$ifndef FullDebugMode} Result := FastFreeMem(P); {$else} Result := DebugFreeMem(P); {$endif} {$else} Result := System.SysFreeMem(P); {$endif} end; //Export: @Borlndmm@SysGetMem$qqri //Symbol: @Borlndmm@SysGetMem$qqri function SysGetMem(Size: Integer): Pointer; begin {$ifndef UseRTLMM} {$ifndef FullDebugMode} Result := FastGetMem(Size); {$else} Result := DebugGetMem(Size); {$endif} {$else} Result := System.SysGetMem(Size); {$endif} end; //Export: @Borlndmm@SysAllocMem$qqri //Symbol: @Borlndmm@SysAllocMem$qqrui function SysAllocMem(Size: Cardinal): Pointer; begin {$ifndef UseRTLMM} {$ifndef FullDebugMode} Result := FastAllocMem(Size); {$else} Result := DebugAllocMem(Size); {$endif} {$else} //{$ifdef VER180} {$if RTLVersion >= 18} Result := System.SysAllocMem(Size); {$ifend} {$if RTLVersion < 18} Result := System.AllocMem(Size); {$ifend} {$endif} end; //Export: @Borlndmm@SysUnregisterExpectedMemoryLeak$qqrpi //Symbol: @Borlndmm@UnregisterExpectedMemoryLeak$qqrpv function UnregisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; begin {$ifndef UseRTLMM} {$ifdef EnableMemoryLeakReporting} Result := UnregisterExpectedMemoryLeak(ALeakedPointer); {$else} Result := False; {$endif} {$else} //{$ifdef VER180} {$if RTLVersion >= 18} Result := System.SysUnregisterExpectedMemoryLeak(ALeakedPointer); {$ifend} {$if RTLVersion < 18} Result := False; {$ifend} {$endif} end; //Export: @Borlndmm@SysRegisterExpectedMemoryLeak$qqrpi //Symbol: @Borlndmm@RegisterExpectedMemoryLeak$qqrpv function RegisterExpectedMemoryLeak(ALeakedPointer: Pointer): Boolean; begin {$ifndef UseRTLMM} {$ifdef EnableMemoryLeakReporting} Result := RegisterExpectedMemoryLeak(ALeakedPointer); {$else} Result := False; {$endif} {$else} //{$ifdef VER180} {$if RTLVersion >= 18} Result := System.SysRegisterExpectedMemoryLeak(ALeakedPointer); {$ifend} {$if RTLVersion < 18} Result := False; {$ifend} {$endif} end; initialization IsMultiThread := True; finalization end.
program FileHandling; {$mode objfpc}{$H+} { Example 08 File Handling } { } { This example demonstrates just a few basic functions of file handling which } { is a major topic in itself. } { } { For more information on all of the available file function see the Ultibo } { Wiki or the Free Pascal user guide. } { } { To compile the example select Run, Compile (or Run, Build) from the menu. } { } { Once compiled copy the kernel7.img file to an SD card along with the } { firmware files and use it to boot your Raspberry Pi. } { } { Raspberry Pi 2B version } { What's the difference? See Project, Project Options, Config and Target. } { After the first time that kernel7.img has been transferred to micro sd card } { tftp xx.xx.xx.xx < cmdstftp } { contents of cmdstftp } { binary } { put kernel7.img } { quit } uses {InitUnit, Include InitUnit to allow us to change the startup behaviour} RaspberryPi2, {Include RaspberryPi2 to make sure all standard functions are included} GlobalConst, GlobalTypes, Platform, Threads, Console, Classes, {Include the common classes} HTTP, {Include HTTP and WebStatus so we can see from a web browser what is happening} WebStatus, Framebuffer, BCM2836, SysUtils, { TimeToStr & Time } Logging, uTFTP, Winsock2, FileSystem, {Include the file system core and interfaces} FATFS, {Include the FAT file system driver} MMC, {Include the MMC/SD core to access our SD card} BCM2709, {And also include the MMC/SD driver for the Raspberry Pi} Shell, ShellFilesystem, ShellUpdate, RemoteShell; { needed for telnet } var Count:Integer; Filename:String; SearchRec:TSearchRec; StringList:TStringList; FileStream:TFileStream; LeftWindow:TWindowHandle; HTTPListener:THTTPListener; { needed to use ultibo-tftp } TCP : TWinsock2TCPClient; IPAddress : string; function WaitForIPComplete : string; var TCP : TWinsock2TCPClient; begin TCP := TWinsock2TCPClient.Create; Result := TCP.LocalAddress; if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then begin while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do begin sleep (1500); Result := TCP.LocalAddress; end; end; TCP.Free; end; procedure Msg (Sender : TObject; s : string); begin ConsoleWindowWriteLn (LeftWindow, s); end; procedure WaitForSDDrive; begin while not DirectoryExists ('C:\') do sleep (500); end; begin {The following 3 lines are logging to the console CONSOLE_REGISTER_LOGGING:=True; LoggingConsoleDeviceAdd(ConsoleDeviceGetDefault); LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_CONSOLE)); } {The following 2 lines are logging to a file LoggingDeviceSetTarget(LoggingDeviceFindByType(LOGGING_TYPE_FILE),'c:\ultibologging.log'); LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_FILE)); } {Create a console window to show what is happening} LeftWindow:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_LEFT,True); {Display a startup message on the console} ConsoleWindowWriteLn(LeftWindow,'Starting TFTP_Template example'); // wait for IP address and SD Card to be initialised. WaitForSDDrive; IPAddress := WaitForIPComplete; {Create and start the HTTP Listener for our web status page} HTTPListener:=THTTPListener.Create; HTTPListener.Active:=True; ConsoleWindowWriteLn (LeftWindow, 'Local Address ' + IPAddress); SetOnMsg (@Msg); {Register the web status page, the "Thread List" page will allow us to see what is happening in the example} WebStatusRegister(HTTPListener,'','',True); {To list the contents we need to use FindFirst/FindNext, start with FindFirst} if FindFirst('C:\*.*',faAnyFile,SearchRec) = 0 then begin {If FindFirst succeeds it will return 0 and we can proceed with the search} repeat {Print the file found to the screen} ConsoleWindowWriteLn(LeftWindow,'Filename is ' + SearchRec.Name + ' - Size is ' + IntToStr(SearchRec.Size) + ' - Time is ' + DateTimeToStr(FileDateToDateTime(SearchRec.Time))); {We keep calling FindNext until there are no more files to find} until FindNext(SearchRec) <> 0; end; {After any call to FindFirst, you must call FindClose or else memory will be leaked} FindClose(SearchRec); ConsoleWindowWriteLn(LeftWindow,''); {Let's try creating a file and writing some text to it, we'll assign our filename to a variable.} Filename:='C:\test0513.txt'; {We should check if the file exists first before trying to create it} ConsoleWindowWriteLn(LeftWindow,'Checking to see if ' + Filename + ' exists'); if FileExists(Filename) then begin {If it does exist we can delete it} ConsoleWindowWriteLn(LeftWindow,'Deleting the file ' + Filename); DeleteFile(Filename); end; {Now create the file, let's use a TFileStream class to do this. We pass both the filename and the mode to TFileStream. fmCreate tells it to create a new file.} ConsoleWindowWriteLn(LeftWindow,'Creating a new file ' + Filename); {TFileStream will raise an exception if creating the file fails} try FileStream:=TFileStream.Create(Filename,fmCreate); {We've created the file, now we need to write some content to it, we can use a TStringList for that but there are many other ways as well.} StringList:=TStringList.Create; {Add some text to our string list} StringList.Add('Example 08 File Handling'); StringList.Add('This is a test file created by the example'); StringList.Add('Here is a another line of text as well.'); {Since TStringList has a SaveToStream method, we can just call that to write all the strings to our new file.} ConsoleWindowWriteLn(LeftWindow,'Saving the TStringList to the file'); StringList.SaveToStream(FileStream); {With that done we can close the file and free the string list} ConsoleWindowWriteLn(LeftWindow,'Closing the file'); ConsoleWindowWriteLn(LeftWindow,''); FileStream.Free; StringList.Free; {Did it work? Let's open the file and display it on screen to see.} ConsoleWindowWriteLn(LeftWindow,'Opening the file ' + Filename); try FileStream:=TFileStream.Create(Filename,fmOpenReadWrite); {Recreate our string list} StringList:=TStringList.Create; {And use LoadFromStream to read it} ConsoleWindowWriteLn(LeftWindow,'Loading the TStringList from the file'); StringList.LoadFromStream(FileStream); {Iterate the strings and print them to the screen} ConsoleWindowWriteLn(LeftWindow,'The contents of the file are:'); for Count:=0 to StringList.Count - 1 do begin ConsoleWindowWriteLn(LeftWindow,StringList.Strings[Count]); end; {Close the file and free the string list again} ConsoleWindowWriteLn(LeftWindow,'Closing the file'); ConsoleWindowWriteLn(LeftWindow,''); FileStream.Free; StringList.Free; {If you remove the SD card and put in back in your computer, you should see the file "Example 08 File Handling.txt" on it. If you open it in a notepad you should see the contents exactly as they appeared on screen.} except {TFileStream couldn't open the file} ConsoleWindowWriteLn(LeftWindow,'Failed to open the file ' + Filename); end; except {Something went wrong creating the file} ConsoleWindowWriteLn(LeftWindow,'Failed to create the file ' + Filename); end; {Halt this thread} ThreadHalt(0); end.
{ *************************************************************************** Copyright (c) 2015-2020 Kike Pérez Unit : Quick.Options.Serializer.Yaml Description : Configuration groups Yaml Serializer Author : Kike Pérez Version : 1.0 Created : 18/10/2019 Modified : 15/12/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.Options.Serializer.Yaml; {$i QuickLib.inc} interface uses System.SysUtils, System.IOUtils, System.Generics.Collections, Quick.YAML, Quick.Commons, Quick.YAML.Serializer, Quick.Options; type TYamlOptionsSerializer = class(TOptionsFileSerializer) private fSerializer : TRTTIYaml; function ParseFile(out aYamlObj : TYamlObject) : Boolean; public constructor Create(const aFilename : string); destructor Destroy; override; function Load(aSections : TSectionList; aFailOnSectionNotExists : Boolean) : Boolean; override; function LoadSection(aSections : TSectionList; aOptions: TOptions) : Boolean; override; procedure Save(aSections : TSectionList); override; function GetFileSectionNames(out oSections : TArray<string>) : Boolean; override; function ConfigExists : Boolean; override; end; implementation { TYamlOptionsSerializer } function TYamlOptionsSerializer.ConfigExists: Boolean; begin Result := FileExists(Filename); end; constructor TYamlOptionsSerializer.Create(const aFilename : string); begin Filename := aFilename; fSerializer := TRTTIYaml.Create(TSerializeLevel.slPublishedProperty,True); end; destructor TYamlOptionsSerializer.Destroy; begin fSerializer.Free; inherited; end; function TYamlOptionsSerializer.GetFileSectionNames(out oSections : TArray<string>) : Boolean; var yaml : TYamlObject; i : Integer; begin Result := False; yaml := nil; if ParseFile(yaml) then begin try for i := 0 to yaml.Count - 1 do begin oSections := oSections + [yaml.Pairs[i].Name]; end; Result := True; finally yaml.Free; end; end; end; function TYamlOptionsSerializer.ParseFile(out aYamlObj : TYamlObject) : Boolean; var fileoptions : string; begin aYamlObj := nil; if FileExists(Filename) then begin fileoptions := TFile.ReadAllText(Filename,TEncoding.UTF8); if fileoptions.IsEmpty then EOptionLoadError.CreateFmt('Config file "%s" is empty!',[ExtractFileName(Filename)]); aYamlObj := TYamlObject.ParseYAMLValue(fileoptions) as TYamlObject; if aYamlObj = nil then raise EOptionLoadError.CreateFmt('Config file "%s" is damaged or not well-formed Yaml format!',[ExtractFileName(Filename)]); end; Result := aYamlObj <> nil; end; function TYamlOptionsSerializer.Load(aSections : TSectionList; aFailOnSectionNotExists : Boolean) : Boolean; var option : TOptions; yaml : TYamlObject; ypair : TYamlPair; found : Integer; begin Result := False; //read option file if ParseFile(yaml) then begin found := 0; try for option in aSections do begin ypair := fSerializer.GetYamlPairByName(yaml,option.Name); if ypair = nil then begin if aFailOnSectionNotExists then raise Exception.CreateFmt('Config section "%s" not found',[option.Name]) else begin //count as found if hidden if option.HideOptions then Inc(found); Continue; end; end; if ypair.Value <> nil then begin //deserialize option fSerializer.DeserializeObject(option,ypair.Value as TYamlObject); //validate loaded configuration option.ValidateOptions; Inc(found); end; end; finally yaml.Free; end; //returns true if all sections located into file Result := found = aSections.Count; end; end; function TYamlOptionsSerializer.LoadSection(aSections : TSectionList; aOptions: TOptions) : Boolean; var yaml : TYamlObject; ypair : TYamlPair; begin Result := False; //read option file if ParseFile(yaml) then begin try ypair := fSerializer.GetYamlPairByName(yaml,aOptions.Name); if (ypair <> nil) and (ypair.Value <> nil) then begin //deserialize option fSerializer.DeserializeObject(aOptions,ypair.Value as TYamlObject); //validate loaded configuration aOptions.ValidateOptions; Result := True; end finally yaml.Free; end; end; end; procedure TYamlOptionsSerializer.Save(aSections : TSectionList); var option : TOptions; fileoptions : string; yaml : TYamlObject; jpair : TYamlPair; begin yaml := TYamlObject.Create; try for option in aSections do begin if not option.HideOptions then begin //validate configuration before save option.ValidateOptions; //serialize option jpair := fSerializer.Serialize(option.Name,option); yaml.AddPair(jpair); end; end; fileoptions := yaml.ToYaml; if not fileoptions.IsEmpty then TFile.WriteAllText(Filename,fileoptions); finally yaml.Free; end; end; end.
unit FFSColorScheme; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FFSTypes; type TFFSColorScheme = class(TComponent) private FGridSelect: TColor; FActionText: TColor; FMainStatusBar: TColor; FDataBackground: TColor; FTabInactive: TColor; FTabNormalText: TColor; FTabBackground: TColor; FActionHighlight: TColor; FGridHighlight: TColor; FDataText: TColor; FDataLabel: TColor; FGridLowlight: TColor; FFormStatusBar: TColor; FActionRollover: TColor; FTabDataText: TColor; FDataUnderline: TColor; FFormActionBar: TColor; FMainFormBar: TColor; FTabActive: TColor; FGridTitlebar: TColor; FMainFormBarText: TColor; FActiveEntryField: TColor; FListText: TColor; FListSelectedText: TColor; FListBackground: TColor; FListRollover: TColor; FListSelected: TColor; FCaptions: TColor; procedure SetActionHighlight(const Value: TColor); procedure SetActionRollover(const Value: TColor); procedure SetActionText(const Value: TColor); procedure SetDataBackground(const Value: TColor); procedure SetDataLabel(const Value: TColor); procedure SetDataText(const Value: TColor); procedure SetDataUnderline(const Value: TColor); procedure SetFormActionBar(const Value: TColor); procedure SetFormStatusBar(const Value: TColor); procedure SetGridHighlight(const Value: TColor); procedure SetGridLowlight(const Value: TColor); procedure SetGridSelect(const Value: TColor); procedure SetGridTitlebar(const Value: TColor); procedure SetMainFormBar(const Value: TColor); procedure SetMainStatusBar(const Value: TColor); procedure SetTabActive(const Value: TColor); procedure SetTabBackground(const Value: TColor); procedure SetTabDataText(const Value: TColor); procedure SetTabInactive(const Value: TColor); procedure SetTabNormalText(const Value: TColor); procedure SetMainFormBarText(const Value: TColor); procedure SetActiveEntryField(const Value: TColor); procedure SetListBackground(const Value: TColor); procedure SetListRollover(const Value: TColor); procedure SetListSelected(const Value: TColor); procedure SetListSelectedText(const Value: TColor); procedure SetListText(const Value: TColor); procedure SetCaptions(const Value: TColor); { Private declarations } protected { Protected declarations } public { Public declarations } procedure ApplyColors; constructor Create(AOwner:TComponent);override; published { Published declarations } property DataBackground:TColor read FDataBackground write SetDataBackground default clWhite; property ActiveEntryField : TColor read FActiveEntryField write SetActiveEntryField default $00EBEBEB; property DataLabel:TColor read FDataLabel write SetDataLabel default clBlack; property DataText:TColor read FDataText write SetDataText default clNavy; property DataUnderline:TColor read FDataUnderline write SetDataUnderline default clSilver; property ActionText:TColor read FActionText write SetActionText default clBlack; property ActionHighlight:TColor read FActionHighlight write SetActionHighlight default clMaroon; property ActionRollover:TColor read FActionRollover write SetActionRollover default clBlue; property MainStatusBar:TColor read FMainStatusBar write SetMainStatusBar; property MainFormBar:TColor read FMainFormBar write SetMainFormBar; property MainFormBarText:TColor read FMainFormBarText write SetMainFormBarText; property FormStatusBar:TColor read FFormStatusBar write SetFormStatusBar; property FormActionBar:TColor read FFormActionBar write SetFormActionBar; property TabActive:TColor read FTabActive write SetTabActive; property TabInactive:TColor read FTabInactive write SetTabInactive; property TabBackground:TColor read FTabBackground write SetTabBackground; property TabNormalText:TColor read FTabNormalText write SetTabNormalText; property TabDataText:TColor read FTabDataText write SetTabDataText; property GridHighlight:TColor read FGridHighlight write SetGridHighlight; property GridLowlight:TColor read FGridLowlight write SetGridLowlight; property GridSelect:TColor read FGridSelect write SetGridSelect; property GridTitlebar:TColor read FGridTitlebar write SetGridTitlebar; property ListBackground:TColor read FListBackground write SetListBackground; property ListRollover:TColor read FListRollover write SetListRollover; property ListText:TColor read FListText write SetListText; property ListSelected:TColor read FListSelected write SetListSelected; property ListSelectedText:TColor read FListSelectedText write SetListSelectedText; property Captions:TColor read FCaptions Write SetCaptions; end; procedure Register; implementation { TFFSColorScheme } procedure Register; begin RegisterComponents('FFS Common', [TFFSColorScheme]); end; procedure TFFSColorScheme.SetActionHighlight(const Value: TColor); begin FActionHighlight := Value; end; procedure TFFSColorScheme.SetActionRollover(const Value: TColor); begin FActionRollover := Value; end; procedure TFFSColorScheme.SetActionText(const Value: TColor); begin FActionText := Value; end; procedure TFFSColorScheme.SetDataBackground(const Value: TColor); begin FDataBackground := Value; end; procedure TFFSColorScheme.SetDataLabel(const Value: TColor); begin FDataLabel := Value; end; procedure TFFSColorScheme.SetDataText(const Value: TColor); begin FDataText := Value; end; procedure TFFSColorScheme.SetDataUnderline(const Value: TColor); begin FDataUnderline := Value; end; procedure TFFSColorScheme.SetFormActionBar(const Value: TColor); begin FFormActionBar := Value; end; procedure TFFSColorScheme.SetFormStatusBar(const Value: TColor); begin FFormStatusBar := Value; end; procedure TFFSColorScheme.SetGridHighlight(const Value: TColor); begin FGridHighlight := Value; end; procedure TFFSColorScheme.SetGridLowlight(const Value: TColor); begin FGridLowlight := Value; end; procedure TFFSColorScheme.SetGridSelect(const Value: TColor); begin FGridSelect := Value; end; procedure TFFSColorScheme.SetGridTitlebar(const Value: TColor); begin FGridTitlebar := Value; end; procedure TFFSColorScheme.SetMainFormBar(const Value: TColor); begin FMainFormBar := Value; end; procedure TFFSColorScheme.SetMainStatusBar(const Value: TColor); begin FMainStatusBar := Value; end; procedure TFFSColorScheme.SetTabActive(const Value: TColor); begin FTabActive := Value; end; procedure TFFSColorScheme.SetTabBackground(const Value: TColor); begin FTabBackground := Value; end; procedure TFFSColorScheme.SetTabDataText(const Value: TColor); begin FTabDataText := Value; end; procedure TFFSColorScheme.SetTabInactive(const Value: TColor); begin FTabInactive := Value; end; procedure TFFSColorScheme.SetTabNormalText(const Value: TColor); begin FTabNormalText := Value; end; procedure TFFSColorScheme.ApplyColors; var m : TMessage; i : integer; begin FFSColor[fcsDataBackground] := FDataBackground; FFSColor[fcsDataLabel] := FDataLabel; FFSColor[fcsActiveEntryField] := FActiveEntryField; FFSColor[fcsDataText] := FDataText; FFSColor[fcsDataUnderline] := FDataUnderline; FFSColor[fcsActionText] := FActionText; FFSColor[fcsActionRollover] := FActionRollover; FFSColor[fcsMainStatusBar] := FMainStatusBar; FFSColor[fcsMainFormBar] := FMainFormBar; FFSColor[fcsMainFormBarText] := FMainFormBarText; FFSColor[fcsFormStatusBar] := FFormStatusBar; FFSColor[fcsFormActionBar] := FFormActionBar; FFSColor[fcsTabActive] := FTabActive; FFSColor[fcsTabInactive] := FTabInactive; FFSColor[fcsTabBackground] := FTabBackground; FFSColor[fcsTabNormalText] := FTabNormalText; FFSColor[fcsTabDataText] := FTabDataText; FFSColor[fcsGridHighlight] := FGridHighlight; FFSColor[fcsGridLowlight] := FGridLowlight; FFSColor[fcsGridSelect] := FGridSelect; FFSColor[fcsGridTitlebar] := FGridTitlebar; FFSColor[fcsListBackground] := FListBackground; FFSColor[fcsListRollover] := FListRollover; FFSColor[fcsListSelected] := FListSelected; FFSColor[fcsListText] := FListText; FFSColor[fcsListSelectedText] := FListSelectedText; FFSColor[fcsCaptions] := FCaptions; // now send a message to the application that the colors have changed m.Msg := Msg_FFSColorChange; m.WParam := 0; m.LParam := 0; m.Result := 0; for i := 0 to Screen.FormCount-1 do Screen.Forms[i].Broadcast(m); end; constructor TFFSColorScheme.Create(AOwner: TComponent); begin inherited; FDataBackground := FFSColor[fcsDataBackground]; FDataLabel := FFSColor[fcsDataLabel]; FActiveEntryField := FFSColor[fcsActiveEntryField]; FDataText := FFSColor[fcsDataText]; FDataUnderline := FFSColor[fcsDataUnderline]; FActionText := FFSColor[fcsActionText]; FActionRollover := FFSColor[fcsActionRollover]; FMainStatusBar := FFSColor[fcsMainStatusBar]; FMainFormBar := FFSColor[fcsMainFormBar]; FMainFormBarText := FFSColor[fcsMainFormBarText]; FFormStatusBar := FFSColor[fcsFormStatusBar]; FFormActionBar := FFSColor[fcsFormActionBar]; FTabActive := FFSColor[fcsTabActive]; FTabInactive := FFSColor[fcsTabInactive]; FTabBackground := FFSColor[fcsTabBackground]; FTabNormalText := FFSColor[fcsTabNormalText]; FTabDataText := FFSColor[fcsTabDataText]; FGridHighlight := FFSColor[fcsGridHighlight]; FGridLowlight := FFSColor[fcsGridLowlight]; FGridSelect := FFSColor[fcsGridSelect]; FGridTitlebar := FFSColor[fcsGridTitlebar]; FListBackground := FFSColor[fcsListBackground]; FListRollover := FFSColor[fcsListRollover]; FListSelected := FFSColor[fcsListSelected]; FListText := FFSColor[fcsListText]; FListSelectedText := FFSColor[fcsListSelectedText]; FCaptions := FFSColor[fcsCaptions]; end; procedure TFFSColorScheme.SetMainFormBarText(const Value: TColor); begin FMainFormBarText := Value; end; procedure TFFSColorScheme.SetActiveEntryField(const Value: TColor); begin FActiveEntryField := Value; end; procedure TFFSColorScheme.SetListBackground(const Value: TColor); begin FListBackground := Value; end; procedure TFFSColorScheme.SetListRollover(const Value: TColor); begin FListRollover := Value; end; procedure TFFSColorScheme.SetListSelected(const Value: TColor); begin FListSelected := Value; end; procedure TFFSColorScheme.SetListSelectedText(const Value: TColor); begin FListSelectedText := Value; end; procedure TFFSColorScheme.SetListText(const Value: TColor); begin FListText := Value; end; procedure TFFSColorScheme.SetCaptions(const Value: TColor); begin FCaptions := Value; end; end.
unit Form_utl; interface uses Forms, Messages; type TOnScroll = procedure(Sender: TObject; HorzScroll: Boolean; OldPos, CurrentPos: Integer) of object; TScrollBox = class(Forms.TScrollBox) private FOnScroll: TOnScroll; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; public property OnScroll: TOnScroll read FOnScroll write FOnScroll; end; implementation { TScrollBox } procedure TScrollBox.WMHScroll(var Message: TWMHScroll); var OldPos: Integer; begin OldPos := HorzScrollBar.Position; inherited; if HorzScrollBar.Position <> OldPos then if Assigned(FOnScroll) then FOnScroll(Self, True, OldPos, HorzScrollBar.Position); end; procedure TScrollBox.WMVScroll(var Message: TWMVScroll); var OldPos: Integer; begin OldPos := VertScrollBar.Position; inherited; if VertScrollBar.Position <> OldPos then if Assigned(FOnScroll) then FOnScroll(Self, False, OldPos, VertScrollBar.Position); end; end.
program TESTC1 ( INPUT , OUTPUT ) ; type TMYRECORD = record A : INTEGER ; B : CHAR ( 5 ) ; end ; const DEFAULT : TMYRECORD = ( 100 , 'foo' ) ; var R : TMYRECORD ; begin (* HAUPTPROGRAMM *) R := DEFAULT ; WRITELN ( 'test const with records' ) ; WRITELN ( 'r.a = <' , R . A , '>' ) ; WRITELN ( 'r.b = <' , R . B , '>' ) ; end (* HAUPTPROGRAMM *) .
unit uRestDataWare; interface uses Datasnap.DSClientRest, REST.Types, REST.Client, REST.Authenticator.Basic, System.JSON, Data.Bind.Components, Data.Bind.ObjectScope; type TRestDataWare = class private FRESTClient: TRESTClient; FRESTRequest: TRESTRequest; FTHTTPBasicAuthenticator: THTTPBasicAuthenticator; public constructor Create; destructor Destroy; override; class function New : TRestDataWare; function AddParameter(pParans: String; aValues: Variant): TRestDataWare; function ClearParans: TRestDataWare; function Execute: TRestDataWare; function HostServer( aValue: String): TRestDataWare; function JSONString( aParant: String): String; function JSONArray: TJSONArray; function Resource( aValue: String) : TRestDataWare; function StatusCode: Integer; end; implementation uses System.SysUtils; { TModelComponentsRestDataWare } function TRestDataWare.AddParameter(pParans: String; aValues: Variant): TRestDataWare; begin Result := Self; FRESTRequest.AddParameter(pParans, aValues); end; function TRestDataWare.ClearParans: TRestDataWare; begin Result := Self; FRESTRequest.Params.Clear; end; constructor TRestDataWare.Create; begin FRESTClient := TRESTClient.Create(Nil); FRESTClient.Accept := 'application/json'; FRESTClient.AcceptCharSet := 'UTF-8'; FRESTClient.ContentType := 'application/json'; FRESTClient.RaiseExceptionOn500 := False; FTHTTPBasicAuthenticator := THTTPBasicAuthenticator.Create('admin', 'admin'); FRESTClient.Authenticator := FTHTTPBasicAuthenticator; FRESTRequest := TRESTRequest.Create(Nil); FRESTRequest.Client := FRESTClient; end; destructor TRestDataWare.Destroy; begin FRESTRequest.DisposeOf; FRESTClient.DisposeOf; FTHTTPBasicAuthenticator.DisposeOf; inherited; end; function TRestDataWare.Execute: TRestDataWare; begin Result := Self; try FRESTRequest.Execute; except end; end; function TRestDataWare.HostServer( aValue: String): TRestDataWare; begin Result := Self; FRESTClient.BaseURL := 'http://'+ aValue; end; function TRestDataWare.JSONArray: TJSONArray; begin Result := TJsonObject.ParseJSONValue (TEncoding.UTF8.GetBytes(FRESTRequest.Response.JSONText), 0) as TJSONArray; end; function TRestDataWare.JSONString( aParant: String): String; begin Result := (TJsonObject.ParseJSONValue (TEncoding.UTF8.GetBytes (FRESTRequest.Response.JSONValue.ToString), 0) as TJSONObject).GetValue(aParant).Value; end; class function TRestDataWare.New: TRestDataWare; begin Result := TRestDataWare.Create; end; function TRestDataWare.Resource( aValue: String): TRestDataWare; begin Result := Self; FRESTRequest.Resource := aValue; end; function TRestDataWare.StatusCode: Integer; begin Result := FRESTRequest.Response.StatusCode end; end.
unit UPassLockDemo; 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.TMSBaseControl, FMX.TMSPassLock; type TForm15 = class(TForm) TMSFMXPassLock1: TTMSFMXPassLock; Panel1: TPanel; Label1: TLabel; rbNumbers: TRadioButton; rbPattern: TRadioButton; rbEnter: TRadioButton; rbLearn: TRadioButton; Label2: TLabel; Label3: TLabel; procedure TMSFMXPassLock1PasswordConfirmed(Sender: TObject; Result: TTMSFMXPasswordConfirm); procedure TMSFMXPassLock1PasswordLearned(Sender: TObject); procedure TMSFMXPassLock1PasswordMatch(Sender: TObject); procedure TMSFMXPassLock1PasswordMismatch(Sender: TObject); procedure rbNumbersChange(Sender: TObject); procedure rbLearnChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure Init; end; var Form15: TForm15; implementation {$R *.fmx} procedure TForm15.FormCreate(Sender: TObject); begin Init; end; procedure TForm15.Init; begin TMSFMXPassLock1.LearnMode := rbLearn.IsChecked; if rbNumbers.IsChecked then TMSFMXPassLock1.LockType := pltNumber else TMSFMXPassLock1.LockType := pltPattern; Label3.Text := 'Enter password:' end; procedure TForm15.rbLearnChange(Sender: TObject); begin Init; end; procedure TForm15.rbNumbersChange(Sender: TObject); begin Init; TMSFMXPassLock1.PassValue := ''; end; procedure TForm15.TMSFMXPassLock1PasswordConfirmed(Sender: TObject; Result: TTMSFMXPasswordConfirm); begin if Result = pcSuccess then Label3.Text := 'Result: Password confirmed.' else Label3.Text := 'Result: Confirm failed. Please try again.'; end; procedure TForm15.TMSFMXPassLock1PasswordLearned(Sender: TObject); begin Label3.Text := 'Result: Password learned. Please confirm password.'; end; procedure TForm15.TMSFMXPassLock1PasswordMatch(Sender: TObject); begin Label3.Text := 'Result: Password is correct'; end; procedure TForm15.TMSFMXPassLock1PasswordMismatch(Sender: TObject); begin Label3.Text := 'Result: Password is wrong. Please try again.'; end; end.
unit MP_Lex; interface type symbol = (noSy, numSy, idSy, plusSy, minusSy, mulSy, divSy, leftParSy, rightParSy, assignSy, commaSy, semicolonSy, dotSy, colonSy, programSy, varSy, beginSy, endSy, readSy, writeSy, integerSy, eofSy); var sy : symbol; numberVal : integer; identStr: string; procedure initLex(inFileName : string); procedure newSy; implementation const EOF_CH = chr(26); TAB_CH = chr(9); var inFile : text; line : string; linePos : integer; ch : char; procedure newCh; FORWARD; procedure initLex(inFileName : string); begin assign(inFile, inFileName); reset(inFile); line := ''; linePos := 0; newCh; end; procedure newSy; begin while (ch = ' ') or (ch = TAB_CH) do newCh; case ch of '+': begin sy := plusSy; newCh; end; '-': begin sy := minusSy; newCh; end; '*': begin sy := mulSy; newCh; end; '/': begin sy := divSy; newCh; end; ':': begin newCH; if ch = '=' then begin sy := assignSy; NewCh; end else sy := colonSy; end; ';': begin sy := semicolonSy; newCh; end; '.': begin sy := dotSy; newCh; end; ',': begin sy := commaSy; newCh; end; '(': begin sy := leftParSy; newCh; end; ')': begin sy := rightParSy; newCh; end; EOF_CH: begin sy := eofSy; newCh; end; '_','a'..'z','A'..'Z': begin identStr := ch; newCh; while ch in ['_','a'..'z','A'..'Z','0'..'9'] do begin identStr := identStr + ch; newCh; end; identStr := upCase(identStr); if identStr = 'PROGRAM' then sy := programSy else if identStr = 'BEGIN' then sy := beginSy else if identStr = 'END' then sy := endSy else if identStr = 'VAR' then sy := varSy else if identStr = 'INTEGER' then sy := integerSy else if identStr = 'READ' then sy := readSy else if identStr = 'WRITE' then sy := writeSy else sy := idSy; end; '0'..'9': begin numberVal := ord(ch) - ord('0'); newCh; while ch in ['0'..'9'] do begin numberVal := numberVal * 10 + ord(ch) - ord('0'); newCh; end; end; else begin sy := noSy; end; end; end; procedure newCh; begin inc(linePos); if linePos > length(line) then begin if not eof(inFile) then begin readLn(inFile, line); linePos := 0; ch := ' '; end else begin ch := EOF_CH; line := ''; linePos := 0; end; end else begin ch := line[linePos]; end; (* else *) end; begin end.
unit Lookups; interface uses Classes, SysUtils; type PLookupItem = ^TLookupItem; TLookupItem = record FID, FValue: pointer; end; const MaxLookupListSize = MaxInt div SizeOf(TLookupItem) - 1; type PLookupItemList = ^TLookupItemList; TLookupItemList = array[0..MaxLookupListSize] of TLookupItem; TCustomLookup = class protected FList: PLookupItemList; FCount: Integer; FCapacity: Integer; FInitialized: Boolean; procedure Add(ID, Value: pointer); function CompareItem(V1, V2: pointer): integer; virtual; abstract; procedure DeallocateList; virtual; function DumpLine(I: integer): AnsiString; virtual; abstract; procedure ExchangeItems(Index1, Index2: Integer); function Exists(ID: pointer): boolean; function Find(ID: pointer): integer; procedure Grow; function IsOrdered: boolean; procedure QuickSort(L, R: Integer); procedure SetInitialized(const Value: Boolean); procedure SetCapacity(NewCapacity: Integer); function Value(ID: pointer): pointer; public destructor Destroy; override; procedure Clear; procedure Dump(Strings: TStrings); property Count: integer read FCount; property Initialized: boolean read FInitialized write SetInitialized; end; TIntegerArray = array of integer; TStringArray = array of AnsiString; TCustomIntKeyLookup = class(TCustomLookup) protected function CompareItem(V1, V2: pointer): integer; override; public function Exists(ID: integer): boolean; function Low: integer; function High: integer; function GetKeys: TIntegerArray; end; TIntToIntLookup = class(TCustomIntKeyLookup) protected function DumpLine(I: integer): AnsiString; override; public procedure Add(ID, Value: integer); function Value(ID: integer): integer; end; TIntToStrLookup = class(TCustomIntKeyLookup) protected procedure DeallocateList; override; function DumpLine(I: integer): AnsiString; override; public procedure Add(ID: integer; Value: AnsiString); function Value(ID: integer): AnsiString; end; TIntToObjectLookup = class(TCustomIntKeyLookup) private FOwnsObjects: boolean; protected procedure DeallocateList; override; function DumpLine(I: integer): AnsiString; override; public procedure Add(ID: integer; Value: TObject); function Value(ID: integer): TObject; property OwnsObjects: boolean read FOwnsObjects write FOwnsObjects; end; TCustomStrKeyLookup = class(TCustomLookup) protected function CompareItem(V1, V2: pointer): integer; override; public function Exists(ID: AnsiString): boolean; function GetKeys: TStringArray; end; TStrToIntLookup = class(TCustomStrKeyLookup) protected procedure DeallocateList; override; function DumpLine(I: integer): AnsiString; override; public procedure Add(ID: AnsiString; Value: integer); function Value(ID: AnsiString): integer; end; TStrToStrLookup = class(TCustomStrKeyLookup) protected procedure DeallocateList; override; function DumpLine(I: integer): AnsiString; override; public procedure Add(ID, Value: AnsiString); function Value(ID: AnsiString): AnsiString; end; TStrToObjectLookup = class(TCustomStrKeyLookup) private FOwnsObjects: boolean; protected procedure DeallocateList; override; function DumpLine(I: integer): AnsiString; override; public procedure Add(ID: AnsiString; Value: TObject); function Value(ID: AnsiString): TObject; property OwnsObjects: boolean read FOwnsObjects write FOwnsObjects; end; implementation function CopyString(Value: AnsiString): PAnsiString; begin New(Result); Result^ := Value; end; { TCustomLookup } procedure TCustomLookup.Add(ID, Value: pointer); begin if FCount = FCapacity then Grow; with FList^[FCount] do begin FID := ID; FValue := Value; end; Inc(FCount); FInitialized := false; end; procedure TCustomLookup.Clear; begin if FCount <> 0 then begin DeallocateList; FCount := 0; FInitialized := false; SetCapacity(0); end; end; procedure TCustomLookup.DeallocateList; begin end; destructor TCustomLookup.Destroy; begin Clear; inherited; end; procedure TCustomLookup.Dump(Strings: TStrings); var i: Integer; begin Strings.Clear; for i := 0 to FCount - 1 do Strings.Add(DumpLine(i)); end; procedure TCustomLookup.ExchangeItems(Index1, Index2: Integer); var temp: pointer; i1, i2: PLookupItem; begin i1 := @FList^[Index1]; i2 := @FList^[Index2]; temp := i1^.FID; i1^.FID := i2^.FID; i2^.FID := temp; temp := i1^.FValue; i1^.FValue := i2^.FValue; i2^.FValue := temp; end; function TCustomLookup.Exists(ID: pointer): boolean; begin Result := Find(ID) <> -1; end; function TCustomLookup.Find(ID: pointer): integer; var L, H, I: Integer; begin Initialized := true; Result := -1; if (FCount = 0) or (CompareItem(ID, FList^[0].FID) = -1) or (CompareItem(ID, FList^[FCount - 1].FID) = 1) then exit; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; case CompareItem(FList^[I].FID, ID) of -1: L := I + 1; 1: H := I - 1; else begin Result := I; exit; end; end; end; end; procedure TCustomLookup.Grow; var Delta: Integer; begin if FCapacity > 64 then Delta := FCapacity div 4 else Delta := 16; SetCapacity(FCapacity + Delta); end; function TCustomLookup.IsOrdered: boolean; var i: integer; id, lastid: pointer; begin Result := true; if FCount > 1 then begin lastid := FList^[0].FID; for i := 1 to FCount - 1 do begin id := FList^[i].FID; if CompareItem(id, lastid) = -1 then begin Result := false; exit; end; lastid := id; end; end; end; procedure TCustomLookup.QuickSort(L, R: Integer); function Compare(Index1, Index2: integer): integer; begin Result := CompareItem(FList^[Index1].FID, FList^[Index2].FID); end; var I, J, P: Integer; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while Compare(I, P) < 0 do Inc(I); while Compare(J, P) > 0 do Dec(J); if I <= J then begin ExchangeItems(I, J); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; procedure TCustomLookup.SetCapacity(NewCapacity: Integer); begin ReallocMem(FList, NewCapacity * SizeOf(TLookupItem)); FCapacity := NewCapacity; end; procedure TCustomLookup.SetInitialized(const Value: Boolean); begin if FInitialized <> Value then begin if Value and not IsOrdered then QuickSort(0, FCount - 1); FInitialized := Value; end; end; function TCustomLookup.Value(ID: pointer): pointer; var index: integer; begin index := Find(ID); if index = -1 then Result := nil else Result := FList^[index].FValue; end; { TCustomIntKeyLookup } function TCustomIntKeyLookup.CompareItem(V1, V2: pointer): integer; begin if Integer(V1) < Integer(V2) then Result := -1 else if Integer(V1) > Integer(V2) then Result := 1 else Result := 0; end; function TCustomIntKeyLookup.Exists(ID: integer): boolean; begin Result := inherited Exists(Ptr(ID)); end; function TCustomIntKeyLookup.GetKeys: TIntegerArray; var i: integer; begin SetLength(Result, FCount); for i := 0 to FCount - 1 do Result[i] := integer(FList[i].FID); end; function TCustomIntKeyLookup.High: integer; begin if Count = 0 then Result := 0 else Result := Integer(FList[FCount-1].FID); end; function TCustomIntKeyLookup.Low: integer; begin if Count = 0 then Result := 0 else Result := Integer(FList[0].FID); end; { TIntToIntLookup } procedure TIntToIntLookup.Add(ID, Value: integer); begin inherited Add(Ptr(ID), Ptr(Value)); end; function TIntToIntLookup.DumpLine(I: integer): AnsiString; begin with FList^[I] do Result := IntToStr(integer(FID)) + '=' + IntToStr(integer(FValue)); end; function TIntToIntLookup.Value(ID: integer): integer; begin Result := integer(inherited Value(Ptr(ID))); end; { TIntToStrLookupList } procedure TIntToStrLookup.Add(ID: integer; Value: AnsiString); begin inherited Add(Ptr(ID), CopyString(Value)); end; procedure TIntToStrLookup.DeallocateList; var i: integer; begin for i := 0 to FCount - 1 do Dispose(PAnsiString(FList^[i].FValue)); end; function TIntToStrLookup.DumpLine(I: integer): AnsiString; begin with FList^[I] do Result := IntToStr(integer(FID)) + '=' + PAnsiString(FValue)^; end; function TIntToStrLookup.Value(ID: integer): AnsiString; begin Result := PAnsiString(inherited Value(Ptr(ID)))^; end; { TIntToObjectLookup } procedure TIntToObjectLookup.Add(ID: integer; Value: TObject); begin inherited Add(Ptr(ID), Value); end; procedure TIntToObjectLookup.DeallocateList; var i: integer; begin if FOwnsObjects then for i := 0 to FCount - 1 do with FList^[i] do if FValue <> nil then TObject(FValue).Free; end; function TIntToObjectLookup.DumpLine(I: integer): AnsiString; begin with FList^[I] do Result := IntToStr(integer(FID)) + '=' + TObject(FValue).ClassName + '($' + IntToHex(integer(FValue), 8); end; function TIntToObjectLookup.Value(ID: integer): TObject; begin Result := TObject(inherited Value(Ptr(ID))); end; { TCustomStrKeyLookup } function TCustomStrKeyLookup.CompareItem(V1, V2: pointer): integer; begin Result := CompareStr(PAnsiString(V1)^, PAnsiString(V2)^); end; function TCustomStrKeyLookup.Exists(ID: AnsiString): boolean; begin Result := inherited Exists(@ID); end; function TCustomStrKeyLookup.GetKeys: TStringArray; var i: integer; begin SetLength(Result, FCount); for i := 0 to FCount - 1 do Result[i] := PAnsiString(FList[i].FID)^; end; { TStrToIntLookup } procedure TStrToIntLookup.Add(ID: AnsiString; Value: integer); begin inherited Add(CopyString(ID), Ptr(Value)); end; procedure TStrToIntLookup.DeallocateList; var i: integer; begin for i := 0 to FCount - 1 do Dispose(PAnsiString(FList^[i].FID)); end; function TStrToIntLookup.DumpLine(I: integer): AnsiString; begin with FList^[I] do Result := PAnsiString(FID)^ + '=' + IntToStr(integer(FValue)); end; function TStrToIntLookup.Value(ID: AnsiString): integer; begin Result := integer(inherited Value(@ID)); end; { TStrToStrLookup } procedure TStrToStrLookup.Add(ID, Value: AnsiString); begin inherited Add(CopyString(ID), CopyString(Value)); end; procedure TStrToStrLookup.DeallocateList; var i: integer; begin for i := 0 to FCount - 1 do begin Dispose(PAnsiString(FList^[i].FID)); Dispose(PAnsiString(FList^[i].FValue)); end; end; function TStrToStrLookup.DumpLine(I: integer): AnsiString; begin with FList^[I] do Result := PAnsiString(FID)^ + '=' + PAnsiString(FValue)^; end; function TStrToStrLookup.Value(ID: AnsiString): AnsiString; begin Result := PAnsiString(inherited Value(@ID))^; end; { TStrToObjectLookup } procedure TStrToObjectLookup.Add(ID: AnsiString; Value: TObject); begin inherited Add(CopyString(ID), Value); end; procedure TStrToObjectLookup.DeallocateList; var i: integer; begin for i := 0 to FCount - 1 do with FList^[i] do begin Dispose(PAnsiString(FID)); if FOwnsObjects and (FValue <> nil) then TObject(FValue).Free; end; end; function TStrToObjectLookup.DumpLine(I: integer): AnsiString; begin with FList^[I] do Result := PAnsiString(FID)^ + '=' + TObject(FValue).ClassName + '($' + IntToHex(integer(FValue), 8); end; function TStrToObjectLookup.Value(ID: AnsiString): TObject; begin Result := TObject(inherited Value(@ID)); end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { This program is free software; you can redistribute it and/or } { modify it under the terms of the GNU General Public } { License as published by the Free Software Foundation; either } { version 2 of the License, or (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU } { General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uXPColorDialog; interface uses SysUtils, Types, Classes, Variants, QGraphics, QControls, QForms, QDialogs, QExtCtrls, QStdCtrls, uGraphics; type TXPColorDialog = class(TForm) btnOther: TButton; procedure FormShow(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOtherClick(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormClick(Sender: TObject); private FSelectedColor: TColor; procedure drawSelected(r: TRect;acolor:TColor); procedure SetSelectedColor(const Value: TColor); { Private declarations } public { Public declarations } lastpx,lastpy:integer; lastx,lasty:integer; lastcolor:TColor; colors: array [0..3,0..4] of integer; property SelectedColor:TColor read FSelectedColor write SetSelectedColor; end; var XPColorDialog: TXPColorDialog; implementation {$R *.xfm} procedure TXPColorDialog.FormShow(Sender: TObject); begin lastcolor:=FSelectedColor; width:=98; end; procedure TXPColorDialog.FormPaint(Sender: TObject); var x,y:integer; r: TRect; begin canvas.brush.color:=clButton; r3d(canvas,clientrect,false,true,false); for x:=0 to 3 do begin for y:=0 to 4 do begin r.left:=(x*23)+5; r.Top:=(y*23)+5; r.Right:=r.left+19; r.Bottom:=r.top+19; canvas.brush.color:=colors[x,y]; r3d(canvas,r,false,false,true); end; end; canvas.brush.color:=FSelectedColor; r.left:=btnOther.BoundsRect.right+3; r.top:=btnOther.BoundsRect.top+2; r.Right:=r.left+19; r.Bottom:=r.top+19; r3d(canvas,r,false,false,true); r.left:=lastx-2; r.top:=lasty-2; r.right:=r.left+23; r.bottom:=r.top+23; drawSelected(r,lastcolor); canvas.pen.color:=clBtnShadow; canvas.moveto(btnOther.left,btnOther.top-4); canvas.lineto(width-5,btnOther.top-4); canvas.pen.color:=clBtnHighlight; canvas.moveto(btnOther.left,btnOther.top-3); canvas.lineto(width-5,btnOther.top-3); canvas.lineto(width-5,btnOther.top-4); end; procedure TXPColorDialog.FormCreate(Sender: TObject); begin lastpx:=-1; lastpy:=-1; lastx:=btnOther.BoundsRect.right+3; lasty:=btnOther.BoundsRect.top+2; FSelectedColor:=clNone; colors[0,0]:=$ffffff; colors[1,0]:=$000000; colors[2,0]:=$c5c2c5; colors[3,0]:=$838183; colors[0,1]:=$0000ff; colors[1,1]:=$000083; colors[2,1]:=$00ffff; colors[3,1]:=$008183; colors[0,2]:=$00ff00; colors[1,2]:=$008200; colors[2,2]:=$ffff00; colors[3,2]:=$838100; colors[0,3]:=$ff0000; colors[1,3]:=$830000; colors[2,3]:=$ff00ff; colors[3,3]:=$830083; colors[0,4]:=$c5dec5; colors[1,4]:=$f6caa4; colors[2,4]:=$f6faff; colors[3,4]:=$a4a1a4; end; procedure TXPColorDialog.btnOtherClick(Sender: TObject); begin modalresult:=mrAll; end; procedure TXPColorDialog.SetSelectedColor(const Value: TColor); begin FSelectedColor := Value; end; procedure TXPColorDialog.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var r:TRect; p: TPoint; begin p.x:=x; p.Y:=y; x:=x div 23; y:=y div 23; if (x>=0) and (x<=3) and (y>=0) and (y<=4) then begin if (x<>lastpx) or (y<>lastpy) then begin lastpx:=x; lastpy:=y; canvas.brush.color:=clButton; canvas.brush.style:=bsClear; canvas.pen.color:=clButton; r.left:=lastx-2; r.top:=lasty-2; r.Right:=r.left+19+4; r.Bottom:=r.top+19+4; canvas.rectangle(r); inflaterect(r,-1,-1); canvas.rectangle(r); canvas.brush.style:=bsSolid; canvas.brush.color:=lastcolor; r3d(canvas,rect(lastx,lasty,lastx+19,lasty+19),false,false,true); r.left:=(x*23)+5-2; r.Top:=(y*23)+5-2; r.Right:=r.left+19+4; r.Bottom:=r.top+19+4; lastx:=r.left+2; lasty:=r.Top+2; lastcolor:=colors[x,y]; drawSelected(r,colors[x,y]); end; end else begin r.left:=btnOther.BoundsRect.right+3; r.top:=btnOther.BoundsRect.top+2; r.Right:=r.left+19; r.Bottom:=r.top+19; if ptInRect(r,p) then begin lastpx:=-1; lastpy:=-1; canvas.brush.color:=clButton; canvas.brush.style:=bsClear; canvas.pen.color:=clButton; r.left:=lastx-2; r.top:=lasty-2; r.Right:=r.left+19+4; r.Bottom:=r.top+19+4; canvas.rectangle(r); inflaterect(r,-1,-1); canvas.rectangle(r); canvas.brush.style:=bsSolid; canvas.brush.color:=lastcolor; r3d(canvas,rect(lastx,lasty,lastx+19,lasty+19),false,false,true); r.left:=btnOther.BoundsRect.right+3-2; r.Top:=btnOther.BoundsRect.top+2-2; r.Right:=r.left+19+4; r.Bottom:=r.top+19+4; lastx:=r.left+2; lasty:=r.Top+2; lastcolor:=FSelectedColor; drawSelected(r,FSelectedColor); end; end; end; procedure TXPColorDialog.drawSelected(r: TRect;acolor:TColor); begin canvas.pen.color:=clBlack; canvas.brush.color:=acolor; canvas.rectangle(r); inflaterect(r,-1,-1); canvas.pen.color:=clWhite; canvas.rectangle(r); inflaterect(r,-1,-1); canvas.pen.color:=clBlack; canvas.rectangle(r); end; procedure TXPColorDialog.FormClick(Sender: TObject); begin SelectedColor:=lastcolor; modalresult:=mrOk; end; end.
unit ThreadKindergartenData; interface uses System.SysUtils, System.Classes, CrossPlatformHeaders, fmx.Forms, System.Generics.Collections, System.Diagnostics, System.SyncObjs, fmx.Dialogs{$IFDEF LINUX},Posix.Pthread,Posix.Signal{$ENDIF}; type ThreadKindergarten = class type TCareThread = class(TThread) private FProc: TProc; index: Integer; owner: ThreadKindergarten; protected public procedure Execute; override; constructor Create(const AProc: TProc; id: Integer; Aowner: ThreadKindergarten); end; private map: TDictionary<Integer, TCareThread>; index: Integer; Addmutex, removeMutex: TSemaphore; public constructor Create(); destructor Destroy(); override; function CreateAnonymousThread(proc: TProc): TThread; procedure removeThread(id: Integer); procedure terminateThread(id: Integer); end; implementation { ThreadKindergarten } uses SyncThr; procedure ThreadKindergarten.removeThread(id: Integer); var temp: TCareThread; begin removeMutex.Acquire; try if map.TryGetValue(id, temp) then begin map.Remove(id); end; finally removeMutex.Release; end; end; procedure ThreadKindergarten.terminateThread(id: Integer); var temp: TCareThread; begin if map.TryGetValue(id, temp) then begin try while not temp.Started do begin Application.ProcessMessages; sleep(10); end; temp.Terminate; except on E: Exception do end; end; end; function ThreadKindergarten.CreateAnonymousThread(proc: TProc): TThread; var temp: TCareThread; begin Addmutex.Acquire; try temp := TCareThread.Create(proc, index, self); // temp.Start; //temp.FreeOnTerminate:=true; map.Add(index, temp); index := index + 1; result := temp; finally Addmutex.Release; end; end; constructor ThreadKindergarten.Create(); begin inherited; map := TDictionary<Integer, TCareThread>.Create(); Addmutex := TSemaphore.Create(); removeMutex := TSemaphore.Create(); index := 0; end; destructor ThreadKindergarten.Destroy(); var it: TDictionary<Integer, TCareThread>.TPairEnumerator; i: Integer; begin // it := map.GetEnumerator; for i := Length(map.ToArray) - 1 downto 0 do begin try if map.ToArray[i].Value <> nil then begin // map.ToArray[i].Value.FreeOnTerminate := true; map.ToArray[i].Value.Terminate; //pthread_kill(map.ToArray[i].Value.ThreadID,9); end; //map.ToArray[High(map.ToArray)]:=map.ToArray[i]; // map.Remove(i); except on E: Exception do begin map.Remove(map.ToArray[i].Key); end; end; end; { while it.MoveNext do begin terminateThread( it.Current.Key ); end; } //{$IF/NDEF LINUX} while map.Count <> 0 do begin try Application.ProcessMessages; except on E: Exception do begin end; end; for i := Length(map.ToArray) - 1 downto 0 do begin if map.ToArray[i].Value<>nil then if map.ToArray[i].Value.Finished=true then map.Remove(map.ToArray[i].Key); end; sleep(100); end; //{$EN/DIF} // it.free; map.free; Addmutex.free; removeMutex.free(); //semaphore.free; //semaphore := nil; inherited; end; procedure ThreadKindergarten.TCareThread.Execute; begin FProc(); owner.removeThread(index); end; constructor ThreadKindergarten.TCareThread.Create(const AProc: TProc; id: Integer; Aowner: ThreadKindergarten); begin inherited Create(true); owner := Aowner; FreeOnTerminate := true; FProc := AProc; index := id; end; end.
unit Search_Strange_Controls; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Search_Strange_Controls.pas" // Стереотип: "VCMControls" // Элемент модели: "Strange" MUID: (4AE89F8A004B) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin)} uses l3IntfUses , BaseTreeSupportUnit , DynamicTreeUnit , FiltersUnit , l3TreeInterfaces , bsTypes , eeInterfaces , PrimPrimListInterfaces , nsTypes {$If NOT Defined(NoVCM)} , vcmInterfaces {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmExternalInterfaces {$IfEnd} // NOT Defined(NoVCM) ; type TNodesArray = IFiltersFromQuery; IQuery_ClearAll_Params = interface {* Параметры для операции Query.ClearAll } function Get_NotClearRange: Boolean; property NotClearRange: Boolean read Get_NotClearRange; end;//IQuery_ClearAll_Params Op_Query_ClearAll = {final} class {* Класс для вызова операции Query.ClearAll } public class function Call(const aTarget: IvcmEntity; aNotClearRange: Boolean): Boolean; overload; {* Вызов операции Query.ClearAll у сущности } class function Call(const aTarget: IvcmAggregate; aNotClearRange: Boolean): Boolean; overload; {* Вызов операции Query.ClearAll у агрегации } class function Call(const aTarget: IvcmEntityForm; aNotClearRange: Boolean): Boolean; overload; {* Вызов операции Query.ClearAll у формы } class function Call(const aTarget: IvcmContainer; aNotClearRange: Boolean): Boolean; overload; {* Вызов операции Query.ClearAll у контейнера } end;//Op_Query_ClearAll IQuery_SetList_Params = interface {* Параметры для операции Query.SetList } function Get_List: IdeList; function Get_InList: Boolean; property List: IdeList read Get_List; property InList: Boolean read Get_InList; end;//IQuery_SetList_Params Op_Query_SetList = {final} class {* Класс для вызова операции Query.SetList } public class function Call(const aTarget: IvcmEntity; const aList: IdeList; aInList: Boolean): Boolean; overload; {* Вызов операции Query.SetList у сущности } class function Call(const aTarget: IvcmAggregate; const aList: IdeList; aInList: Boolean): Boolean; overload; {* Вызов операции Query.SetList у агрегации } class function Call(const aTarget: IvcmEntityForm; const aList: IdeList; aInList: Boolean): Boolean; overload; {* Вызов операции Query.SetList у формы } class function Call(const aTarget: IvcmContainer; const aList: IdeList; aInList: Boolean): Boolean; overload; {* Вызов операции Query.SetList у контейнера } end;//Op_Query_SetList IQuery_GetList_Params = interface {* Параметры для операции Query.GetList } function Get_ResultValue: IdeList; procedure Set_ResultValue(const aValue: IdeList); property ResultValue: IdeList read Get_ResultValue write Set_ResultValue; end;//IQuery_GetList_Params Op_Query_GetList = {final} class {* Класс для вызова операции Query.GetList } public class function Call(const aTarget: IvcmEntity): IdeList; overload; {* Вызов операции Query.GetList у сущности } class function Call(const aTarget: IvcmAggregate): IdeList; overload; {* Вызов операции Query.GetList у агрегации } class function Call(const aTarget: IvcmEntityForm): IdeList; overload; {* Вызов операции Query.GetList у формы } class function Call(const aTarget: IvcmContainer): IdeList; overload; {* Вызов операции Query.GetList у контейнера } end;//Op_Query_GetList IFilterable_Add_Params = interface {* Параметры для операции Filterable.Add } function Get_Filter: IFilterFromQuery; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); property Filter: IFilterFromQuery read Get_Filter; property ResultValue: Boolean read Get_ResultValue write Set_ResultValue; end;//IFilterable_Add_Params Op_Filterable_Add = {final} class {* Класс для вызова операции Filterable.Add } public class function Call(const aTarget: IvcmEntity; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Add у сущности } class function Call(const aTarget: IvcmAggregate; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Add у агрегации } class function Call(const aTarget: IvcmEntityForm; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Add у формы } class function Call(const aTarget: IvcmContainer; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Add у контейнера } end;//Op_Filterable_Add IFilterable_Delete_Params = interface {* Параметры для операции Filterable.Delete } function Get_Filter: IFilterFromQuery; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); property Filter: IFilterFromQuery read Get_Filter; property ResultValue: Boolean read Get_ResultValue write Set_ResultValue; end;//IFilterable_Delete_Params Op_Filterable_Delete = {final} class {* Класс для вызова операции Filterable.Delete } public class function Call(const aTarget: IvcmEntity; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Delete у сущности } class function Call(const aTarget: IvcmAggregate; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Delete у агрегации } class function Call(const aTarget: IvcmEntityForm; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Delete у формы } class function Call(const aTarget: IvcmContainer; const aFilter: IFilterFromQuery): Boolean; overload; {* Вызов операции Filterable.Delete у контейнера } end;//Op_Filterable_Delete Op_Filterable_ClearAll = {final} class {* Класс для вызова операции Filterable.ClearAll } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции Filterable.ClearAll у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции Filterable.ClearAll у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции Filterable.ClearAll у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции Filterable.ClearAll у контейнера } end;//Op_Filterable_ClearAll IFilterable_Refresh_Params = interface {* Параметры для операции Filterable.Refresh } function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); property ResultValue: Boolean read Get_ResultValue write Set_ResultValue; end;//IFilterable_Refresh_Params Op_Filterable_Refresh = {final} class {* Класс для вызова операции Filterable.Refresh } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции Filterable.Refresh у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции Filterable.Refresh у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции Filterable.Refresh у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции Filterable.Refresh у контейнера } end;//Op_Filterable_Refresh IFilterable_GetListType_Params = interface {* Параметры для операции Filterable.GetListType } function Get_ResultValue: TbsListType; procedure Set_ResultValue(aValue: TbsListType); property ResultValue: TbsListType read Get_ResultValue write Set_ResultValue; end;//IFilterable_GetListType_Params Op_Filterable_GetListType = {final} class {* Класс для вызова операции Filterable.GetListType } public class function Call(const aTarget: IvcmEntity): TbsListType; overload; {* Вызов операции Filterable.GetListType у сущности } class function Call(const aTarget: IvcmAggregate): TbsListType; overload; {* Вызов операции Filterable.GetListType у агрегации } class function Call(const aTarget: IvcmEntityForm): TbsListType; overload; {* Вызов операции Filterable.GetListType у формы } class function Call(const aTarget: IvcmContainer): TbsListType; overload; {* Вызов операции Filterable.GetListType у контейнера } end;//Op_Filterable_GetListType ILoadable_Load_Params = interface {* Параметры для операции Loadable.Load } function Get_Node: IeeNode; function Get_Data: IUnknown; function Get_nOp: TListLogicOperation; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); property Node: IeeNode read Get_Node; property Data: IUnknown read Get_Data; property nOp: TListLogicOperation read Get_nOp; property ResultValue: Boolean read Get_ResultValue write Set_ResultValue; end;//ILoadable_Load_Params Op_Loadable_Load = {final} class {* Класс для вызова операции Loadable.Load } public class function Call(const aTarget: IvcmEntity; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; overload; {* Вызов операции Loadable.Load у сущности } class function Call(const aTarget: IvcmAggregate; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; overload; {* Вызов операции Loadable.Load у агрегации } class function Call(const aTarget: IvcmEntityForm; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; overload; {* Вызов операции Loadable.Load у формы } class function Call(const aTarget: IvcmContainer; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; overload; {* Вызов операции Loadable.Load у контейнера } end;//Op_Loadable_Load {$If NOT Defined(Monitorings)} IFilters_GetSelected_Params = interface {* Параметры для операции Filters.GetSelected } function Get_ResultValue: IFiltersFromQuery; procedure Set_ResultValue(const aValue: IFiltersFromQuery); property ResultValue: IFiltersFromQuery read Get_ResultValue write Set_ResultValue; end;//IFilters_GetSelected_Params {$IfEnd} // NOT Defined(Monitorings) {$If NOT Defined(Monitorings)} Op_Filters_GetSelected = {final} class {* Класс для вызова операции Filters.GetSelected } public class function Call(const aTarget: IvcmEntity): IFiltersFromQuery; overload; {* Вызов операции Filters.GetSelected у сущности } class function Call(const aTarget: IvcmAggregate): IFiltersFromQuery; overload; {* Вызов операции Filters.GetSelected у агрегации } class function Call(const aTarget: IvcmEntityForm): IFiltersFromQuery; overload; {* Вызов операции Filters.GetSelected у формы } class function Call(const aTarget: IvcmContainer): IFiltersFromQuery; overload; {* Вызов операции Filters.GetSelected у контейнера } end;//Op_Filters_GetSelected {$IfEnd} // NOT Defined(Monitorings) Op_SearchParameter_QueryNotSaved = {final} class {* Класс для вызова операции SearchParameter.QueryNotSaved } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции SearchParameter.QueryNotSaved у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции SearchParameter.QueryNotSaved у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции SearchParameter.QueryNotSaved у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции SearchParameter.QueryNotSaved у контейнера } end;//Op_SearchParameter_QueryNotSaved Op_SearchParameter_ClearMistakes = {final} class {* Класс для вызова операции SearchParameter.ClearMistakes } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции SearchParameter.ClearMistakes у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции SearchParameter.ClearMistakes у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции SearchParameter.ClearMistakes у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции SearchParameter.ClearMistakes у контейнера } end;//Op_SearchParameter_ClearMistakes Op_SearchParameter_QuerySaved = {final} class {* Класс для вызова операции SearchParameter.QuerySaved } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции SearchParameter.QuerySaved у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции SearchParameter.QuerySaved у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции SearchParameter.QuerySaved у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции SearchParameter.QuerySaved у контейнера } end;//Op_SearchParameter_QuerySaved Op_PrintParams_UpdatePrinter = {final} class {* Класс для вызова операции PrintParams.UpdatePrinter } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции PrintParams.UpdatePrinter у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции PrintParams.UpdatePrinter у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции PrintParams.UpdatePrinter у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции PrintParams.UpdatePrinter у контейнера } class procedure Broadcast; {* Вызов операции PrintParams.UpdatePrinter у всех зарегистрированных сущностей } end;//Op_PrintParams_UpdatePrinter Op_List_SetNewContent = {final} class {* Класс для вызова операции List.SetNewContent } public class function Call(const aTarget: IvcmEntity): Boolean; overload; {* Вызов операции List.SetNewContent у сущности } class function Call(const aTarget: IvcmAggregate): Boolean; overload; {* Вызов операции List.SetNewContent у агрегации } class function Call(const aTarget: IvcmEntityForm): Boolean; overload; {* Вызов операции List.SetNewContent у формы } class function Call(const aTarget: IvcmContainer): Boolean; overload; {* Вызов операции List.SetNewContent у контейнера } end;//Op_List_SetNewContent const en_Query = 'Query'; en_capQuery = ''; op_ClearAll = 'ClearAll'; op_capClearAll = ''; op_SetList = 'SetList'; op_capSetList = ''; op_GetList = 'GetList'; op_capGetList = ''; en_Filterable = 'Filterable'; en_capFilterable = ''; op_Add = 'Add'; op_capAdd = ''; op_Delete = 'Delete'; op_capDelete = ''; op_Refresh = 'Refresh'; op_capRefresh = ''; op_GetListType = 'GetListType'; op_capGetListType = ''; en_Loadable = 'Loadable'; en_capLoadable = 'Это первый кандидат на превращение в Facet. Который нужно вызвать вот тут: f_RequestingForm.Entity.Operation(op_Loadable_Load, l_Params).Done'; op_Load = 'Load'; op_capLoad = 'Коллеги, кто может описать этот метод?'; en_Filters = 'Filters'; en_capFilters = ''; op_GetSelected = 'GetSelected'; op_capGetSelected = ''; en_SearchParameter = 'SearchParameter'; en_capSearchParameter = ''; op_QueryNotSaved = 'QueryNotSaved'; op_capQueryNotSaved = ''; op_ClearMistakes = 'ClearMistakes'; op_capClearMistakes = ''; op_QuerySaved = 'QuerySaved'; op_capQuerySaved = ''; en_PrintParams = 'PrintParams'; en_capPrintParams = ''; op_UpdatePrinter = 'UpdatePrinter'; op_capUpdatePrinter = ''; en_List = 'List'; en_capList = ''; op_SetNewContent = 'SetNewContent'; op_capSetNewContent = ''; en_CardOperation = 'CardOperation'; en_capCardOperation = ''; op_ExpandCollapse = 'ExpandCollapse'; op_capExpandCollapse = ''; op_DeleteAll = 'DeleteAll'; op_capDeleteAll = ''; op_CreateAttr = 'CreateAttr'; op_capCreateAttr = ''; op_OpenTreeSelection = 'OpenTreeSelection'; op_capOpenTreeSelection = ''; en_File = 'File'; en_capFile = 'Файл'; op_SaveToFolder = 'SaveToFolder'; op_capSaveToFolder = 'Сохранить в папки'; op_LoadFromFolder = 'LoadFromFolder'; op_capLoadFromFolder = 'Загрузить из папок'; op_GetOldQuery = 'GetOldQuery'; op_capGetOldQuery = ''; op_SearchType = 'SearchType'; op_capSearchType = ''; en_LogicOperation = 'LogicOperation'; en_capLogicOperation = ''; op_LogicOr = 'LogicOr'; op_capLogicOr = ''; op_LogicAnd = 'LogicAnd'; op_capLogicAnd = ''; op_LogicNot = 'LogicNot'; op_capLogicNot = ''; op_FiltersListOpen = 'FiltersListOpen'; op_capFiltersListOpen = 'Фильтры (вкладка)'; en_Preview = 'Preview'; en_capPreview = ''; op_ZoomIn = 'ZoomIn'; op_capZoomIn = ''; op_ZoomOut = 'ZoomOut'; op_capZoomOut = ''; op_ZoomWidth = 'ZoomWidth'; op_capZoomWidth = ''; op_ZoomPage = 'ZoomPage'; op_capZoomPage = ''; en_Document = 'Document'; en_capDocument = ''; op_FullSelectedSwitch = 'FullSelectedSwitch'; op_capFullSelectedSwitch = ''; op_RGBGrayscaleSwitch = 'RGBGrayscaleSwitch'; op_capRGBGrayscaleSwitch = ''; op_PrintInfoSwitch = 'PrintInfoSwitch'; op_capPrintInfoSwitch = ''; en_SubPanelSettings = 'SubPanelSettings'; en_capSubPanelSettings = 'Настройки панели меток'; op_ShowSpecial = 'ShowSpecial'; op_capShowSpecial = 'Показывать спецсимволы'; op_ShowInfo = 'ShowInfo'; op_capShowInfo = 'Показывать блоки'; en_Result = 'Result'; en_capResult = ''; op_Restore = 'Restore'; op_capRestore = ''; op_SaveAsDefault = 'SaveAsDefault'; op_capSaveAsDefault = ''; en_ColontitulMacro = 'ColontitulMacro'; en_capColontitulMacro = ''; op_AppTitle = 'AppTitle'; op_capAppTitle = ''; op_DocName = 'DocName'; op_capDocName = ''; op_DocFullName = 'DocFullName'; op_capDocFullName = ''; op_DocRedactionDate = 'DocRedactionDate'; op_capDocRedactionDate = ''; op_DocCurrentPage = 'DocCurrentPage'; op_capDocCurrentPage = ''; op_DocPagesCount = 'DocPagesCount'; op_capDocPagesCount = ''; op_CurrentDate = 'CurrentDate'; op_capCurrentDate = ''; op_CurrentTime = 'CurrentTime'; op_capCurrentTime = ''; op_InternalDocNumber = 'InternalDocNumber'; op_capInternalDocNumber = ''; op_DocumentSIze = 'DocumentSIze'; op_capDocumentSIze = ''; op_FilePosition = 'FilePosition'; op_capFilePosition = ''; op_Show = 'Show'; op_capShow = 'Показывать метки'; op_ShowByShortCut = 'ShowByShortCut'; op_capShowByShortCut = ''; var opcode_Query_ClearAll: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Query_SetList: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Query_GetList: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filterable_Add: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filterable_Delete: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filterable_ClearAll: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filterable_Refresh: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filterable_GetListType: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Loadable_Load: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filters_GetSelected: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SearchParameter_QueryNotSaved: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SearchParameter_ClearMistakes: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SearchParameter_QuerySaved: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_PrintParams_UpdatePrinter: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_List_SetNewContent: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_CardOperation_ExpandCollapse: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_CardOperation_DeleteAll: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_CardOperation_CreateAttr: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_CardOperation_OpenTreeSelection: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_File_SaveToFolder: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_File_LoadFromFolder: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Query_GetOldQuery: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Query_SearchType: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_LogicOperation_LogicOr: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_LogicOperation_LogicAnd: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_LogicOperation_LogicNot: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Filters_FiltersListOpen: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Preview_ZoomIn: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Preview_ZoomOut: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Preview_ZoomWidth: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Preview_ZoomPage: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Document_FullSelectedSwitch: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Document_RGBGrayscaleSwitch: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Document_PrintInfoSwitch: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SubPanelSettings_ShowSpecial: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SubPanelSettings_ShowInfo: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Result_Restore: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_Result_SaveAsDefault: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_AppTitle: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_DocName: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_DocFullName: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_DocRedactionDate: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_DocCurrentPage: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_DocPagesCount: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_CurrentDate: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_CurrentTime: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_InternalDocNumber: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_DocumentSIze: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_ColontitulMacro_FilePosition: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SubPanelSettings_Show: TvcmOPID = (rEnID : -1; rOpID : -1); var opcode_SubPanelSettings_ShowByShortCut: TvcmOPID = (rEnID : -1; rOpID : -1); {$IfEnd} // NOT Defined(Admin) implementation {$If NOT Defined(Admin)} uses l3ImplUses , l3CProtoObject {$If NOT Defined(NoVCM)} , vcmOperationsForRegister {$IfEnd} // NOT Defined(NoVCM) {$If NOT Defined(NoVCM)} , vcmOperationStatesForRegister {$IfEnd} // NOT Defined(NoVCM) , l3Base {$If NOT Defined(NoVCM)} , vcmBase {$IfEnd} // NOT Defined(NoVCM) ; type TQuery_ClearAll_Params = {final} class(Tl3CProtoObject, IQuery_ClearAll_Params) {* Реализация IQuery_ClearAll_Params } private f_NotClearRange: Boolean; protected function Get_NotClearRange: Boolean; public constructor Create(aNotClearRange: Boolean); reintroduce; class function Make(aNotClearRange: Boolean): IQuery_ClearAll_Params; reintroduce; end;//TQuery_ClearAll_Params TQuery_SetList_Params = {final} class(Tl3CProtoObject, IQuery_SetList_Params) {* Реализация IQuery_SetList_Params } private f_List: IdeList; f_InList: Boolean; protected function Get_List: IdeList; function Get_InList: Boolean; procedure ClearFields; override; public constructor Create(const aList: IdeList; aInList: Boolean); reintroduce; class function Make(const aList: IdeList; aInList: Boolean): IQuery_SetList_Params; reintroduce; end;//TQuery_SetList_Params TQuery_GetList_Params = {final} class(Tl3CProtoObject, IQuery_GetList_Params) {* Реализация IQuery_GetList_Params } private f_ResultValue: IdeList; protected function Get_ResultValue: IdeList; procedure Set_ResultValue(const aValue: IdeList); procedure ClearFields; override; public class function Make: IQuery_GetList_Params; reintroduce; end;//TQuery_GetList_Params TFilterable_Add_Params = {final} class(Tl3CProtoObject, IFilterable_Add_Params) {* Реализация IFilterable_Add_Params } private f_Filter: IFilterFromQuery; f_ResultValue: Boolean; protected function Get_Filter: IFilterFromQuery; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); procedure ClearFields; override; public constructor Create(const aFilter: IFilterFromQuery); reintroduce; class function Make(const aFilter: IFilterFromQuery): IFilterable_Add_Params; reintroduce; end;//TFilterable_Add_Params TFilterable_Delete_Params = {final} class(Tl3CProtoObject, IFilterable_Delete_Params) {* Реализация IFilterable_Delete_Params } private f_Filter: IFilterFromQuery; f_ResultValue: Boolean; protected function Get_Filter: IFilterFromQuery; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); procedure ClearFields; override; public constructor Create(const aFilter: IFilterFromQuery); reintroduce; class function Make(const aFilter: IFilterFromQuery): IFilterable_Delete_Params; reintroduce; end;//TFilterable_Delete_Params TFilterable_Refresh_Params = {final} class(Tl3CProtoObject, IFilterable_Refresh_Params) {* Реализация IFilterable_Refresh_Params } private f_ResultValue: Boolean; protected function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); public class function Make: IFilterable_Refresh_Params; reintroduce; end;//TFilterable_Refresh_Params TFilterable_GetListType_Params = {final} class(Tl3CProtoObject, IFilterable_GetListType_Params) {* Реализация IFilterable_GetListType_Params } private f_ResultValue: TbsListType; protected function Get_ResultValue: TbsListType; procedure Set_ResultValue(aValue: TbsListType); public class function Make: IFilterable_GetListType_Params; reintroduce; end;//TFilterable_GetListType_Params TLoadable_Load_Params = {final} class(Tl3CProtoObject, ILoadable_Load_Params) {* Реализация ILoadable_Load_Params } private f_Node: IeeNode; f_Data: IUnknown; f_nOp: TListLogicOperation; f_ResultValue: Boolean; protected function Get_Node: IeeNode; function Get_Data: IUnknown; function Get_nOp: TListLogicOperation; function Get_ResultValue: Boolean; procedure Set_ResultValue(aValue: Boolean); procedure ClearFields; override; public constructor Create(const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE); reintroduce; class function Make(const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): ILoadable_Load_Params; reintroduce; end;//TLoadable_Load_Params {$If NOT Defined(Monitorings)} TFilters_GetSelected_Params = {final} class(Tl3CProtoObject, IFilters_GetSelected_Params) {* Реализация IFilters_GetSelected_Params } private f_ResultValue: IFiltersFromQuery; protected function Get_ResultValue: IFiltersFromQuery; procedure Set_ResultValue(const aValue: IFiltersFromQuery); procedure ClearFields; override; public class function Make: IFilters_GetSelected_Params; reintroduce; end;//TFilters_GetSelected_Params {$IfEnd} // NOT Defined(Monitorings) constructor TQuery_ClearAll_Params.Create(aNotClearRange: Boolean); begin inherited Create; f_NotClearRange := aNotClearRange; end;//TQuery_ClearAll_Params.Create class function TQuery_ClearAll_Params.Make(aNotClearRange: Boolean): IQuery_ClearAll_Params; var l_Inst : TQuery_ClearAll_Params; begin l_Inst := Create(aNotClearRange); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TQuery_ClearAll_Params.Make function TQuery_ClearAll_Params.Get_NotClearRange: Boolean; begin Result := f_NotClearRange; end;//TQuery_ClearAll_Params.Get_NotClearRange class function Op_Query_ClearAll.Call(const aTarget: IvcmEntity; aNotClearRange: Boolean): Boolean; {* Вызов операции Query.ClearAll у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TQuery_ClearAll_Params.Make(aNotClearRange)); aTarget.Operation(opcode_Query_ClearAll, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Query_ClearAll.Call class function Op_Query_ClearAll.Call(const aTarget: IvcmAggregate; aNotClearRange: Boolean): Boolean; {* Вызов операции Query.ClearAll у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TQuery_ClearAll_Params.Make(aNotClearRange)); aTarget.Operation(opcode_Query_ClearAll, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Query_ClearAll.Call class function Op_Query_ClearAll.Call(const aTarget: IvcmEntityForm; aNotClearRange: Boolean): Boolean; {* Вызов операции Query.ClearAll у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aNotClearRange); end;//Op_Query_ClearAll.Call class function Op_Query_ClearAll.Call(const aTarget: IvcmContainer; aNotClearRange: Boolean): Boolean; {* Вызов операции Query.ClearAll у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aNotClearRange); end;//Op_Query_ClearAll.Call constructor TQuery_SetList_Params.Create(const aList: IdeList; aInList: Boolean); begin inherited Create; f_List := aList; f_InList := aInList; end;//TQuery_SetList_Params.Create class function TQuery_SetList_Params.Make(const aList: IdeList; aInList: Boolean): IQuery_SetList_Params; var l_Inst : TQuery_SetList_Params; begin l_Inst := Create(aList, aInList); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TQuery_SetList_Params.Make function TQuery_SetList_Params.Get_List: IdeList; begin Result := f_List; end;//TQuery_SetList_Params.Get_List function TQuery_SetList_Params.Get_InList: Boolean; begin Result := f_InList; end;//TQuery_SetList_Params.Get_InList procedure TQuery_SetList_Params.ClearFields; begin f_List := nil; inherited; end;//TQuery_SetList_Params.ClearFields class function Op_Query_SetList.Call(const aTarget: IvcmEntity; const aList: IdeList; aInList: Boolean): Boolean; {* Вызов операции Query.SetList у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TQuery_SetList_Params.Make(aList, aInList)); aTarget.Operation(opcode_Query_SetList, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Query_SetList.Call class function Op_Query_SetList.Call(const aTarget: IvcmAggregate; const aList: IdeList; aInList: Boolean): Boolean; {* Вызов операции Query.SetList у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TQuery_SetList_Params.Make(aList, aInList)); aTarget.Operation(opcode_Query_SetList, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Query_SetList.Call class function Op_Query_SetList.Call(const aTarget: IvcmEntityForm; const aList: IdeList; aInList: Boolean): Boolean; {* Вызов операции Query.SetList у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aList, aInList); end;//Op_Query_SetList.Call class function Op_Query_SetList.Call(const aTarget: IvcmContainer; const aList: IdeList; aInList: Boolean): Boolean; {* Вызов операции Query.SetList у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aList, aInList); end;//Op_Query_SetList.Call class function TQuery_GetList_Params.Make: IQuery_GetList_Params; var l_Inst : TQuery_GetList_Params; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TQuery_GetList_Params.Make function TQuery_GetList_Params.Get_ResultValue: IdeList; begin Result := f_ResultValue; end;//TQuery_GetList_Params.Get_ResultValue procedure TQuery_GetList_Params.Set_ResultValue(const aValue: IdeList); begin f_ResultValue := aValue; end;//TQuery_GetList_Params.Set_ResultValue procedure TQuery_GetList_Params.ClearFields; begin f_ResultValue := nil; inherited; end;//TQuery_GetList_Params.ClearFields class function Op_Query_GetList.Call(const aTarget: IvcmEntity): IdeList; {* Вызов операции Query.GetList у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TQuery_GetList_Params.Make); aTarget.Operation(opcode_Query_GetList, l_Params); with l_Params do begin if Done then begin Result := IQuery_GetList_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Query_GetList.Call class function Op_Query_GetList.Call(const aTarget: IvcmAggregate): IdeList; {* Вызов операции Query.GetList у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TQuery_GetList_Params.Make); aTarget.Operation(opcode_Query_GetList, l_Params); with l_Params do begin if Done then begin Result := IQuery_GetList_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Query_GetList.Call class function Op_Query_GetList.Call(const aTarget: IvcmEntityForm): IdeList; {* Вызов операции Query.GetList у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_Query_GetList.Call class function Op_Query_GetList.Call(const aTarget: IvcmContainer): IdeList; {* Вызов операции Query.GetList у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_Query_GetList.Call constructor TFilterable_Add_Params.Create(const aFilter: IFilterFromQuery); begin inherited Create; f_Filter := aFilter; end;//TFilterable_Add_Params.Create class function TFilterable_Add_Params.Make(const aFilter: IFilterFromQuery): IFilterable_Add_Params; var l_Inst : TFilterable_Add_Params; begin l_Inst := Create(aFilter); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TFilterable_Add_Params.Make function TFilterable_Add_Params.Get_Filter: IFilterFromQuery; begin Result := f_Filter; end;//TFilterable_Add_Params.Get_Filter function TFilterable_Add_Params.Get_ResultValue: Boolean; begin Result := f_ResultValue; end;//TFilterable_Add_Params.Get_ResultValue procedure TFilterable_Add_Params.Set_ResultValue(aValue: Boolean); begin f_ResultValue := aValue; end;//TFilterable_Add_Params.Set_ResultValue procedure TFilterable_Add_Params.ClearFields; begin f_Filter := nil; inherited; end;//TFilterable_Add_Params.ClearFields class function Op_Filterable_Add.Call(const aTarget: IvcmEntity; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Add у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_Add_Params.Make(aFilter)); aTarget.Operation(opcode_Filterable_Add, l_Params); with l_Params do begin if Done then begin Result := IFilterable_Add_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_Add.Call class function Op_Filterable_Add.Call(const aTarget: IvcmAggregate; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Add у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_Add_Params.Make(aFilter)); aTarget.Operation(opcode_Filterable_Add, l_Params); with l_Params do begin if Done then begin Result := IFilterable_Add_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_Add.Call class function Op_Filterable_Add.Call(const aTarget: IvcmEntityForm; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Add у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aFilter); end;//Op_Filterable_Add.Call class function Op_Filterable_Add.Call(const aTarget: IvcmContainer; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Add у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aFilter); end;//Op_Filterable_Add.Call constructor TFilterable_Delete_Params.Create(const aFilter: IFilterFromQuery); begin inherited Create; f_Filter := aFilter; end;//TFilterable_Delete_Params.Create class function TFilterable_Delete_Params.Make(const aFilter: IFilterFromQuery): IFilterable_Delete_Params; var l_Inst : TFilterable_Delete_Params; begin l_Inst := Create(aFilter); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TFilterable_Delete_Params.Make function TFilterable_Delete_Params.Get_Filter: IFilterFromQuery; begin Result := f_Filter; end;//TFilterable_Delete_Params.Get_Filter function TFilterable_Delete_Params.Get_ResultValue: Boolean; begin Result := f_ResultValue; end;//TFilterable_Delete_Params.Get_ResultValue procedure TFilterable_Delete_Params.Set_ResultValue(aValue: Boolean); begin f_ResultValue := aValue; end;//TFilterable_Delete_Params.Set_ResultValue procedure TFilterable_Delete_Params.ClearFields; begin f_Filter := nil; inherited; end;//TFilterable_Delete_Params.ClearFields class function Op_Filterable_Delete.Call(const aTarget: IvcmEntity; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Delete у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_Delete_Params.Make(aFilter)); aTarget.Operation(opcode_Filterable_Delete, l_Params); with l_Params do begin if Done then begin Result := IFilterable_Delete_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_Delete.Call class function Op_Filterable_Delete.Call(const aTarget: IvcmAggregate; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Delete у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_Delete_Params.Make(aFilter)); aTarget.Operation(opcode_Filterable_Delete, l_Params); with l_Params do begin if Done then begin Result := IFilterable_Delete_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_Delete.Call class function Op_Filterable_Delete.Call(const aTarget: IvcmEntityForm; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Delete у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aFilter); end;//Op_Filterable_Delete.Call class function Op_Filterable_Delete.Call(const aTarget: IvcmContainer; const aFilter: IFilterFromQuery): Boolean; {* Вызов операции Filterable.Delete у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aFilter); end;//Op_Filterable_Delete.Call class function Op_Filterable_ClearAll.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции Filterable.ClearAll у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_Filterable_ClearAll, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_ClearAll.Call class function Op_Filterable_ClearAll.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции Filterable.ClearAll у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_Filterable_ClearAll, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_ClearAll.Call class function Op_Filterable_ClearAll.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции Filterable.ClearAll у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_Filterable_ClearAll.Call class function Op_Filterable_ClearAll.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции Filterable.ClearAll у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_Filterable_ClearAll.Call class function TFilterable_Refresh_Params.Make: IFilterable_Refresh_Params; var l_Inst : TFilterable_Refresh_Params; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TFilterable_Refresh_Params.Make function TFilterable_Refresh_Params.Get_ResultValue: Boolean; begin Result := f_ResultValue; end;//TFilterable_Refresh_Params.Get_ResultValue procedure TFilterable_Refresh_Params.Set_ResultValue(aValue: Boolean); begin f_ResultValue := aValue; end;//TFilterable_Refresh_Params.Set_ResultValue class function Op_Filterable_Refresh.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции Filterable.Refresh у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_Refresh_Params.Make); aTarget.Operation(opcode_Filterable_Refresh, l_Params); with l_Params do begin if Done then begin Result := IFilterable_Refresh_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_Refresh.Call class function Op_Filterable_Refresh.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции Filterable.Refresh у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_Refresh_Params.Make); aTarget.Operation(opcode_Filterable_Refresh, l_Params); with l_Params do begin if Done then begin Result := IFilterable_Refresh_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_Refresh.Call class function Op_Filterable_Refresh.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции Filterable.Refresh у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_Filterable_Refresh.Call class function Op_Filterable_Refresh.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции Filterable.Refresh у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_Filterable_Refresh.Call class function TFilterable_GetListType_Params.Make: IFilterable_GetListType_Params; var l_Inst : TFilterable_GetListType_Params; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TFilterable_GetListType_Params.Make function TFilterable_GetListType_Params.Get_ResultValue: TbsListType; begin Result := f_ResultValue; end;//TFilterable_GetListType_Params.Get_ResultValue procedure TFilterable_GetListType_Params.Set_ResultValue(aValue: TbsListType); begin f_ResultValue := aValue; end;//TFilterable_GetListType_Params.Set_ResultValue class function Op_Filterable_GetListType.Call(const aTarget: IvcmEntity): TbsListType; {* Вызов операции Filterable.GetListType у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_GetListType_Params.Make); aTarget.Operation(opcode_Filterable_GetListType, l_Params); with l_Params do begin if Done then begin Result := IFilterable_GetListType_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_GetListType.Call class function Op_Filterable_GetListType.Call(const aTarget: IvcmAggregate): TbsListType; {* Вызов операции Filterable.GetListType у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilterable_GetListType_Params.Make); aTarget.Operation(opcode_Filterable_GetListType, l_Params); with l_Params do begin if Done then begin Result := IFilterable_GetListType_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filterable_GetListType.Call class function Op_Filterable_GetListType.Call(const aTarget: IvcmEntityForm): TbsListType; {* Вызов операции Filterable.GetListType у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_Filterable_GetListType.Call class function Op_Filterable_GetListType.Call(const aTarget: IvcmContainer): TbsListType; {* Вызов операции Filterable.GetListType у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_Filterable_GetListType.Call constructor TLoadable_Load_Params.Create(const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE); begin inherited Create; f_Node := aNode; f_Data := aData; f_nOp := anOp; end;//TLoadable_Load_Params.Create class function TLoadable_Load_Params.Make(const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): ILoadable_Load_Params; var l_Inst : TLoadable_Load_Params; begin l_Inst := Create(aNode, aData, anOp); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TLoadable_Load_Params.Make function TLoadable_Load_Params.Get_Node: IeeNode; begin Result := f_Node; end;//TLoadable_Load_Params.Get_Node function TLoadable_Load_Params.Get_Data: IUnknown; begin Result := f_Data; end;//TLoadable_Load_Params.Get_Data function TLoadable_Load_Params.Get_nOp: TListLogicOperation; begin Result := f_nOp; end;//TLoadable_Load_Params.Get_nOp function TLoadable_Load_Params.Get_ResultValue: Boolean; begin Result := f_ResultValue; end;//TLoadable_Load_Params.Get_ResultValue procedure TLoadable_Load_Params.Set_ResultValue(aValue: Boolean); begin f_ResultValue := aValue; end;//TLoadable_Load_Params.Set_ResultValue procedure TLoadable_Load_Params.ClearFields; begin f_Node := nil; f_Data := nil; inherited; end;//TLoadable_Load_Params.ClearFields class function Op_Loadable_Load.Call(const aTarget: IvcmEntity; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; {* Вызов операции Loadable.Load у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TLoadable_Load_Params.Make(aNode, aData, anOp)); aTarget.Operation(opcode_Loadable_Load, l_Params); with l_Params do begin if Done then begin Result := ILoadable_Load_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Loadable_Load.Call class function Op_Loadable_Load.Call(const aTarget: IvcmAggregate; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; {* Вызов операции Loadable.Load у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TLoadable_Load_Params.Make(aNode, aData, anOp)); aTarget.Operation(opcode_Loadable_Load, l_Params); with l_Params do begin if Done then begin Result := ILoadable_Load_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Loadable_Load.Call class function Op_Loadable_Load.Call(const aTarget: IvcmEntityForm; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; {* Вызов операции Loadable.Load у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity, aNode, aData, anOp); end;//Op_Loadable_Load.Call class function Op_Loadable_Load.Call(const aTarget: IvcmContainer; const aNode: IeeNode; const aData: IUnknown; anOp: TListLogicOperation = LLO_NONE): Boolean; {* Вызов операции Loadable.Load у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm, aNode, aData, anOp); end;//Op_Loadable_Load.Call {$If NOT Defined(Monitorings)} class function TFilters_GetSelected_Params.Make: IFilters_GetSelected_Params; var l_Inst : TFilters_GetSelected_Params; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TFilters_GetSelected_Params.Make function TFilters_GetSelected_Params.Get_ResultValue: IFiltersFromQuery; begin Result := f_ResultValue; end;//TFilters_GetSelected_Params.Get_ResultValue procedure TFilters_GetSelected_Params.Set_ResultValue(const aValue: IFiltersFromQuery); begin f_ResultValue := aValue; end;//TFilters_GetSelected_Params.Set_ResultValue procedure TFilters_GetSelected_Params.ClearFields; begin Finalize(f_ResultValue); inherited; end;//TFilters_GetSelected_Params.ClearFields {$IfEnd} // NOT Defined(Monitorings) {$If NOT Defined(Monitorings)} class function Op_Filters_GetSelected.Call(const aTarget: IvcmEntity): IFiltersFromQuery; {* Вызов операции Filters.GetSelected у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilters_GetSelected_Params.Make); aTarget.Operation(opcode_Filters_GetSelected, l_Params); with l_Params do begin if Done then begin Result := IFilters_GetSelected_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filters_GetSelected.Call class function Op_Filters_GetSelected.Call(const aTarget: IvcmAggregate): IFiltersFromQuery; {* Вызов операции Filters.GetSelected у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := TvcmExecuteParams.MakeForInternal(TFilters_GetSelected_Params.Make); aTarget.Operation(opcode_Filters_GetSelected, l_Params); with l_Params do begin if Done then begin Result := IFilters_GetSelected_Params(Data).ResultValue; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_Filters_GetSelected.Call class function Op_Filters_GetSelected.Call(const aTarget: IvcmEntityForm): IFiltersFromQuery; {* Вызов операции Filters.GetSelected у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_Filters_GetSelected.Call class function Op_Filters_GetSelected.Call(const aTarget: IvcmContainer): IFiltersFromQuery; {* Вызов операции Filters.GetSelected у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_Filters_GetSelected.Call {$IfEnd} // NOT Defined(Monitorings) class function Op_SearchParameter_QueryNotSaved.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции SearchParameter.QueryNotSaved у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_SearchParameter_QueryNotSaved, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_SearchParameter_QueryNotSaved.Call class function Op_SearchParameter_QueryNotSaved.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции SearchParameter.QueryNotSaved у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_SearchParameter_QueryNotSaved, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_SearchParameter_QueryNotSaved.Call class function Op_SearchParameter_QueryNotSaved.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции SearchParameter.QueryNotSaved у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_SearchParameter_QueryNotSaved.Call class function Op_SearchParameter_QueryNotSaved.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции SearchParameter.QueryNotSaved у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_SearchParameter_QueryNotSaved.Call class function Op_SearchParameter_ClearMistakes.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции SearchParameter.ClearMistakes у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_SearchParameter_ClearMistakes, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_SearchParameter_ClearMistakes.Call class function Op_SearchParameter_ClearMistakes.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции SearchParameter.ClearMistakes у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_SearchParameter_ClearMistakes, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_SearchParameter_ClearMistakes.Call class function Op_SearchParameter_ClearMistakes.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции SearchParameter.ClearMistakes у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_SearchParameter_ClearMistakes.Call class function Op_SearchParameter_ClearMistakes.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции SearchParameter.ClearMistakes у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_SearchParameter_ClearMistakes.Call class function Op_SearchParameter_QuerySaved.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции SearchParameter.QuerySaved у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_SearchParameter_QuerySaved, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_SearchParameter_QuerySaved.Call class function Op_SearchParameter_QuerySaved.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции SearchParameter.QuerySaved у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_SearchParameter_QuerySaved, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_SearchParameter_QuerySaved.Call class function Op_SearchParameter_QuerySaved.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции SearchParameter.QuerySaved у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_SearchParameter_QuerySaved.Call class function Op_SearchParameter_QuerySaved.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции SearchParameter.QuerySaved у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_SearchParameter_QuerySaved.Call class function Op_PrintParams_UpdatePrinter.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции PrintParams.UpdatePrinter у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_PrintParams_UpdatePrinter, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_PrintParams_UpdatePrinter.Call class function Op_PrintParams_UpdatePrinter.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции PrintParams.UpdatePrinter у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_PrintParams_UpdatePrinter, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_PrintParams_UpdatePrinter.Call class function Op_PrintParams_UpdatePrinter.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции PrintParams.UpdatePrinter у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_PrintParams_UpdatePrinter.Call class function Op_PrintParams_UpdatePrinter.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции PrintParams.UpdatePrinter у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_PrintParams_UpdatePrinter.Call class procedure Op_PrintParams_UpdatePrinter.Broadcast; {* Вызов операции PrintParams.UpdatePrinter у всех зарегистрированных сущностей } var l_Params : IvcmExecuteParams; begin if (vcmDispatcher <> nil) then begin l_Params := vcmParams; vcmDispatcher.EntityOperationBroadcast(opcode_PrintParams_UpdatePrinter, l_Params); end//vcmDispatcher <> nil end;//Op_PrintParams_UpdatePrinter.Broadcast class function Op_List_SetNewContent.Call(const aTarget: IvcmEntity): Boolean; {* Вызов операции List.SetNewContent у сущности } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_List_SetNewContent, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_List_SetNewContent.Call class function Op_List_SetNewContent.Call(const aTarget: IvcmAggregate): Boolean; {* Вызов операции List.SetNewContent у агрегации } var l_Params : IvcmExecuteParams; begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then begin l_Params := vcmParams; aTarget.Operation(opcode_List_SetNewContent, l_Params); with l_Params do begin if Done then begin Result := true; end;//Done end;//with l_Params end;//aTarget <> nil end;//Op_List_SetNewContent.Call class function Op_List_SetNewContent.Call(const aTarget: IvcmEntityForm): Boolean; {* Вызов операции List.SetNewContent у формы } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.Entity); end;//Op_List_SetNewContent.Call class function Op_List_SetNewContent.Call(const aTarget: IvcmContainer): Boolean; {* Вызов операции List.SetNewContent у контейнера } begin l3FillChar(Result, SizeOf(Result)); if (aTarget <> nil) then Result := Call(aTarget.AsForm); end;//Op_List_SetNewContent.Call initialization with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Query, op_ClearAll, en_capQuery, op_capClearAll, True, False, opcode_Query_ClearAll)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Query, op_SetList, en_capQuery, op_capSetList, True, False, opcode_Query_SetList)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Query, op_GetList, en_capQuery, op_capGetList, True, False, opcode_Query_GetList)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filterable, op_Add, en_capFilterable, op_capAdd, True, False, opcode_Filterable_Add)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filterable, op_Delete, en_capFilterable, op_capDelete, True, False, opcode_Filterable_Delete)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filterable, op_ClearAll, en_capFilterable, op_capClearAll, True, False, opcode_Filterable_ClearAll)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filterable, op_Refresh, en_capFilterable, op_capRefresh, True, False, opcode_Filterable_Refresh)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filterable, op_GetListType, en_capFilterable, op_capGetListType, True, False, opcode_Filterable_GetListType)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Loadable, op_Load, en_capLoadable, op_capLoad, True, False, opcode_Loadable_Load)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filters, op_GetSelected, en_capFilters, op_capGetSelected, True, False, opcode_Filters_GetSelected)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SearchParameter, op_QueryNotSaved, en_capSearchParameter, op_capQueryNotSaved, True, False, opcode_SearchParameter_QueryNotSaved)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SearchParameter, op_ClearMistakes, en_capSearchParameter, op_capClearMistakes, True, False, opcode_SearchParameter_ClearMistakes)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SearchParameter, op_QuerySaved, en_capSearchParameter, op_capQuerySaved, True, False, opcode_SearchParameter_QuerySaved)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_PrintParams, op_UpdatePrinter, en_capPrintParams, op_capUpdatePrinter, True, False, opcode_PrintParams_UpdatePrinter)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_List, op_SetNewContent, en_capList, op_capSetNewContent, True, False, opcode_List_SetNewContent)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_CardOperation, op_ExpandCollapse, en_capCardOperation, op_capExpandCollapse, False, False, opcode_CardOperation_ExpandCollapse)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_CardOperation, op_DeleteAll, en_capCardOperation, op_capDeleteAll, False, False, opcode_CardOperation_DeleteAll)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_CardOperation, op_CreateAttr, en_capCardOperation, op_capCreateAttr, False, False, opcode_CardOperation_CreateAttr)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_CardOperation, op_OpenTreeSelection, en_capCardOperation, op_capOpenTreeSelection, False, False, opcode_CardOperation_OpenTreeSelection)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_File, op_SaveToFolder, en_capFile, op_capSaveToFolder, False, False, opcode_File_SaveToFolder)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_File, op_LoadFromFolder, en_capFile, op_capLoadFromFolder, False, False, opcode_File_LoadFromFolder)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Query, op_GetOldQuery, en_capQuery, op_capGetOldQuery, False, False, opcode_Query_GetOldQuery)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Query, op_SearchType, en_capQuery, op_capSearchType, False, False, opcode_Query_SearchType)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_LogicOperation, op_LogicOr, en_capLogicOperation, op_capLogicOr, False, False, opcode_LogicOperation_LogicOr)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_LogicOperation, op_LogicAnd, en_capLogicOperation, op_capLogicAnd, False, False, opcode_LogicOperation_LogicAnd)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_LogicOperation, op_LogicNot, en_capLogicOperation, op_capLogicNot, False, False, opcode_LogicOperation_LogicNot)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Filters, op_FiltersListOpen, en_capFilters, op_capFiltersListOpen, False, False, opcode_Filters_FiltersListOpen)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Preview, op_ZoomIn, en_capPreview, op_capZoomIn, False, False, opcode_Preview_ZoomIn)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Preview, op_ZoomOut, en_capPreview, op_capZoomOut, False, False, opcode_Preview_ZoomOut)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Preview, op_ZoomWidth, en_capPreview, op_capZoomWidth, False, False, opcode_Preview_ZoomWidth)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Preview, op_ZoomPage, en_capPreview, op_capZoomPage, False, False, opcode_Preview_ZoomPage)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Document, op_FullSelectedSwitch, en_capDocument, op_capFullSelectedSwitch, False, False, opcode_Document_FullSelectedSwitch)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Document, op_RGBGrayscaleSwitch, en_capDocument, op_capRGBGrayscaleSwitch, False, False, opcode_Document_RGBGrayscaleSwitch)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Document, op_PrintInfoSwitch, en_capDocument, op_capPrintInfoSwitch, False, False, opcode_Document_PrintInfoSwitch)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SubPanelSettings, op_ShowSpecial, en_capSubPanelSettings, op_capShowSpecial, False, False, opcode_SubPanelSettings_ShowSpecial)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SubPanelSettings, op_ShowInfo, en_capSubPanelSettings, op_capShowInfo, False, False, opcode_SubPanelSettings_ShowInfo)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_Restore, en_capResult, op_capRestore, False, False, opcode_Result_Restore)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_Result, op_SaveAsDefault, en_capResult, op_capSaveAsDefault, False, False, opcode_Result_SaveAsDefault)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_AppTitle, en_capColontitulMacro, op_capAppTitle, False, False, opcode_ColontitulMacro_AppTitle)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_DocName, en_capColontitulMacro, op_capDocName, False, False, opcode_ColontitulMacro_DocName)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_DocFullName, en_capColontitulMacro, op_capDocFullName, False, False, opcode_ColontitulMacro_DocFullName)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_DocRedactionDate, en_capColontitulMacro, op_capDocRedactionDate, False, False, opcode_ColontitulMacro_DocRedactionDate)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_DocCurrentPage, en_capColontitulMacro, op_capDocCurrentPage, False, False, opcode_ColontitulMacro_DocCurrentPage)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_DocPagesCount, en_capColontitulMacro, op_capDocPagesCount, False, False, opcode_ColontitulMacro_DocPagesCount)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_CurrentDate, en_capColontitulMacro, op_capCurrentDate, False, False, opcode_ColontitulMacro_CurrentDate)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_CurrentTime, en_capColontitulMacro, op_capCurrentTime, False, False, opcode_ColontitulMacro_CurrentTime)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_InternalDocNumber, en_capColontitulMacro, op_capInternalDocNumber, False, False, opcode_ColontitulMacro_InternalDocNumber)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_DocumentSIze, en_capColontitulMacro, op_capDocumentSIze, False, False, opcode_ColontitulMacro_DocumentSIze)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_ColontitulMacro, op_FilePosition, en_capColontitulMacro, op_capFilePosition, False, False, opcode_ColontitulMacro_FilePosition)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SubPanelSettings, op_Show, en_capSubPanelSettings, op_capShow, False, False, opcode_SubPanelSettings_Show)) do begin end; with TvcmOperationsForRegister.AddOperation(TvcmOperationForRegister_C(en_SubPanelSettings, op_ShowByShortCut, en_capSubPanelSettings, op_capShowByShortCut, False, False, opcode_SubPanelSettings_ShowByShortCut)) do begin end; {$IfEnd} // NOT Defined(Admin) end.
unit WarningKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы Warning } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\Forms\WarningKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "WarningKeywordsPack" MUID: (4AB1355B01EA_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , Warning_Form , tfwPropertyLike {$If Defined(Nemesis)} , nscEditor {$IfEnd} // Defined(Nemesis) , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwControlString , kwBynameControlPush , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4AB1355B01EA_Packimpl_uses* //#UC END# *4AB1355B01EA_Packimpl_uses* ; type TkwWarningFormViewer = {final} class(TtfwPropertyLike) {* Слово скрипта .TWarningForm.Viewer } private function Viewer(const aCtx: TtfwContext; aWarningForm: TWarningForm): TnscEditor; {* Реализация слова скрипта .TWarningForm.Viewer } 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;//TkwWarningFormViewer Tkw_Form_Warning = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы Warning ---- *Пример использования*: [code]форма::Warning TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_Warning Tkw_Warning_Control_Viewer = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Viewer ---- *Пример использования*: [code]контрол::Viewer TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Warning_Control_Viewer Tkw_Warning_Control_Viewer_Push = {final} class(TkwBynameControlPush) {* Слово словаря для контрола Viewer ---- *Пример использования*: [code]контрол::Viewer:push pop:control:SetFocus ASSERT[code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Warning_Control_Viewer_Push function TkwWarningFormViewer.Viewer(const aCtx: TtfwContext; aWarningForm: TWarningForm): TnscEditor; {* Реализация слова скрипта .TWarningForm.Viewer } begin Result := aWarningForm.Viewer; end;//TkwWarningFormViewer.Viewer class function TkwWarningFormViewer.GetWordNameForRegister: AnsiString; begin Result := '.TWarningForm.Viewer'; end;//TkwWarningFormViewer.GetWordNameForRegister function TkwWarningFormViewer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscEditor); end;//TkwWarningFormViewer.GetResultTypeInfo function TkwWarningFormViewer.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwWarningFormViewer.GetAllParamsCount function TkwWarningFormViewer.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TWarningForm)]); end;//TkwWarningFormViewer.ParamsTypes procedure TkwWarningFormViewer.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Viewer', aCtx); end;//TkwWarningFormViewer.SetValuePrim procedure TkwWarningFormViewer.DoDoIt(const aCtx: TtfwContext); var l_aWarningForm: TWarningForm; begin try l_aWarningForm := TWarningForm(aCtx.rEngine.PopObjAs(TWarningForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aWarningForm: TWarningForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Viewer(aCtx, l_aWarningForm)); end;//TkwWarningFormViewer.DoDoIt function Tkw_Form_Warning.GetString: AnsiString; begin Result := 'WarningForm'; end;//Tkw_Form_Warning.GetString class procedure Tkw_Form_Warning.RegisterInEngine; begin inherited; TtfwClassRef.Register(TWarningForm); end;//Tkw_Form_Warning.RegisterInEngine class function Tkw_Form_Warning.GetWordNameForRegister: AnsiString; begin Result := 'форма::Warning'; end;//Tkw_Form_Warning.GetWordNameForRegister function Tkw_Warning_Control_Viewer.GetString: AnsiString; begin Result := 'Viewer'; end;//Tkw_Warning_Control_Viewer.GetString class procedure Tkw_Warning_Control_Viewer.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscEditor); end;//Tkw_Warning_Control_Viewer.RegisterInEngine class function Tkw_Warning_Control_Viewer.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Viewer'; end;//Tkw_Warning_Control_Viewer.GetWordNameForRegister procedure Tkw_Warning_Control_Viewer_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Viewer'); inherited; end;//Tkw_Warning_Control_Viewer_Push.DoDoIt class function Tkw_Warning_Control_Viewer_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Viewer:push'; end;//Tkw_Warning_Control_Viewer_Push.GetWordNameForRegister initialization TkwWarningFormViewer.RegisterInEngine; {* Регистрация WarningForm_Viewer } Tkw_Form_Warning.RegisterInEngine; {* Регистрация Tkw_Form_Warning } Tkw_Warning_Control_Viewer.RegisterInEngine; {* Регистрация Tkw_Warning_Control_Viewer } Tkw_Warning_Control_Viewer_Push.RegisterInEngine; {* Регистрация Tkw_Warning_Control_Viewer_Push } TtfwTypeRegistrator.RegisterType(TypeInfo(TWarningForm)); {* Регистрация типа TWarningForm } {$If Defined(Nemesis)} TtfwTypeRegistrator.RegisterType(TypeInfo(TnscEditor)); {* Регистрация типа TnscEditor } {$IfEnd} // Defined(Nemesis) {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
{ GDAX/Coinbase-Pro client library Copyright (c) 2018 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. } unit gdax.api.authenticator; {$i gdax.inc} interface uses Classes, SysUtils, gdax.api.consts, gdax.api.types; type { TGDAXAuthenticatorImpl } TGDAXAuthenticatorImpl = class(TInterfacedObject,IGDAXAuthenticator) strict private FKey: String; FPass: String; FSecret: String; FTime: IGDAXTime; FUseLocalTime: Boolean; FMode: TGDAXApi; protected function GetKey: String; function GetMode: TGDAXApi; function GetPassphrase: String; function GetSecret: String; function GetTime: IGDAXTime; function GetUseLocalTime: Boolean; procedure SetKey(Const AValue: String); procedure SetMode(Const AValue: TGDAXApi); procedure SetPassphrase(Const AValue: String); procedure SetSecret(Const AValue: String); procedure SetUseLocalTime(Const AValue: Boolean); strict protected procedure DoBuildHeaders(Const AOutput:TStrings;Const ASignature:String; Const AEpoch:Integer);virtual; public property Key: String read GetKey write SetKey; property Secret: String read GetSecret write SetSecret; property Passphrase: String read GetPassphrase write SetPassphrase; (* when true, this machine's time will be used when HMAC signing to save a request to GDAX's time endpoint *) property UseLocalTime: Boolean read GetUseLocalTime write SetUseLocalTime; property Mode: TGDAXApi read GetMode write SetMode; procedure BuildHeaders(Const AOutput:TStrings;Const ASignature:String; Const AEpoch:Integer); function GenerateAccessSignature(Const AOperation:TRestOperation; Const ARequestPath:String;Out Epoch:Integer;Const ARequestBody:String=''):String; constructor Create;virtual; destructor Destroy; override; end; implementation uses DateUtils, SbpBase64, gdax.api.time, HlpIHashInfo, HlpConverters, HlpHashFactory; { TGDAXAuthenticatorImpl } procedure TGDAXAuthenticatorImpl.BuildHeaders(Const AOutput: TStrings; Const ASignature: String;Const AEpoch:Integer); begin DoBuildHeaders(AOutput,ASignature,AEpoch); end; constructor TGDAXAuthenticatorImpl.Create; begin FTime := TGDAXTimeImpl.Create; FTime.Authenticator := Self; FUseLocalTime := True; end; destructor TGDAXAuthenticatorImpl.Destroy; begin FTime := nil; inherited; end; function TGDAXAuthenticatorImpl.GetKey: String; begin Result := FKey; end; function TGDAXAuthenticatorImpl.GetMode: TGDAXApi; begin Result := FMode; end; function TGDAXAuthenticatorImpl.GetPassphrase: String; begin Result := FPass; end; function TGDAXAuthenticatorImpl.GetSecret: String; begin Result := FSecret; end; function TGDAXAuthenticatorImpl.GetTime: IGDAXTime; begin Result := FTime; end; function TGDAXAuthenticatorImpl.GetUseLocalTime: Boolean; begin Result := FUseLocalTime; end; procedure TGDAXAuthenticatorImpl.SetKey(Const AValue: String); begin FKey := AValue; end; procedure TGDAXAuthenticatorImpl.SetMode(Const AValue: TGDAXApi); begin FMode := AValue; end; procedure TGDAXAuthenticatorImpl.SetPassphrase(Const AValue: String); begin FPass := AValue; end; procedure TGDAXAuthenticatorImpl.SetSecret(Const AValue: String); begin FSecret := AValue; end; procedure TGDAXAuthenticatorImpl.SetUseLocalTime(Const AValue: Boolean); begin FUseLocalTime := AValue; end; procedure TGDAXAuthenticatorImpl.DoBuildHeaders(Const AOutput: TStrings; Const ASignature: String;Const AEpoch:Integer); begin AOutput.Clear; AOutput.NameValueSeparator:=':'; AOutput.Add('%s: %s',['Connection','keep-alive']); AOutput.Add('%s: %s',['Content-Type','application/json']); AOutput.Add('%s: %s',['User-Agent',USER_AGENT_MOZILLA]); AOutput.Add('%s: %s',[CB_ACCESS_KEY,FKey]); AOutput.Add('%s: %s',[CB_ACCESS_SIGN,ASignature]); AOutput.Add('%s: %s',[CB_ACCESS_TIME,IntToStr(AEpoch)]); AOutput.Add('%s: %s',[CB_ACCESS_PASS,FPass]); end; function TGDAXAuthenticatorImpl.GenerateAccessSignature( Const AOperation: TRestOperation; Const ARequestPath: String; Out Epoch:Integer;Const ARequestBody: String): String; var LContent:String; LError:String; LMessage:String; LHMAC:IHMAC; begin //https://docs.gdax.com/#creating-a-request Result:=''; LHMAC := THashFactory.THMAC.CreateHMAC(THashFactory.TCrypto.CreateSHA2_256); if not FUseLocalTime then begin if not FTime.Get(LContent,LError) then raise Exception.Create(LError); Epoch := Trunc(FTime.Epoch); end else Epoch := DateTimeToUnix(LocalTimeToUniversal(Now)); LMessage := IntToStr(Trunc(Epoch)); //then append the operation case AOperation of roGet: LMessage := LMessage+OP_GET; roPost: LMessage := LMessage+OP_POST; roDelete: LMessage := LMessage+OP_DELETE; end; //now add the request path LMessage := Trim(LMessage+ARequestPath); //now if there is a body, add it if AOperation=roPost then LMessage := LMessage+Trim(ARequestBody); //decode the base64 encoded secret and record to key LHMAC.Key := TBase64.Default.Decode( String( TEncoding.UTF8.GetString( TConverters.ConvertStringToBytes(FSecret, TEncoding.UTF8) ) ) ); //using decoded key and message, sign using HMAC Result := TBase64.Default.Encode( LHMAC.ComputeString(LMessage, TEncoding.UTF8).GetBytes() ); end; end.
unit uPermissoesAcoes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, DB, ZAbstractRODataset, ZDataset, StdCtrls, DBClient, ImgList, JvExControls, JvXPCore, JvXPButtons, ExtCtrls, CheckLst, ComCtrls, JvExComCtrls, JvDBTreeView; type TTipoPermissao = (tpGrupo, tpUsuario); TString = class(TObject) private vStr: string; public constructor Create(const AStr: string); property Texto: string read vStr write vStr; end; TfrmPermissoesAcoes = class(TForm) lbCategoria: TLabel; qrCategoria: TZReadOnlyQuery; dsCategoria: TDataSource; cbCategoria: TcxLookupComboBox; lbDescricao: TLabel; tvMenus: TJvDBTreeView; clbAcoes: TCheckListBox; Panel1: TPanel; ImageList1: TImageList; qrMenus: TZReadOnlyQuery; dsMenus: TDataSource; cdsAcao: TClientDataSet; cdsAcaoid: TIntegerField; cdsAcaoid_menu: TIntegerField; cdsAcaodescricao: TStringField; cdsAcaopermissao: TStringField; qrAcao: TZReadOnlyQuery; Panel2: TPanel; btnGravar: TJvXPButton; btnFechar: TJvXPButton; btnAlterar: TJvXPButton; btnCancelar: TJvXPButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure tvMenusGetImageIndex(Sender: TObject; Node: TTreeNode); procedure tvMenusGetSelectedIndex(Sender: TObject; Node: TTreeNode); procedure clbAcoesClick(Sender: TObject); procedure btnGravarClick(Sender: TObject); procedure btnFecharClick(Sender: TObject); procedure btnAlterarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure dsMenusDataChange(Sender: TObject; Field: TField); private FTipoPermissao: TTipoPermissao; FTabela, FCampo: string; procedure SetTipoPermissao(const Value: TTipoPermissao); { Private declarations } procedure VeAcao(const AID_User: Integer); procedure VeAcaoMenu(const AID_Menu: Integer); procedure VeEditaAcao(const AID_Acao: Integer); procedure GravaAcao(const AID_User: Integer); procedure VeEdicao(AEditar: Boolean); procedure VePermissaoMenuPai(const no: TTreeNode; AID_User: Integer); function PermissaoPaiExiste(aID_User, aID: Integer): Boolean; procedure GravaPermissaoPai(aID_User, aID: Integer); public { Public declarations } property TipoPermissao: TTipoPermissao read FTipoPermissao write SetTipoPermissao; end; var frmPermissoesAcoes: TfrmPermissoesAcoes; implementation uses udmPrincipal; {$R *.dfm} { TfrmPermissoesAcoes } procedure TfrmPermissoesAcoes.SetTipoPermissao( const Value: TTipoPermissao); begin FTipoPermissao := Value; case FTipoPermissao of tpGrupo: begin lbCategoria.Caption := 'Selecione um grupo:'; lbDescricao.Caption := 'Configure abaixo as operações permitidas para o grupo:'; qrCategoria.Close; qrCategoria.SQL.Text := 'select codigo,descricao from grupos order by 2'; qrCategoria.Open; cbCategoria.Properties.ListColumns[0].Caption := 'Grupos'; Self.Caption := 'Permissões para grupos de usuários'; FTabela := 'acoes_grupo'; FCampo := 'id_grupo'; qrAcao.Close; qrAcao.SQL.Clear; qrAcao.SQL.Add('select id,id_menu,descricao,'); qrAcao.SQL.Add(' if(isnull(id_acao),"N","S")permissao'); qrAcao.SQL.Add('from acoes a'); qrAcao.SQL.Add(' left join acoes_grupo ag on a.id=ag.id_acao and tipo="A" and id_grupo=:pID'); end; tpUsuario: begin lbCategoria.Caption := 'Selecione um usuário:'; lbDescricao.Caption := 'Configure abaixo as operações permitidas para o usuário:'; qrCategoria.Close; qrCategoria.SQL.Text := 'select codigo,nome_completo as descricao from usuarios where ativo="S" order by 2'; qrCategoria.Open; cbCategoria.Properties.ListColumns[0].Caption := 'Usuários'; Self.Caption := 'Permissões para usuários'; FTabela := 'acoes_usuario'; FCampo := 'id_usuario'; qrAcao.Close; qrAcao.SQL.Clear; qrAcao.SQL.Add('select id,id_menu,descricao,'); qrAcao.SQL.Add(' if(isnull(id_acao),"N","S")permissao'); qrAcao.SQL.Add('from acoes a'); qrAcao.SQL.Add(' left join acoes_usuario ag on a.id=ag.id_acao and tipo="A" and id_usuario=:pID'); end; end; end; procedure TfrmPermissoesAcoes.FormCreate(Sender: TObject); begin TipoPermissao := tpGrupo; qrMenus.Open; cdsAcao.CreateDataSet; end; procedure TfrmPermissoesAcoes.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmPermissoesAcoes.FormDestroy(Sender: TObject); begin if qrCategoria.Active then qrCategoria.Close; if qrMenus.Active then qrMenus.Close; end; procedure TfrmPermissoesAcoes.tvMenusGetImageIndex(Sender: TObject; Node: TTreeNode); var idxImagem: integer; begin idxImagem := -1; if Node.Parent = nil then idxImagem := 0 else idxImagem := 1; if not Node.HasChildren then idxImagem := 6; Node.ImageIndex := idxImagem; Node.SelectedIndex := idxImagem; Node.StateIndex := idxImagem; end; procedure TfrmPermissoesAcoes.tvMenusGetSelectedIndex(Sender: TObject; Node: TTreeNode); begin if not Node.HasChildren then Node.SelectedIndex := 7; end; procedure TfrmPermissoesAcoes.GravaAcao(const AID_User: Integer); var qrAcoesGrava: TZReadOnlyQuery; begin qrAcoesGrava := TZReadOnlyQuery.Create(nil); dsMenus.OnDataChange := nil; try with qrAcoesGrava do begin Connection := dmPrincipal.Database; SQL.Text := 'DELETE FROM ' + FTabela + ' WHERE ' + FCampo + '=:pID'; ParamByName('pID').AsInteger := AID_User; ExecSQL; SQL.Text := 'INSERT INTO ' + FTabela + ' VALUES(:pID_Grupo,:pID_Acao,"A")'; ParamByName('pID_Grupo').AsInteger := AID_User; cdsAcao.Filtered := False; cdsAcao.Filter := 'permissao=' + QuotedStr('S'); cdsAcao.Filtered := True; cdsAcao.IndexFieldNames := 'id'; cdsAcao.First; while not cdsAcao.Eof do begin qrMenus.Locate('id', cdsAcaoid_menu.AsInteger, []); VePermissaoMenuPai(tvMenus.Selected, AID_User); ParamByName('pID_Acao').AsInteger := cdsAcaoid.AsInteger; ExecSQL; cdsAcao.Next; end; end; finally FreeAndNil(qrAcoesGrava); dsMenus.OnDataChange := dsMenusDataChange; end; end; procedure TfrmPermissoesAcoes.VeAcao(const AID_User: Integer); begin cdsAcao.EmptyDataSet; qrAcao.Close; qrAcao.ParamByName('pID').AsInteger := AID_User; qrAcao.Open; try if qrAcao.IsEmpty then Exit; qrAcao.First; while not qrAcao.Eof do begin cdsAcao.Append; cdsAcaoid.AsInteger := qrAcao.fieldbyname('id').AsInteger; cdsAcaoid_menu.AsInteger := qrAcao.fieldbyname('id_menu').AsInteger; cdsAcaodescricao.AsString := qrAcao.fieldbyname('descricao').AsString; cdsAcaopermissao.AsString := qrAcao.fieldbyname('permissao').AsString; cdsAcao.Post; qrAcao.Next; end; finally qrAcao.Close; end; end; procedure TfrmPermissoesAcoes.VeAcaoMenu(const AID_Menu: Integer); var Item: Integer; strAcao: TString; begin cdsAcao.Filtered := False; cdsAcao.Filter := 'id_menu=' + IntToStr(AID_Menu); cdsAcao.Filtered := True; cdsAcao.IndexFieldNames := 'descricao'; cdsAcao.First; clbAcoes.Clear; while not cdsAcao.Eof do begin strAcao := TString.Create(cdsAcaoid.AsString); Item := clbAcoes.Items.AddObject(cdsAcaodescricao.AsString, strAcao); clbAcoes.Checked[Item] := cdsAcaopermissao.AsString = 'S'; cdsAcao.Next; end; end; procedure TfrmPermissoesAcoes.VeEditaAcao(const AID_Acao: Integer); begin if AID_Acao = 0 then Exit; if cdsAcao.Locate('id', AID_Acao, []) then begin cdsAcao.Edit; if clbAcoes.Checked[clbAcoes.ItemIndex] then cdsAcaopermissao.AsString := 'S' else cdsAcaopermissao.AsString := 'N'; cdsAcao.Post; end; end; procedure TfrmPermissoesAcoes.VeEdicao(AEditar: Boolean); begin tvMenus.Enabled := AEditar; tvMenus.AutoExpand := AEditar; clbAcoes.Enabled := AEditar; cbCategoria.Enabled := not AEditar; btnAlterar.Enabled := not AEditar; btnGravar.Enabled := AEditar; btnCancelar.Enabled := AEditar; btnFechar.Enabled := not AEditar; end; procedure TfrmPermissoesAcoes.VePermissaoMenuPai(const no: TTreeNode; AID_User: Integer); var ID: Integer; begin //Sleep(100); tvMenus.Selected := no; ID := qrMenus.FieldByName('id').AsInteger; if not PermissaoPaiExiste(AID_User, ID) then GravaPermissaoPai(AID_User, ID); if Assigned(no.Parent) then VePermissaoMenuPai(no.Parent, AID_User); end; procedure TfrmPermissoesAcoes.GravaPermissaoPai(aID_User, aID: Integer); begin with TZReadOnlyQuery.Create(nil) do begin Connection := dmPrincipal.Database; try SQL.Text := 'INSERT INTO ' + FTabela + ' VALUES(:pID_Grupo,:pID_Acao,"M")'; ParamByName('pID_Grupo').AsInteger := AID_User; ParamByName('pID_Acao').AsInteger := aID; ExecSQL; finally Close; Free; end; end; end; function TfrmPermissoesAcoes.PermissaoPaiExiste(aID_User, aID: Integer): Boolean; begin with TZReadOnlyQuery.Create(nil) do begin Connection := dmPrincipal.Database; try SQL.Text := 'select count(*) from ' + FTabela + ' where ' + FCampo + '=:pID_User and id_acao=:pID and tipo="M"'; ParamByName('pID_User').AsInteger := aID_User; ParamByName('pID').AsInteger := aID; Open; Result := Fields[0].AsInteger > 0; finally Close; Free; end; end; end; { TString } constructor TString.Create(const AStr: string); begin inherited Create; vStr := AStr; end; procedure TfrmPermissoesAcoes.clbAcoesClick(Sender: TObject); begin VeEditaAcao(StrToIntDef(TString(clbAcoes.Items.Objects[clbAcoes.ItemIndex]).Texto, 0)); end; procedure TfrmPermissoesAcoes.btnGravarClick(Sender: TObject); begin GravaAcao(cbCategoria.EditValue); btnCancelar.Click; end; procedure TfrmPermissoesAcoes.btnFecharClick(Sender: TObject); begin Close; end; procedure TfrmPermissoesAcoes.btnAlterarClick(Sender: TObject); begin if cbCategoria.Text = EmptyStr then begin MessageBox(handle, PChar(Copy(lbCategoria.Caption, 1, Length(lbCategoria.Caption) - 1) + '!'), 'Erro', mb_ok + mb_IconError); if cbCategoria.CanFocus then cbCategoria.SetFocus; keybd_event(VK_F4, 0, 0, 0); Exit; end; qrMenus.First; VeAcao(cbCategoria.EditValue); VeEdicao(True); tvMenus.SetFocus; end; procedure TfrmPermissoesAcoes.btnCancelarClick(Sender: TObject); begin VeAcao(-1); qrMenus.First; VeAcaoMenu(qrMenus.fieldbyname('id').AsInteger); VeEdicao(False); cbCategoria.SetFocus; end; procedure TfrmPermissoesAcoes.dsMenusDataChange(Sender: TObject; Field: TField); begin if btnGravar.Enabled then VeAcaoMenu(qrMenus.fieldbyname('id').AsInteger); end; end.
unit DW.Android.Service; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // RTL System.Android.Service; type TLocalServiceConnection = class(System.Android.Service.TLocalServiceConnection) public class procedure StartForegroundService(const AServiceName: string); static; end; implementation uses // RTL System.SysUtils, // Android Androidapi.Helpers, AndroidApi.JNI.GraphicsContentViewText, // DW DW.Consts.Android, DW.Androidapi.JNI.ContextWrapper; { TLocalServiceConnection } class procedure TLocalServiceConnection.StartForegroundService(const AServiceName: string); var LIntent: JIntent; LService: string; begin if TOSVersion.Check(8) then begin LIntent := TJIntent.Create; LService := AServiceName; if not LService.StartsWith(cEMBTJavaServicePrefix) then LService := cEMBTJavaServicePrefix + LService; LIntent.setClassName(TAndroidHelper.Context.getPackageName(), TAndroidHelper.StringToJString(LService)); TJContextWrapper.Wrap(System.JavaContext).startForegroundService(LIntent); end else StartService(AServiceName); end; end.
unit K538560814; {* [Requestlink:538560814] } // Модуль: "w:\common\components\rtl\Garant\Daily\K538560814.pas" // Стереотип: "TestCase" // Элемент модели: "K538560814" MUID: (53881E4003E3) // Имя типа: "TK538560814" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK538560814 = class(TRTFtoEVDWriterTest) {* [Requestlink:538560814] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK538560814 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *53881E4003E3impl_uses* //#UC END# *53881E4003E3impl_uses* ; function TK538560814.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.10'; end;//TK538560814.GetFolder function TK538560814.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '53881E4003E3'; end;//TK538560814.GetModelElementGUID initialization TestFramework.RegisterTest(TK538560814.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
(* * TASK #1 - Sum Bitwise Operator * * GUEST LANGUAGE: THIS IS THE PASCAL VERSION OF ch-1a.pl, suitable for * the Free Pascal compiler. *) uses sysutils; const maxints = 256; type intarray = array [0..maxints-1] of integer; var debug : boolean; (* process_args( nel, v ); * Process command line arguments, * specifically process the -d flag, * set nel to the number of remaining arguments, * check that all those remaining arguments are +ve numbers, * copy remaining args to a new integer array v. *) procedure process_args( var nel : integer; var v : intarray ); (* note: paramStr(i)); for i in 1 to paramCount() *) var nparams : integer; arg : integer; i : integer; p : string; begin nparams := paramCount(); arg := 1; if (nparams>0) and SameText( paramStr(arg), '-d' ) then begin debug := true; arg := 2; end; nel := 1+nparams-arg; if nel < 2 then begin writeln( stderr, 'Usage: sum-bitwise-pairs [-d] list of +ve numbers' ); halt; end; if nel > maxints then begin writeln( stderr, 'sum-bitwise-pairs: too many numbers (max ', maxints, ')' ); halt; end; if debug then begin writeln( 'debug: arg', arg, ', nparams=', nparams, ', nel=', nel ); end; // elements are in argv[arg..nparams], copy them to v[] // check that all remaining arguments are +ve integers, // and then copy them to v[] for i := arg to nparams do begin p := paramStr(i); if (p[1] < '0') or (p[1] > '9') then begin writeln( stderr, 'sum-bitwise-pairs: arg ', i, ' (', p, ') is not a +ve number' ); halt; end; v[i-arg] := StrToInt( p ); end; end; procedure main; var nel : integer; v : intarray; sum : integer; i, j : integer; a, b : integer; r : integer; begin debug := false; process_args( nel, v ); sum := 0; for i := 0 to nel-2 do begin for j:= i+1 to nel-1 do begin a := v[i]; b := v[j]; r := a and b; if debug then begin writeln( 'debug: i=', i, ', j=', j, ', a=', a, ', b=', b, ', a&b=', r ); end; sum := sum + r; end; end; writeln( sum ); end; begin main; end.
object FormViewOptions: TFormViewOptions Left = 340 Top = 206 ActiveControl = edText BorderStyle = bsDialog Caption = 'Viewer settings' ClientHeight = 279 ClientWidth = 481 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object btnOk: TButton Left = 304 Top = 248 Width = 81 Height = 25 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 3 end object btnCancel: TButton Left = 392 Top = 248 Width = 81 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 4 end object boxExt: TGroupBox Left = 8 Top = 4 Width = 465 Height = 117 Caption = 'File extensions' TabOrder = 0 object Label1: TLabel Left = 8 Top = 20 Width = 26 Height = 13 Caption = '&Text:' FocusControl = edText end object Label2: TLabel Left = 8 Top = 44 Width = 39 Height = 13 Caption = '&Images:' FocusControl = edImages end object Label3: TLabel Left = 8 Top = 68 Width = 32 Height = 13 Caption = '&Media:' FocusControl = edMedia end object Label4: TLabel Left = 8 Top = 92 Width = 44 Height = 13 Caption = 'I&nternet:' FocusControl = edInternet end object edText: TEdit Left = 88 Top = 16 Width = 341 Height = 21 TabOrder = 0 end object edImages: TEdit Left = 88 Top = 40 Width = 341 Height = 21 TabOrder = 2 end object edMedia: TEdit Left = 88 Top = 64 Width = 341 Height = 21 TabOrder = 3 end object edInternet: TEdit Left = 88 Top = 88 Width = 341 Height = 21 TabOrder = 4 end object btnTextOptions: TButton Left = 434 Top = 16 Width = 25 Height = 21 Caption = '...' TabOrder = 1 OnClick = btnTextOptionsClick end end object boxText: TGroupBox Left = 8 Top = 124 Width = 201 Height = 149 Caption = 'Text modes' TabOrder = 1 object labTextFont: TLabel Left = 88 Top = 21 Width = 22 Height = 13 Caption = 'Font' end object Label5: TLabel Left = 40 Top = 104 Width = 78 Height = 13 Caption = 'Fi&xed text width' FocusControl = edTextWidth end object Label6: TLabel Left = 40 Top = 128 Width = 135 Height = 13 Caption = 'Search &result: lines from top' FocusControl = edTextIndent end object btnTextColor: TButton Left = 8 Top = 46 Width = 73 Height = 25 Caption = '&Color...' TabOrder = 1 OnClick = btnTextColorClick end object btnTextFont: TButton Left = 8 Top = 16 Width = 73 Height = 25 Caption = '&Font...' TabOrder = 0 OnClick = btnTextFontClick end object edTextWidth: TEdit Left = 8 Top = 100 Width = 25 Height = 21 TabOrder = 3 end object edTextIndent: TEdit Left = 8 Top = 124 Width = 25 Height = 21 TabOrder = 4 end object chkTextWidthFit: TCheckBox Left = 8 Top = 78 Width = 185 Height = 17 Caption = '&Auto-fit text width' TabOrder = 2 OnClick = chkTextWidthFitClick end end object boxMedia: TGroupBox Left = 216 Top = 124 Width = 257 Height = 61 Caption = 'Multimedia mode' TabOrder = 2 object chkMediaMCI: TRadioButton Left = 8 Top = 16 Width = 241 Height = 17 Caption = 'Use &standard media interface' TabOrder = 0 end object chkMediaWMP64: TRadioButton Left = 8 Top = 34 Width = 241 Height = 17 Caption = 'Use &Windows Media Player 6.4 interface' TabOrder = 1 end end object FontDialog1: TFontDialog Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Shell Dlg' Font.Style = [] MinFontSize = 0 MaxFontSize = 0 Left = 288 Top = 4 end object ColorDialog1: TColorDialog Ctl3D = True Left = 312 Top = 4 end end
// ********************************************************************** // // Copyright (c) 2000 - 2003 MT Tools. // // All Rights Reserved // // MT_DORB is based in part on the product DORB, // written by Shadrin Victor // // See Readme.txt for contact information // // ********************************************************************** unit mtdebug; interface {$I dorb.inc} uses {$IFDEF MSWINDOWS}Windows{$ENDIF}{$IFDEF LINUX}Libc{$ENDIF},SysUtils, Classes, mtdebug_int, osthread, orbtypes; {$IFNDEF USELIB} type TLogger = class(TInterfacedObject, ILogger) private FMutex: TMutex; FInfo: THandle; FError: THandle; FMsgTypes: TMessageTypes; procedure InternalMessage(const AHandle: THandle; const Msg: AnsiString); protected { ILogger } function IsLogged(const MsgType: mtdebug_int.TMessageType): boolean; procedure Info(const Msg: AnsiString); procedure Error(const Msg: AnsiString); procedure Warning(const Msg: AnsiString); procedure Trace(const Category, Msg: AnsiString); public constructor Create(const MsgTypes: TMessageTypes = []; const InfoFile: string = ''; const ErrorFile: string = ''); destructor Destroy; override; end; procedure CreateLogger(const MsgTypes: TMessageTypes; const InfoFile: string; const ErrorFile: string); procedure DestroyLogger; function MTDORBLogger: ILogger; procedure Debug(const Msg: AnsiString); function CallStackTextualRepresentation(): string; {$ELSE} procedure CreateLogger(const MsgTypes: TMessageTypes; const InfoFile: string; const ErrorFile: string); external MTDORB_Library_Name; function MTDORBLogger: ILogger; external MTDORB_Library_Name; procedure Debug(const Msg: AnsiString); external MTDORB_Library_Name; function CallStackTextualRepresentation(): string; external MTDORB_Library_Name; {$ENDIF} {$IFNDEF USELIB} implementation {$IFDEF USE_JCL}uses JclDebug;{$ENDIF} var loggerVar: ILogger; function CallStackTextualRepresentation(): string; {$IFDEF USE_JCL} var strs: TStrings; {$ENDIF} begin {$IFDEF USE_JCL} strs := TStringList.Create; try JclCreateStackList(true, 6, nil).AddToStrings(strs, true); result := strs.Text; finally strs.Free; end; { try/finally } {$ENDIF} end; procedure CreateLogger(const MsgTypes: TMessageTypes; const InfoFile: string; const ErrorFile: string); begin loggerVar := TLogger.Create(MsgTypes, InfoFile, ErrorFile); end; //WJ: logger should be cleared after orb shutdown procedure DestroyLogger; begin loggerVar := nil; end; function MTDORBLogger: ILogger; begin result := loggerVar; end; {$IFDEF MSWINDOWS} var x: Integer; {$ENDIF} procedure Debug(const Msg: AnsiString); begin {$IFDEF MSWINDOWS} OutputDebugString(PChar(Format('%d %s Thread=%x%s', [InterlockedIncrement(x), Msg, GetCurrentThreadID, #10 + #13]))); {$ENDIF} end; { TLogger } constructor TLogger.Create(const MsgTypes: TMessageTypes; const InfoFile, ErrorFile: string); begin inherited Create; FMsgTypes := MsgTypes; FMutex := TMutex.Create; if InfoFile <> '' then begin if FileExists(InfoFile) then FInfo := FileOpen(InfoFile, fmOpenWrite or fmShareDenyNone) else FInfo := FileCreate(InfoFile); FileSeek(FInfo, 0, 2); end else {$IFDEF MSWINDOWS} FInfo := GetStdHandle(STD_OUTPUT_HANDLE); {$ENDIF} {$IFDEF LINUX} FInfo := STDOUT_FILENO; {$ENDIF} if ErrorFile <> '' then begin //WJ: if user wants all log in one file - open it only once if UpperCase(ErrorFile) = UpperCase(InfoFile) then FError := FInfo else if FileExists(ErrorFile) then FError := FileOpen(ErrorFile, fmOpenWrite or fmShareDenyNone) else FError := FileCreate(ErrorFile); FileSeek(FError, 0, 2); end else {$IFDEF MSWINDOWS} FError := GetStdHandle(STD_ERROR_HANDLE); {$ENDIF} {$IFDEF LINUX} FError := STDERR_FILENO; {$ENDIF} end; destructor TLogger.Destroy; begin //WJ: set message on closing log Info('Info logger is closed'); Error('Error logger is closed'); {$IFDEF MSWINDOWS} CloseHandle(FError); {$ENDIF} {$IFDEF LINUX} __close(FError); {$ENDIF} if FError <> FInfo then begin {$IFDEF MSWINDOWS} CloseHandle(FInfo); {$ENDIF} {$IFDEF LINUX} __close(FInfo); {$ENDIF} end; FreeAndNil(FMutex); inherited; end; procedure TLogger.Error(const Msg: AnsiString); begin if mtError in FMsgTypes then InternalMessage(FError, Msg); end; procedure TLogger.Info(const Msg: AnsiString); begin if mtInfo in FMsgTypes then InternalMessage(FInfo, Msg); end; procedure TLogger.InternalMessage(const AHandle: THandle; const Msg: AnsiString); var sync: ISynchronized; intMsg: string; begin intMsg := Format('[%s] %s%s', [FormatDateTime('ddd mmm dd hh:nn:ss.zzz yyyy', Now), Msg, #13{$IFDEF MSWINDOWS} + #10{$ENDIF}]); sync := TSynchronized.Create(FMutex); FileWrite(AHandle, intMsg, Length(intMsg)); sync := nil; end; function TLogger.IsLogged(const MsgType: mtdebug_int.TMessageType): boolean; begin result := MsgType in FMsgTypes; end; procedure TLogger.Trace(const Category, Msg: AnsiString); begin if mtTrace in FMsgTypes then InternalMessage(FInfo, AnsiString(Format('%s: %s', [Category, Msg]))); end; procedure TLogger.Warning(const Msg: AnsiString); begin if mtWarning in FMsgTypes then InternalMessage(FInfo, Msg); end; {$IFDEF LIBRARY} exports Debug, CreateLogger, MTDORBLogger, CallStackTextualRepresentation; {$ENDIF} {$ELSE} implementation {$ENDIF} end.
unit MFichas.Model.Venda.Interfaces; interface uses MFichas.Model.Item.Interfaces, MFichas.Model.Caixa.Interfaces, MFichas.Model.Entidade.VENDA, MFichas.Model.Pagamento.Interfaces, ORMBR.Container.ObjectSet.Interfaces; type iModelVenda = interface; iModelVendaMetodos = interface; iModelVendaMetodosAbrir = interface; iModelVendaMetodosPagar = interface; iModelVendaMetodosFinalizar = interface; iModelVenda = interface ['{CB5AE15E-1BC5-4CF8-B5C4-CD5F77DBCC4D}'] function SetState(AState: iModelVendaMetodos): iModelVenda; function Metodos : iModelVendaMetodos; function Entidade(AEntidade: TVENDA): iModelVenda; overload; function Entidade : TVENDA; overload; function Caixa : iModelCaixa; function Item : iModelItem; function Pagamento : iModelPagamento; function DAO : iContainerObjectSet<TVENDA>; end; iModelVendaMetodos = interface ['{07EB681F-CEF2-486B-A9E9-910A7DA7F507}'] function Abrir : iModelVendaMetodosAbrir; function Pagar : iModelVendaMetodosPagar; function Finalizar: iModelVendaMetodosFinalizar; function &End : iModelVenda; end; iModelVendaMetodosAbrir = interface ['{FD1A0630-4CA0-4A2D-90CD-2B24FC1483F3}'] function Executar: iModelVendaMetodosAbrir; function &End : iModelVendaMetodos; end; iModelVendaMetodosPagar = interface ['{75E0001E-4A9C-49E2-AB56-FC9349AE20A0}'] function Executar: iModelVendaMetodosPagar; function &End : iModelVendaMetodos; end; iModelVendaMetodosFinalizar = interface ['{34E97BB4-A513-4F5C-BEF7-1636457DE4AE}'] function Executar: iModelVendaMetodosFinalizar; function &End : iModelVendaMetodos; end; implementation end.
unit ClientSocket; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SocketComp, StdCtrls; type TClientForm = class( TForm ) SendBuffer: TEdit; ReceiveBuffer: TEdit; procedure ClientSocketRead( Sender : TObject; Socket : TCustomWinSocket ); procedure ClientSocketError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); procedure SendBufferKeyDown( Sender : TObject; var Key : Word;Shift : TShiftState ); procedure FormCreate( Sender : TObject ); procedure FormDestroy( Sender : TObject ); private { Private declarations } ClientSocket : TClientSocket; fPacketQueue : TList; public { Public declarations } end; var ClientForm: TClientForm; implementation {$R *.DFM} uses WinSock; procedure TClientForm.ClientSocketRead( Sender : TObject; Socket : TCustomWinSocket ); begin try ReceiveBuffer.Text := Socket.ReceiveText except on ESocketError do ReceiveBuffer.Text := 'Error while reading from socket' else ReceiveBuffer.Text := 'An unexpected error has ocurred' end end; procedure TClientForm.ClientSocketError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); begin ErrorCode := 0; case ErrorEvent of eeGeneral: Application.MessageBox( 'General error', 'TCP/IP Client', MB_OK ); eeSend: Application.MessageBox( 'Error writing to socket', 'TCP/IP Client', MB_OK ); eeReceive: Application.MessageBox( 'Error reading from socket', 'TCP/IP Client', MB_OK ); eeConnect: Application.MessageBox( 'Error establishing connection', 'TCP/IP Client', MB_OK ); eeDisconnect: Application.MessageBox( 'Error closing socket', 'TCP/IP Client', MB_OK ); eeAccept: Application.MessageBox( 'Unexpected error', 'TCP/IP Client', MB_OK ) end end; procedure TClientForm.SendBufferKeyDown( Sender : TObject; var Key : Word; Shift : TShiftState ); var str : string; begin SetLength(str, 1024*1024 div 10); FillChar(str[1], 1024*1024 div 10, 65); if Key = VK_RETURN then with ClientSocket do try if SendBuffer.Text <> '' then Socket.SendText( {SendBuffer.Text} str ); except on ESocketError do ReceiveBuffer.Text := 'Error while writing to socket' else ReceiveBuffer.Text := 'An unexpected error has ocurred' end end; procedure TClientForm.FormCreate(Sender: TObject); begin ClientSocket := TClientSocket.Create( ClientForm ); with ClientSocket do begin Address := InputBox( 'TCP/IP Client', 'Server address:', '127.0.0.1' ); try Port := StrToInt( InputBox( 'TCP/IP Client', 'Server port:', '5000' ) ); except Port := 5000 end; OnRead := ClientSocketRead; OnError := ClientSocketError; ClientType := ctNonBlocking; Open end; fPacketQueue := TList.Create end; procedure TClientForm.FormDestroy(Sender: TObject); begin ClientSocket.Free; fPacketQueue.Free end; end.
unit eInterestSimulator.Model.PagamentoUnico.Calculadora; interface uses eInterestSimulator.Model.Interfaces, System.Generics.Collections, eInterestSimulator.Controller.Observer.Interfaces, eInterestSimulator.Model.Interfaces.Calculadora; type TModelPagamentoUnicoCalculadora = class(TInterfacedObject, iCalculadora) private FSimulador: iSimulador; FResultados: TList<iResultado>; FObserverResultado : iSubjectResultado; function Resultados: TList<iResultado>; function Calcular: iCalculadora; function Simulador: iSimulador; overload; function Simulador(Value: iSimulador): iCalculadora; overload; public constructor Create; destructor Destroy; override; class function New: iCalculadora; function ObserverResultado(Value : iSubjectResultado): iCalculadora; overload; function ObserverResultado: iSubjectResultado; overload; end; implementation uses eInterestSimulator.Model.Resultado.Factory, System.SysUtils; { TModelPagamentoUnicoCalculadora } function TModelPagamentoUnicoCalculadora.Resultados: TList<iResultado>; begin Result := FResultados; end; function TModelPagamentoUnicoCalculadora.Calcular: iCalculadora; var I: Integer; FResultado: iResultado; FValorAcumulado, FJuros, FValorAmortizacao, FValorPagamento: Real; const cCEM = 100; begin Result := Self; with FSimulador do begin FValorAcumulado := Capital; FJuros := 0; FValorAmortizacao := 0; FValorPagamento := 0; for I := 0 to TotalParcelas do begin if I = TotalParcelas then begin FValorAmortizacao := Capital; FValorPagamento := FValorAcumulado; FValorAcumulado := 0; end; FResultado := TModelResultadoFactory.New.PagamentoUnico.NumeroParcela(I) .ValorJuros(FJuros).ValorAmortizacao(FValorAmortizacao) .ValorPagamento(FValorPagamento).ValorSaldo(FValorAcumulado); FResultados.Add(FResultado); FJuros := (FValorAcumulado * TaxaJuros / cCEM); FValorAcumulado := (FValorAcumulado + FJuros); end; end; FObserverResultado.Notify(FResultados); end; constructor TModelPagamentoUnicoCalculadora.Create; begin FResultados := TList<iResultado>.Create; end; destructor TModelPagamentoUnicoCalculadora.Destroy; begin FreeAndNil(FResultados); inherited; end; class function TModelPagamentoUnicoCalculadora.New: iCalculadora; begin Result := Self.Create; end; function TModelPagamentoUnicoCalculadora.ObserverResultado: iSubjectResultado; begin Result := FObserverResultado; end; function TModelPagamentoUnicoCalculadora.ObserverResultado( Value: iSubjectResultado): iCalculadora; begin Result := Self; FObserverResultado := Value; end; function TModelPagamentoUnicoCalculadora.Simulador: iSimulador; begin Result := FSimulador; end; function TModelPagamentoUnicoCalculadora.Simulador(Value: iSimulador) : iCalculadora; begin Result := Self; FSimulador := Value; end; end.
unit WinUtils; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, Messages, SysUtils; // Message Queue Inspection ------------------------------------------------------ function WindowHasMessageWaiting( WinHandle : HWND ) : boolean; const // See QS_XXX flags in GetQueueStatus QS_USERINPUT = QS_KEY or QS_MOUSEBUTTON or QS_HOTKEY; QS_IMPORTANT = QS_USERINPUT or QS_POSTMESSAGE; function ThreadHasInputWaiting : boolean; function ThreadHasMessageWaiting : boolean; function ThreadHasImportantMessageWaiting : boolean; function ThreadHasTheseMessagesWaiting( Mask : integer ) : boolean; // Mask = QS_XXX flags // Window searching ----------------------------------------------------------------- function GetWindowOfClass( const ClassName : string ) : HWND; function GetWindowOfCaption( const Caption : string ) : HWND; // Window info ----------------------------------------------------------------- function GetWindowCaption( WinHandle : HWND ) : string; function GetWindowClass( WinHandle : HWND ) : string; function GetWindowInstance( WinHandle : HWND ) : HMODULE; function GetWindowID( WinHandle : HWND ) : integer; // Window styles ---------------------------------------------------------------- procedure ExcludeWindowStyle( WinHandle : HWND; NewStyle : integer ); procedure IncludeWindowStyle( WinHandle : HWND; NewStyle : integer ); procedure SetWindowStyle( WinHandle : HWND; NewStyle : integer ); function GetWindowStyle( WinHandle : HWND ) : integer; procedure ExcludeWindowExStyle( WinHandle : HWND; NewExStyle : integer ); procedure IncludeWindowExStyle( WinHandle : HWND; NewExStyle : integer ); procedure SetWindowExStyle( WinHandle : HWND; NewExStyle : integer ); function GetWindowExStyle( WinHandle : HWND ) : integer; // Window list ----------------------------------------------------------------- function GetWindowOwner( WinHandle : HWND ) : HWND; function GetFirstChild( WinHandle : HWND ) : HWND; function GetFirstSibling( WinHandle : HWND ) : HWND; function GetLastSibling( WinHandle : HWND ) : HWND; function GetNextSibling( WinHandle : HWND ) : HWND; function GetPrevSibling( WinHandle : HWND ) : HWND; // Window Visuals ----------------------------------------------------------------- procedure SetWindowRedraw( WinHandle : HWND; Redraw : boolean ); // For compatibility with Windowsx.h procedure LockWindowPainting( WinHandle : HWND; Locked : boolean ); // Use this ones instead procedure UnlockPainting( WinHandle : HWND ); function IsMinimized( WinHandle : HWND ) : boolean; function IsMaximized( WinHandle : HWND ) : boolean; function IsRestored( WinHandle : HWND ) : boolean; procedure MaximizeWindow( WinHandle : HWND ); procedure MinimizeWindow( WinHandle : HWND ); procedure RestoreWindow( WinHandle : HWND ); procedure ActivateWindow( WinHandle : HWND ); // Brings window to front, and gives it the focus procedure ShowDontActivateWindow( WinHandle : HWND ); // Only make sure it's visible procedure TopmostWindow( WinHandle : HWND ); // Make window topmost procedure HideWindow( WinHandle : HWND ); procedure ShowWindow( WinHandle : HWND ); procedure UpdateWindowFrame( WinHandle : HWND ); // Repaint window borders & caption procedure SetWindowSizeable( WinHandle : HWND; WinSizeable : boolean ); // Allow/Disable resizing function WindowIsSizeable( WinHandle : HWND) : boolean; function GetRealClientRect( WinHandle : HWND ) : TRect; function WindowIsDropTarget( WinHandle : HWND) : boolean; // True if this window accepts files dropping // Window subclassing ----------------------------------------------------------------- type EWndProcCannotBeRestored = class( Exception ); function SubclassWindow( WinHandle : integer; NewWndProc : pointer ) : pointer; // For compatibility with Windowsx.h function CurrentWndProc( WinHandle : HWND ) : pointer; function ChangeWndProc( WinHandle : HWND; NewWndProc : pointer ) : integer; function RestoreWndProc( WinHandle : HWND; Data : integer ) : pointer; function PrevWndProc( Data : dword ) : pointer; implementation // Window Messages ----------------------------------------------------------------- function WindowHasMessageWaiting( WinHandle : HWND ) : boolean; var Msg : TMsg; begin Result := PeekMessage( Msg, WinHandle, 0, 0, PM_NOREMOVE ); end; function ThreadHasInputWaiting : boolean; begin Result := GetInputState; end; function ThreadHasMessageWaiting : boolean; begin Result := GetQueueStatus( QS_ALLINPUT ) <> 0; end; function ThreadHasImportantMessageWaiting : boolean; begin Result := GetQueueStatus( QS_IMPORTANT ) <> 0; end; function ThreadHasTheseMessagesWaiting( Mask : integer ) : boolean; begin Result := GetQueueStatus( Mask ) <> 0; end; // Window info ----------------------------------------------------------------- function GetWindowCaption( WinHandle : HWND ) : string; begin SetLength( Result, MAX_PATH ); SetLength( Result, GetWindowText( WinHandle, pchar( Result ), length( Result ) ) ); end; function GetWindowClass( WinHandle : HWND ) : string; begin SetLength( Result, MAX_PATH ); SetLength( Result, GetClassName( WinHandle, pchar( Result ), length( Result ) ) ); end; function GetWindowStyle( WinHandle : HWND ) : integer; begin Result := GetWindowLong( WinHandle, GWL_STYLE ); end; procedure SetWindowStyle( WinHandle : HWND; NewStyle : integer ); begin SetWindowLong( WinHandle, GWL_STYLE, NewStyle ); end; procedure IncludeWindowStyle( WinHandle : HWND; NewStyle : integer ); begin NewStyle := GetWindowStyle( WinHandle ) or NewStyle; SetWindowLong( WinHandle, GWL_STYLE, NewStyle ); end; procedure ExcludeWindowStyle( WinHandle : HWND; NewStyle : integer ); begin NewStyle := GetWindowStyle( WinHandle ) and (not NewStyle); SetWindowLong( WinHandle, GWL_STYLE, NewStyle ); end; function GetWindowExStyle( WinHandle : HWND ) : integer; begin Result := GetWindowLong( WinHandle, GWL_EXSTYLE ); end; procedure SetWindowExStyle( WinHandle : HWND; NewExStyle : integer ); begin SetWindowLong( WinHandle, GWL_EXSTYLE, NewExStyle ); end; procedure IncludeWindowExStyle( WinHandle : HWND; NewExStyle : integer ); begin NewExStyle := GetWindowExStyle( WinHandle ) or NewExStyle; SetWindowLong( WinHandle, GWL_EXSTYLE, NewExStyle ); end; procedure ExcludeWindowExStyle( WinHandle : HWND; NewExStyle : integer ); begin NewExStyle := GetWindowExStyle( WinHandle ) and (not NewExStyle); SetWindowLong( WinHandle, GWL_EXSTYLE, NewExStyle ); end; function GetWindowOwner( WinHandle : HWND ) : HWND; begin Result := GetWindow( GW_OWNER, WinHandle ); end; function GetWindowInstance( WinHandle : HWND ) : HMODULE; begin Result := GetWindowLong( WinHandle, GWL_HINSTANCE); end; function GetFirstChild( WinHandle : HWND ) : HWND; begin Result := GetTopWindow( WinHandle ); end; function GetFirstSibling( WinHandle : HWND ) : HWND; begin Result := GetWindow( WinHandle, GW_HWNDFIRST ); end; function GetLastSibling( WinHandle : HWND ) : HWND; begin Result := GetWindow( WinHandle, GW_HWNDLAST ); end; function GetNextSibling( WinHandle : HWND ) : HWND; begin Result := GetWindow( WinHandle, GW_HWNDNEXT ); end; function GetPrevSibling( WinHandle : HWND ) : HWND; begin Result := GetWindow( WinHandle, GW_HWNDPREV ); end; function GetWindowID( WinHandle : HWND ) : integer; begin Result := GetDlgCtrlID( WinHandle ); end; // Window searching ----------------------------------------------------------------- function GetWindowOfCaption( const Caption : string ) : HWND; begin Result := FindWindow( nil, pchar(Caption) ); end; function GetWindowOfClass( const ClassName : string ) : HWND; begin Result := FindWindow( pchar(ClassName), nil ); end; // Window Visuals ----------------------------------------------------------------- procedure SetWindowRedraw( WinHandle : HWND; Redraw : boolean ); begin SendMessage( WinHandle, WM_SETREDRAW, WPARAM( Redraw ), 0 ); end; procedure LockWindowPainting( WinHandle : HWND; Locked : boolean ); begin SendMessage( WinHandle, WM_SETREDRAW, WPARAM( not Locked ), 0 ); end; procedure UnlockPainting( WinHandle : HWND ); begin LockWindowPainting( WinHandle, false ); InvalidateRect( WinHandle, nil, false ); end; function IsMinimized( WinHandle : HWND ) : boolean; begin Result := IsIconic( WinHandle ); end; function IsMaximized( WinHandle : HWND ) : boolean; begin Result := IsZoomed( WinHandle ); end; function IsRestored( WinHandle : HWND ) : boolean; begin Result := GetWindowStyle( WinHandle ) and ( WS_MINIMIZE or WS_MAXIMIZE ) = 0; end; procedure MaximizeWindow( WinHandle : HWND ); begin Windows.ShowWindow( WinHandle, SW_MAXIMIZE ); end; procedure MinimizeWindow( WinHandle : HWND ); begin Windows.ShowWindow( WinHandle, SW_MINIMIZE ); end; procedure RestoreWindow( WinHandle : HWND ); begin Windows.ShowWindow( WinHandle, SW_RESTORE ); end; procedure HideWindow( WinHandle : HWND ); begin Windows.ShowWindow( WinHandle, SW_HIDE ); end; procedure ShowWindow( WinHandle : HWND ); begin Windows.ShowWindow( WinHandle, SW_SHOWNORMAL ); end; procedure ActivateWindow( WinHandle : HWND ); begin Windows.ShowWindow( WinHandle, SW_SHOWNORMAL ); SetForegroundWindow( WinHandle ); end; procedure TopmostWindow( WinHandle : HWND ); begin SetWindowPos( WinHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE ); end; procedure ShowDontActivateWindow( WinHandle : HWND ); begin SetWindowPos( WinHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE ); end; procedure UpdateWindowFrame( WinHandle : HWND ); begin SetWindowPos( WinHandle, 0, 0, 0, 0, 0, SWP_FRAMECHANGED or SWP_NOSIZE or SWP_NOMOVE or SWP_NOACTIVATE or SWP_NOZORDER ); end; procedure SetWindowSizeable( WinHandle : HWND; WinSizeable : boolean ); begin if WinSizeable then IncludeWindowStyle( WinHandle, WS_SIZEBOX ) else ExcludeWindowStyle( WinHandle, WS_SIZEBOX ); UpdateWindowFrame( WinHandle ); end; function WindowIsSizeable( WinHandle : HWND ) : boolean; begin Result := ( GetWindowStyle( WinHandle ) and WS_SIZEBOX ) <> 0; end; function GetRealClientRect( WinHandle : HWND ) : TRect; var WinStyle : dword; begin WinStyle := GetWindowStyle( WinHandle ); GetClientRect( WinHandle, Result ); with Result do begin if WinStyle and WS_HSCROLL <> 0 then inc( Bottom, GetSystemMetrics( SM_CYHSCROLL ) ); if WinStyle and WS_VSCROLL <> 0 then inc( Right, GetSystemMetrics( SM_CXVSCROLL ) ); end; end; function WindowIsDropTarget( WinHandle : HWND) : boolean; begin Result := ( GetWindowExStyle( WinHandle ) and WS_EX_ACCEPTFILES ) <> 0; end; function SubclassWindow( WinHandle : integer; NewWndProc : pointer ) : pointer; begin Result := pointer( SetWindowLong( WinHandle, GWL_WNDPROC, longint(NewWndProc) ) ); end; function CurrentWndProc( WinHandle : HWND ) : pointer; begin Result := pointer( GetWindowLong( WinHandle, GWL_WNDPROC ) ); end; // ----------------------------------------------------------------- type PDoubleLinkedNode = ^TDoubleLinkedNode; TDoubleLinkedNode = record Prev, Next : PDoubleLinkedNode; Data : integer; end; function NewNode( aPrev, aNext : pointer; aData : dword ) : PDoubleLinkedNode; begin new( Result ); with Result^ do begin Prev := aPrev; Next := aNext; Data := aData; end; end; procedure FreeNode( Node : PDoubleLinkedNode ); begin with Node^ do begin // Chain Prev & Next if Prev <> nil then Prev.Next := Next; if Next <> nil then Next.Prev := Prev; end; Dispose( Node ); end; function PrevWndProc( Data : dword ) : pointer; var Node : PDoubleLinkedNode absolute Data; begin Result := pointer( Node.Prev.Data ) end; function ChangeWndProc( WinHandle : HWND; NewWndProc : pointer ) : integer; var ListAtom : pchar; List : PDoubleLinkedNode; Node : PDoubleLinkedNode absolute Result; begin ListAtom := pchar( GlobalAddAtom( 'WndProc_List' ) ); List := PDoubleLinkedNode( GetProp( WinHandle, ListAtom ) ); if List = nil then begin // Create list List := NewNode( nil, nil, integer( CurrentWndProc( WinHandle ) ) ); SetProp( WinHandle, ListAtom, dword( List ) ); end; while ( List.Next <> nil ) and (List.Data <> integer( NewWndProc ) ) do List := List.Next; if List.Next = nil then begin Node := NewNode( List, nil, integer( NewWndProc ) ); List.Next := Node; SubclassWindow( WinHandle, NewWndProc ); end; end; function RestoreWndProc( WinHandle : HWND; Data : integer ) : pointer; var ListAtom : pchar; List : PDoubleLinkedNode; Node : PDoubleLinkedNode absolute Data; begin if Data <> 0 then begin ListAtom := pchar( GlobalAddAtom( 'WndProc_List' ) ); List := PDoubleLinkedNode( GetProp( WinHandle, ListAtom ) ); with Node^ do begin if Next = nil then Result := SubclassWindow( WinHandle, pointer( Prev.Data ) ) else Result := CurrentWndProc( WinHandle ); if Prev = List // Free list then begin FreeNode( List ); RemoveProp( WinHandle, ListAtom ); end; end; FreeNode( Node ); end else Result := nil; end; end.
unit uFormDemineur; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, ClassDemineur, FMX.StdCtrls, FMX.Controls.Presentation, System.ImageList, FMX.ImgList, FMX.Objects, FMX.Styles.Objects, FMX.Ani, FMX.Menus, System.Actions, FMX.ActnList; type TFormDemineur = class(TForm) GridLayout: TGridLayout; StyleBook: TStyleBook; LayoutTop: TLayout; TexteMine: TText; imgMine: TImage; TexteTimer: TText; LayoutMain: TLayout; RectButton: TRectangle; btnEasy: TButton; LayoutOptions: TLayout; btnHard: TButton; btnMiddle: TButton; TextePlay: TText; faLayoutOptions: TFloatAnimation; MainMenu: TMainMenu; miNewGame: TMenuItem; ActionList: TActionList; aNouvellePartie: TAction; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormShow(Sender: TObject); procedure btnEasyClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure aNouvellePartieExecute(Sender: TObject); procedure aNouvellePartieUpdate(Sender: TObject); private FDemineur : TDemineur; procedure GetActionGame(GameAction : TGameAction); procedure GetMine(iMine : integer); procedure GetTimer(iSecond : integer); public { Déclarations publiques } end; var FormDemineur: TFormDemineur; implementation uses System.DateUtils; {$R *.fmx} procedure TFormDemineur.aNouvellePartieExecute(Sender: TObject); begin FDemineur.Stop(gaNewParty); end; procedure TFormDemineur.aNouvellePartieUpdate(Sender: TObject); begin aNouvellePartie.Enabled := Assigned(FDemineur); end; procedure TFormDemineur.btnEasyClick(Sender: TObject); begin if Sender = btnMiddle then FDemineur.Level := lvMiddle else begin if Sender = btnHard then FDemineur.Level := lvHard else FDemineur.Level := lvEasy; end; RectButton.Visible := False; FDemineur.Play; end; procedure TFormDemineur.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if CanClose then FreeAndNil(FDemineur); end; procedure TFormDemineur.FormCreate(Sender: TObject); begin FDemineur := nil; RectButton.Visible := True; end; procedure TFormDemineur.FormShow(Sender: TObject); begin if not Assigned(FDemineur) then begin FDemineur := TDemineur.Create(Self, GridLayout); FDemineur.OnGameAction := GetActionGame; FDemineur.OnGetMine := GetMine; FDemineur.OnGetTimer := GetTimer; end; end; procedure TFormDemineur.GetActionGame(GameAction : TGameAction); begin // permet de savoir quand le jeu est gagné, ou perdu if GameAction = gaLose then TextePlay.Text := 'Perdu !' else if GameAction = gaWin then TextePlay.Text := 'Gagné !' else TextePlay.Text := 'Commencer'; faLayoutOptions.StartValue := Self.Height + 1; RectButton.Visible := True; faLayoutOptions.Start; end; procedure TFormDemineur.GetMine(iMine : integer); begin // ajout d'un effet lors de l'affichage du nombre de mines restantes TAnimator.AnimateFloat(TexteMine, 'Font.Size', 35); TAnimator.AnimateFloat(TexteMine, 'Font.Size', 25); TexteMine.Text := iMine.ToString; end; procedure TFormDemineur.GetTimer(iSecond : integer); begin // affichage du chronomètre TexteTimer.Text := iSecond.ToString; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpRandomNumberGenerator; {$I ..\..\Include\CryptoLib.inc} interface uses SysUtils, ClpCryptoLibTypes, ClpIRandomNumberGenerator; resourcestring SUnknownAlgorithm = 'Unknown Random Generation Algorithm Requested'; type TRandomNumberGenerator = class abstract(TInterfacedObject, IRandomNumberGenerator) public class function CreateRNG(): IRandomNumberGenerator; overload; static; class function CreateRNG(const rngName: String): IRandomNumberGenerator; overload; static; procedure GetBytes(const data: TCryptoLibByteArray); virtual; abstract; procedure GetNonZeroBytes(const data: TCryptoLibByteArray); virtual; abstract; end; implementation uses // included here to avoid circular dependency :) ClpPCGRandomNumberGenerator, ClpOSRandomNumberGenerator; { TRandomNumberGenerator } class function TRandomNumberGenerator.CreateRNG: IRandomNumberGenerator; begin result := TOSRandomNumberGenerator.Create(); end; class function TRandomNumberGenerator.CreateRNG(const rngName: String) : IRandomNumberGenerator; begin if CompareText(rngName, 'OSRandomNumberGenerator') = 0 then begin result := TOSRandomNumberGenerator.Create(); end else if CompareText(rngName, 'PCGRandomNumberGenerator') = 0 then begin result := TPCGRandomNumberGenerator.Create(); end else begin raise EArgumentCryptoLibException.CreateRes(@SUnknownAlgorithm); end; end; end.
unit LandClasses; interface uses Windows, Land, Collection, SysUtils, Graphics, IniFiles; const TextureNames : array[TLandClass] of string = ( 'Grass', 'MidGrass', 'DryGround', 'Water' ); type TCollection = Collection.TCollection; TClassTypeInfo = array[TLandType] of TCollection; type TMapTexture = class; TLandClassInfo = class; TTextureRelation = (trNone, trMix, trBorder, trDither); PTextureRelations = ^TTextureRelations; TTextureRelations = array[0..0] of TTextureRelation; TMapTexture = class public constructor Create(Bmp : TBitmap; txCount : integer); destructor Destroy; override; private fBmp : TBitmap; fRelations : PTextureRelations; end; TLandClassInfo = class public constructor Create(IniPath : string); destructor Destroy; override; private fTemplate : TBitmap; fTextures : TCollection; fClassTypes : TClassTypeInfo; fSourcePath : string; fOutputPath : string; fClassesPath : string; fCenterCount : integer; fStrghtCount : integer; fCornerCount : integer; private procedure LoadTextures(Ini : TIniFile); procedure LoadVectors(center, straight, corner : string); procedure SaveClass(name : string; Bmp : TBitmap; clType : TLandType; txA, txB, varIdx : integer; TraceVert : boolean); procedure GenCenters; procedure GenOtherTypes; public procedure Run; end; implementation uses Classes, Forms; type TColorRec = packed record R : byte; G : byte; B : byte; I : byte; end; function LoadBitmap(path : string; Bmp : TBitmap) : boolean; var st : TStream; begin try st := TFileStream.Create(path, fmOpenRead); try Bmp.LoadFromStream(st); finally st.Free; end; result := true; except result := false; end; end; function SaveBitmap(path : string; Bmp : TBitmap) : boolean; var st : TStream; begin try st := TFileStream.Create(path, fmCreate); try Bmp.SaveToStream(st); finally st.Free; end; result := true; except result := false; end; end; procedure StraightGradient(Bmp : TBitmap); var xSize : integer; ySize : integer; tC : TColor; fC : TColor; i : integer; y, y1 : integer; d : integer; Step : integer; Brush : integer; Color : TColor; begin xSize := Bmp.Width; ySize := Bmp.Height; tC := Bmp.Canvas.Pixels[0, 0]; fC := Bmp.Canvas.Pixels[0, pred(ySize)]; for i := 0 to pred(xSize) do begin y := pred(ySize); while (y >= 0) and (Bmp.Canvas.Pixels[i, y] = fC) do dec(y); y1 := y; d := 0; while (y >= 0) and (Bmp.Canvas.Pixels[i, y] <> tC) do begin dec(y); inc(d); end; Step := integer(lo(tC) - lo(fC)) div d; Brush := lo(fC); while y1 >= y do begin with TColorRec(Color) do begin R := Brush; G := Brush; B := Brush; I := 0; end; Brush := Brush + Step; Bmp.Canvas.Pixels[i, y1] := Color; Color := Bmp.Canvas.Pixels[i, y1]; dec(y1); end; while y1 > 0 do begin if Bmp.Canvas.Pixels[i, y1] <> tC then Bmp.Canvas.Pixels[i, y1] := tC; dec(y1); end; end; end; procedure RadialGradient(Bmp : TBitmap); var xSize : integer; ySize : integer; tC : TColor; fC : TColor; i, j : integer; x, x1 : integer; y, y1 : integer; d : integer; Step : integer; Brush : integer; Color : TColor; ptA : integer; ptB : integer; begin xSize := Bmp.Width; ySize := Bmp.Height; fC := Bmp.Canvas.Pixels[1, 1]; tC := Bmp.Canvas.Pixels[pred(xSize)-1, pred(xSize)-1]; j := 0; // Calculate ptA x := 0; y := pred(ySize); while (x < xSize) and (Bmp.Canvas.Pixels[x, y] <> tC) do inc(x); ptA := x; // Calculate ptB x := pred(xSize); y := 0; while (y < ySize) and (Bmp.Canvas.Pixels[x, y] <> tC) do inc(y); ptB := y; for i := pred(ySize) downto 0 do begin x := 0; y := i; while (x <= j) and (y < ySize) and (Bmp.Canvas.Pixels[x, y] = fC) do begin inc(x); inc(y); end; x1 := x; y1 := y; d := 0; while (x <= j) and (y < ySize) and (Bmp.Canvas.Pixels[x, y] <> tC) do begin inc(x); inc(y); inc(d); end; if d > 0 then begin //if Bmp.Canvas.Pixels[x, y] = -1 //then d := ySize div 2; if y = ySize then d := d + round(sqrt(sqr(ptA - x)/2)); Step := integer(lo(tC) - lo(fC)) div d; Brush := lo(fC); while (x1 < x) and (y1 < y) do begin with TColorRec(Color) do begin R := Brush; G := Brush; B := Brush; I := 0; end; Brush := Brush + Step; Bmp.Canvas.Pixels[x1, y1] := Color; inc(x1); inc(y1); end; end; inc(j); end; j := pred(xSize); for i := 0 to pred(ySize) do begin x := j; y := 0; while (x <= pred(xSize)) and (y <= i) and (Bmp.Canvas.Pixels[x, y] = fC) do begin inc(x); inc(y); end; x1 := x; y1 := y; d := 0; while (x <= pred(xSize)) and (y <= i) and (Bmp.Canvas.Pixels[x, y] <> tC) do begin inc(x); inc(y); inc(d); end; if d > 0 then begin //if Bmp.Canvas.Pixels[x, y] = -1 //then d := ySize div 2; if x = xSize then d := d + round(sqrt(sqr(ptB - y)/2)); Step := integer(lo(tC) - lo(fC)) div d; Brush := lo(fC); while (x1 < x) and (y1 < y) do begin with TColorRec(Color) do begin R := Brush; G := Brush; B := Brush; I := 0; end; Brush := Brush + Step; Bmp.Canvas.Pixels[x1, y1] := Color; inc(x1); inc(y1); end; end; dec(j); end; {for i := 0 to pred(Bmp.Width) do for j := 0 to pred(Bmp.Height) do begin if (Bmp.Canvas.Pixels[i, j] <> clWhite) and (Bmp.Canvas.Pixels[i, j] <> clBlack) then Bmp.Canvas.Pixels[i, j] := $00808080; end;} end; procedure RotateBitmap(var Bmp : TBitmap); var xSize : integer; ySize : integer; x, y : integer; TmpBmp : TBitmap; begin xSize := Bmp.Width; ySize := Bmp.Height; TmpBmp := TBitmap.Create; TmpBmp.Width := xSize; TmpBmp.Height := ySize; for x := 0 to pred(xSize) do for y := 0 to pred(ySize) do TmpBmp.Canvas.Pixels[x, y] := Bmp.Canvas.Pixels[y, xSize-x-1]; Bmp.Free; Bmp := TmpBmp; end; function Xt(x, y, offset : integer) : integer; begin result := offset + x - y; end; function Yt(x, y : integer) : integer; begin result := trunc((x + y)/2); end; function ConvertToIsometric(Template, Bmp : TBitmap) : TBitmap; var xSize : integer; ySize : integer; x, y : integer; c : TColor; begin xSize := Bmp.Width; ySize := Bmp.Height; result := TBitmap.Create; result.Width := 2*xSize; result.Height := ySize; result.Canvas.Brush.Color := clBlue; result.Canvas.FillRect(result.Canvas.ClipRect); for x := 0 to pred(xSize) do for y := 0 to pred(ySize) do begin c := Bmp.Canvas.Pixels[x, y]; result.Canvas.Pixels[Xt(x, y, xSize), Yt(x, y) + 1] := c; result.Canvas.Pixels[Xt(x, y, xSize) - 1, Yt(x, y)] := c; end; c := Bmp.Canvas.Pixels[random(xSize), random(ySize)]; for x := 0 to pred(Template.Width) do for y := 0 to pred(Template.Height) do if Template.Canvas.Pixels[x, y] = clWhite then result.Canvas.Pixels[x, y] := clBlue else if result.Canvas.Pixels[x, y] = clBlue then result.Canvas.Pixels[x, y] := c; end; function AverageColors(Color1, Color2 : TColor; Perc1, Perc2, BrdPrc1, BrdPrc2 : single) : TColor; var ColRec1 : TColorRec absolute Color1; ColRec2 : TColorRec absolute Color2; begin with TColorRec(result) do begin R := round((ColRec1.R*Perc1*BrdPrc1 + ColRec2.R*Perc2*BrdPrc2)); G := round((ColRec1.G*Perc1*BrdPrc1 + ColRec2.G*Perc2*BrdPrc2)); B := round((ColRec1.B*Perc1*BrdPrc1 + ColRec2.B*Perc2*BrdPrc2)); I := round((ColRec1.I*Perc1*BrdPrc1 + ColRec2.I*Perc2*BrdPrc2)); end; end; function MixTextures(Template, TextureA, TextureB : TBitmap; PercA, PercB : byte; Dither : boolean) : TBitmap; var Templ : TCanvas; xSize : integer; ySize : integer; xTa : integer; yTa : integer; xTb : integer; yTb : integer; i, j : integer; Color : integer; Transp : integer; aPerc : byte; bPerc : byte; begin Templ := Template.Canvas; with Templ.ClipRect do begin xSize := Right - Left; ySize := Bottom - Top; end; // Result bitmap result := TBitMap.Create; result.Width := xSize; result.Height := ySize; // Get the transparent color Transp := ColorToRGB(Templ.Pixels[0, 0]); // Get randomly the areas in the textures xTa := random(TextureA.Canvas.ClipRect.Right - xSize); yTa := random(TextureA.Canvas.ClipRect.Bottom - ySize); xTb := random(TextureB.Canvas.ClipRect.Right - xSize); yTb := random(TextureB.Canvas.ClipRect.Bottom - ySize); // Create the resulting texture for i := 0 to pred(xSize) do for j := 0 to pred(ySize) do begin Color := ColorToRGB(Templ.Pixels[i, j]); if Color <> Transp then case lo(Color) of $00 : result.Canvas.Pixels[i, j] := TextureB.Canvas.Pixels[xTb + i, yTb + j]; $FF : result.Canvas.Pixels[i, j] := TextureA.Canvas.Pixels[xTa + i, yTa + j]; else begin aPerc := lo(Color); bPerc := high(bPerc) - aPerc; if Dither then begin if random(256) <= aPerc then result.Canvas.Pixels[i, j] := TextureA.Canvas.Pixels[xTa + i, yTa + j] else result.Canvas.Pixels[i, j] := TextureB.Canvas.Pixels[xTa + i, yTa + j]; end else result.Canvas.Pixels[i, j] := AverageColors( TextureA.Canvas.Pixels[xTa + i, yTa + j], TextureB.Canvas.Pixels[xTb + i, yTb + j], aPerc/high(aPerc), bPerc/high(bPerc), PercA/100, PercB/100); end; end else result.Canvas.Pixels[i, j] := Transp; end; end; (* function ConvertToPalettedBitmap(Bmp : TBitmap; VertTrace : boolean; var AvrColor : TColor) : TBitmap; begin result := Bmp; end; *) function ConvertToPalettedBitmap(Bmp : TBitmap; VertTrace : boolean; var AvrColor : TColor) : TBitmap; type PRGB = ^TRGB; TRGB = packed record Blue : byte; Green : byte; Red : byte; Unk : byte; end; T256Palette = array[0..255] of TColor; var pal : PLogPalette; hpal : HPALETTE; line : PByteArray; aux : T256Palette; plIdx : integer; xSize : integer; ySize : integer; i, j : integer; Color : TColor; function SameColor(var col1, col2 : TColor) : boolean; const MinDist = 10; var c1 : TRGB absolute col1; c2 : TRGB absolute col2; dist : integer; begin dist := abs(integer(c1.Red) - integer(c2.Red)) + abs(integer(c1.Green) - integer(c2.Green)) + abs(integer(c1.Blue) - integer(c2.Blue)); result := dist <= MinDist; end; function ColorExists(Color : TColor) : boolean; var i : integer; begin Color := Color and $00FFFFFF; i := pred(plIdx); while (i >= 0) and not SameColor(Color, aux[i]) do //(Color <> aux[i]) do //((aux[i].Red <> C.R) or (aux[i].Green <> C.G) or (aux[i].Blue <> C.B)) do dec(i); result := i >= 0; end; function PaletteIndexOf(Color : TColor) : byte; var t : single; d : single; i : integer; C : TColorRec absolute Color; begin Color := Color and $00FFFFFF; if Color = aux[0] then result := 0 else begin result := 1; d := 256; i := 1; while (i < 256) and (d > 0) do begin with TColorRec(aux[i]) do t := sqrt(sqr(C.R - R) + sqr(C.G - G) + sqr(C.B - B)); if d > t then begin d := t; result := i; end; inc(i); end; end; end; procedure PickColor(Color : TColor); begin if not ColorExists(Color) then begin aux[plIdx] := Color and $00FFFFFF; inc(plIdx); end; end; procedure PickVLineColors(lnIdx : integer); var i : integer; begin i := 0; while (i < ySize) and (plIdx < 256) do begin PickColor(Bmp.Canvas.Pixels[Xt(lnIdx, i, 32), Yt(lnIdx, i)]); inc(i); end; end; procedure PickHLineColors(lnIdx : integer); var j : integer; begin j := 0; while (j < xSize) and (plIdx < 256) do begin PickColor(Bmp.Canvas.Pixels[Yt(j, lnIdx), Xt(j, lnIdx, 32)]); inc(j); end; end; var cR, cG, cB : integer; cnt : integer; bgColor : TColor; begin cR := 0; cG := 0; cB := 0; cnt := 0; xSize := Bmp.Width; ySize := Bmp.Height; GetMem(pal, sizeof(TLogPalette) + sizeof(TPaletteEntry) * 255); pal.palVersion := $300; pal.palNumEntries := 256; // Create the 256 colors palette FillChar(aux, 256*sizeof(aux[0]), 0); // Transparent color aux[0] := $000000FF; //Bmp.Canvas.Pixels[0, 0]; plIdx := 1; bgColor := Bmp.Canvas.Pixels[0, 0]; i := 0; while (i < ySize) and (plIdx < 256) do begin j := 0; while (j < xSize) and (plIdx < 256) do begin Color := Bmp.Canvas.Pixels[j, i]; PickColor(Color); if Color <> bgColor then begin with TColorRec(Color) do begin inc(cR, R); inc(cG, G); inc(cB, B); end; inc(cnt); end; inc(j); end; inc(i); end; { while (i < pred(ySize div 2)) and (plIdx < 256) do begin PickVLineColors(pred(ySize div 2) - i); PickHLineColors(pred(ySize div 2) - i); PickVLineColors(pred(ySize) - i); PickHLineColors(pred(ySize) - i); inc(i); end; } // Create the new bitmap result := TBitmap.Create; result.PixelFormat := pf8bit; result.Width := xSize; result.Height := ySize; // Assign the palette for i := 0 to 255 do pal.palPalEntry[i] := TPaletteEntry(aux[i]); { with TColorRec(aux[i]) do begin pal.palPalEntry[i].peRed := R; pal.palPalEntry[i].peGreen := G; pal.palPalEntry[i].peBlue := B; end; } hpal := CreatePalette(pal^); if hpal <> 0 then result.Palette := hpal; // Set the pixels for i := 0 to pred(ySize) do begin line := result.ScanLine[i]; for j := 0 to pred(xSize) do line[j] := PaletteIndexOf(Bmp.Canvas.Pixels[j, i]); end; with TColorRec(AvrColor) do begin R := round(cR/cnt); G := round(cG/cnt); B := round(cB/cnt); I := 0; end; end; (* function ConvertToPalettedBitmap(Bmp : TBitmap; VertTrace : boolean; var AvrColor : TColor) : TBitmap; type PRGB = ^TRGB; TRGB = packed record Blue : byte; Green : byte; Red : byte; Unk : byte; end; T256Palette = array[0..255] of TColor; var pal : PLogPalette; hpal : HPALETTE; line : PByteArray; aux : T256Palette; plIdx : integer; xSize : integer; ySize : integer; i, j : integer; Color : TColor; function ColorExists(Color : TColor) : boolean; var i : integer; begin Color := Color and $00FFFFFF; i := pred(plIdx); while (i >= 0) and (Color <> aux[i]) do //((aux[i].Red <> C.R) or (aux[i].Green <> C.G) or (aux[i].Blue <> C.B)) do dec(i); result := i >= 0; end; function PaletteIndexOf(Color : TColor) : byte; var t : single; d : single; i : integer; C : TColorRec absolute Color; begin Color := Color and $00FFFFFF; if Color = aux[0] then result := 0 else begin result := 1; d := 256; i := 1; while (i < 256) and (d > 0) do begin with TColorRec(aux[i]) do t := sqrt(sqr(C.R - R) + sqr(C.G - G) + sqr(C.B - B)); if d > t then begin d := t; result := i; end; inc(i); end; end; end; procedure PickColor(Color : TColor); begin if not ColorExists(Color) then begin aux[plIdx] := Color and $00FFFFFF; inc(plIdx); end; end; procedure PickVLineColors(lnIdx : integer); var i : integer; begin i := 0; while (i < ySize) and (plIdx < 256) do begin PickColor(Bmp.Canvas.Pixels[Xt(lnIdx, i, 32), Yt(lnIdx, i)]); inc(i); end; end; procedure PickHLineColors(lnIdx : integer); var j : integer; begin j := 0; while (j < xSize) and (plIdx < 256) do begin PickColor(Bmp.Canvas.Pixels[Yt(j, lnIdx), Xt(j, lnIdx, 32)]); inc(j); end; end; var cR, cG, cB : integer; cnt : integer; bgColor : TColor; begin cR := 0; cG := 0; cB := 0; cnt := 0; xSize := Bmp.Width; ySize := Bmp.Height; GetMem(pal, sizeof(TLogPalette) + sizeof(TPaletteEntry) * 255); pal.palVersion := $300; pal.palNumEntries := 256; // Create the 256 colors palette FillChar(aux, 256*sizeof(aux[0]), 0); // Transparent color aux[0] := $000000FF; //Bmp.Canvas.Pixels[0, 0]; plIdx := 1; bgColor := Bmp.Canvas.Pixels[0, 0]; i := 0; while (i < ySize) and (plIdx < 256) do begin j := 0; while (j < xSize) and (plIdx < 256) do begin Color := Bmp.Canvas.Pixels[j, i]; PickColor(Color); if Color <> bgColor then begin with TColorRec(Color) do begin inc(cR, R); inc(cG, G); inc(cB, B); end; inc(cnt); end; inc(j); end; inc(i); end; { while (i < pred(ySize div 2)) and (plIdx < 256) do begin PickVLineColors(pred(ySize div 2) - i); PickHLineColors(pred(ySize div 2) - i); PickVLineColors(pred(ySize) - i); PickHLineColors(pred(ySize) - i); inc(i); end; } // Create the new bitmap result := TBitmap.Create; result.PixelFormat := pf8bit; result.Width := xSize; result.Height := ySize; // Assign the palette for i := 0 to 255 do pal.palPalEntry[i] := TPaletteEntry(aux[i]); { with TColorRec(aux[i]) do begin pal.palPalEntry[i].peRed := R; pal.palPalEntry[i].peGreen := G; pal.palPalEntry[i].peBlue := B; end; } hpal := CreatePalette(pal^); if hpal <> 0 then result.Palette := hpal; // Set the pixels for i := 0 to pred(ySize) do begin line := result.ScanLine[i]; for j := 0 to pred(xSize) do line[j] := PaletteIndexOf(Bmp.Canvas.Pixels[j, i]); end; with TColorRec(AvrColor) do begin R := round(cR/cnt); G := round(cG/cnt); B := round(cB/cnt); I := 0; end; end; *) { function ConvertToPalettedBitmap(Bmp : TBitmap; VertTrace : boolean) : TBitmap; type PRGB = ^TRGB; TRGB = record Red : byte; Green : byte; Blue : byte; end; T256Palette = array[0..255] of TRGB; var pal : PLogPalette; hpal : HPALETTE; line : PByteArray; aux : T256Palette; p : PRGB; plIdx : integer; Color : TColor; xSize : integer; ySize : integer; i, j : integer; function ColorExists(Color : TColor) : boolean; var i : integer; p : PRGB; C : TColorRec absolute Color; begin i := 0; p := @aux[i]; while (i < plIdx) and ((p.Red <> C.R) or (p.Green <> C.G) or (p.Blue <> C.B)) do inc(i); result := i < plIdx; end; function PaletteIndexOf(Color : TColor) : byte; var t : integer; d : integer; i : integer; p : PRGB; begin result := 0; d := 3*256; i := 0; while (i < 256) and (d > 0) do begin p := @aux[i]; with TColorRec(Color) do t := abs(p.Red - R) + abs(p.Green - G) + abs(p.Blue - B); if d > t then begin d := t; result := i; end; inc(i); end; end; begin xSize := Bmp.Width; ySize := Bmp.Height; GetMem(pal, sizeof(TLogPalette) + sizeof(TPaletteEntry) * 255); pal.palVersion := $300; pal.palNumEntries := 256; // Create the 256 colors palette FillChar(aux, 256*sizeof(aux[0]), 0); plIdx := 0; // aux[0] = Black i := 0; while (i < ySize) and (plIdx < 256) do begin j := 0; while (j < xSize) and (plIdx < 256) do begin Color := Bmp.Canvas.Pixels[i, j]; if not ColorExists(Color) then begin p := @aux[plIdx]; with TColorRec(Color) do begin p.Red := R; p.Green := G; p.Blue := B; end; inc(plIdx); end; inc(j); end; inc(i); end; // Create the new bitmap result := TBitmap.Create; result.PixelFormat := pf8bit; result.Width := xSize; result.Height := ySize; // Assign the palette for i := 0 to 255 do begin p := @aux[i]; pal.palPalEntry[i].peRed := p.Red; pal.palPalEntry[i].peGreen := p.Green; pal.palPalEntry[i].peBlue := p.Blue; end; hpal := CreatePalette(pal^); if hpal <> 0 then result.Palette := hpal; // Set the pixels for i := 0 to pred(ySize) do begin line := result.ScanLine[i]; for j := 0 to pred(xSize) do line[j] := PaletteIndexOf(Bmp.Canvas.Pixels[j, i]); end; end; } // TMapTexture constructor TMapTexture.Create(Bmp : TBitmap; txCount : integer); begin inherited Create; fBmp := Bmp; GetMem(fRelations, txCount*sizeof(fRelations[0])); FillChar(fRelations[0], txCount*sizeof(fRelations[0]), byte(trNone)); end; destructor TMapTexture.Destroy; begin fBmp.Free; FreeMem(fRelations); end; // TLandClassInfo constructor TLandClassInfo.Create(IniPath : string); var i : TLandType; Ini : TIniFile; ExePath : string; begin Ini := TIniFile.Create(IniPath); try ExePath := ExtractFilePath(Application.ExeName); fSourcePath := ExePath + Ini.ReadString('Paths', 'Source', ''); fOutputPath := ExePath + Ini.ReadString('Paths', 'ImgOutput', ''); fClassesPath := ExePath + Ini.ReadString('Paths', 'ClassOutput', ''); fCenterCount := Ini.ReadInteger('Variation', 'cntCenter', 1); fStrghtCount := Ini.ReadInteger('Variation', 'cntStraight', 1); fCornerCount := Ini.ReadInteger('Variation', 'cntCorner', 1); fTextures := TCollection.Create(0, rkBelonguer); LoadTextures(Ini); fTemplate := TBitmap.Create; LoadBitmap(fSourcePath + 'Template.bmp', fTemplate); for i := low(i) to high(i) do fClassTypes[i] := TCollection.Create(0, rkBelonguer); LoadVectors( Ini.ReadString('Source', 'Center', ''), Ini.ReadString('Source', 'Straight', ''), Ini.ReadString('Source', 'Corner', '')); finally Ini.Free; end; end; destructor TLandClassInfo.Destroy; var i : TLandType; begin fTemplate.Free; fTextures.Free; for i := low(i) to high(i) do fClassTypes[i].Free; end; procedure TLandClassInfo.LoadTextures(Ini : TIniFile); var Bmp : TBitmap; Texture : TMapTexture; i, j : integer; Count : integer; txRel : string; begin Count := Ini.ReadInteger('Textures', 'Count', 0); for i := 0 to pred(Count) do begin Bmp := TBitmap.Create; if LoadBitmap(fSourcePath + 'Texture.' + IntToStr(i) + '.bmp', Bmp) then begin Texture := TMapTexture.Create(Bmp, Count); txRel := Ini.ReadString('Textures', 'Texture' + IntToStr(i), ''); j := 1; while (j <= Count) and (j <= length(txRel)) do begin case txRel[j] of 'm' : Texture.fRelations[j-1] := trMix; 'd' : Texture.fRelations[j-1] := trDither; 'b' : Texture.fRelations[j-1] := trBorder; else Texture.fRelations[j-1] := trNone; end; inc(j); end; fTextures.Insert(Texture); end else Bmp.Free; end; end; procedure TLandClassInfo.LoadVectors(center, straight, corner : string); var Bmp, Tmp : TBitmap; SearchRec : TSearchRec; x, y : integer; //St : TStream; begin // Center Bmp := TBitmap.Create; if LoadBitmap(fSourcePath + center, Bmp) then begin //St := TFileStream.Create('d:\temp\center.bmp', fmCreate); Tmp := ConvertToIsometric(fTemplate, Bmp); //Tmp.SaveToStream(St); //St.Free; fClassTypes[ldtCenter].Insert(Tmp); end; Bmp.Free; // Straight if FindFirst(fSourcePath + straight, faArchive, SearchRec) = 0 then repeat Bmp := TBitmap.Create; if LoadBitmap(fSourcePath + SearchRec.Name, Bmp) then begin StraightGradient(Bmp); // East fClassTypes[ldtE].Insert(ConvertToIsometric(fTemplate, Bmp)); // South RotateBitmap(Bmp); fClassTypes[ldtS].Insert(ConvertToIsometric(fTemplate, Bmp)); // West RotateBitmap(Bmp); fClassTypes[ldtW].Insert(ConvertToIsometric(fTemplate, Bmp)); // North RotateBitmap(Bmp); fClassTypes[ldtN].Insert(ConvertToIsometric(fTemplate, Bmp)); Bmp.Free; end; until FindNext(SearchRec) <> 0; // Corner if FindFirst(fSourcePath + corner, faArchive, SearchRec) = 0 then repeat Bmp := TBitmap.Create; if LoadBitmap(fSourcePath + SearchRec.Name, Bmp) then begin // Apply gradient RadialGradient(Bmp); // Northeast fClassTypes[ldtNEo].Insert(ConvertToIsometric(fTemplate, Bmp)); // Southeast RotateBitmap(Bmp); fClassTypes[ldtSEo].Insert(ConvertToIsometric(fTemplate, Bmp)); // Southwest RotateBitmap(Bmp); fClassTypes[ldtSWo].Insert(ConvertToIsometric(fTemplate, Bmp)); // Northwest RotateBitmap(Bmp); fClassTypes[ldtNWo].Insert(ConvertToIsometric(fTemplate, Bmp)); Bmp.Free; Bmp := TBitmap.Create; LoadBitmap(fSourcePath + SearchRec.Name, Bmp); // swap colors for x := 0 to pred(Bmp.Width) do for y := 0 to pred(Bmp.Height) do case ColorToRGB(Bmp.Canvas.Pixels[x, y]) of clBlack : Bmp.Canvas.Pixels[x, y] := clWhite; clWhite : Bmp.Canvas.Pixels[x, y] := clBlack; end; // Apply gradient RadialGradient(Bmp); // Northeast fClassTypes[ldtSWi].Insert(ConvertToIsometric(fTemplate, Bmp)); // Southeast RotateBitmap(Bmp); fClassTypes[ldtNWi].Insert(ConvertToIsometric(fTemplate, Bmp)); // Southwest RotateBitmap(Bmp); fClassTypes[ldtNEi].Insert(ConvertToIsometric(fTemplate, Bmp)); // Northwest RotateBitmap(Bmp); fClassTypes[ldtSEi].Insert(ConvertToIsometric(fTemplate, Bmp)); end; until FindNext(SearchRec) <> 0; end; function LandTypeToStr(aType : TLandType) : string; begin case atype of ldtCenter : result := 'Center'; ldtN : result := 'N'; ldtE : result := 'E'; ldtS : result := 'S'; ldtW : result := 'W'; ldtNEo : result := 'NEo'; ldtSEo : result := 'SEo'; ldtSWo : result := 'SWo'; ldtNWo : result := 'NWo'; ldtNEi : result := 'NEi'; ldtSEi : result := 'SEi'; ldtSWi : result := 'SWi'; ldtNWi : result := 'NWi'; end; end; procedure SaveIniClass(path : string; Id : byte; Color : TColor; BmpName : string); var Ini : TextFile; begin AssignFile(Ini, path + 'land.' + IntToStr(Id) + '.ini'); Rewrite(Ini); Writeln(Ini, '[General]'); Writeln(Ini, 'Id=' + IntToStr(Id)); Writeln(Ini, 'MapColor=' + IntToStr(integer(Color))); // >> Writeln(Ini, '[Images]'); Writeln(Ini, '64x32=' + BmpName); CloseFile(Ini); end; procedure TLandClassInfo.SaveClass(name : string; Bmp : TBitmap; clType : TLandType; txA, txB, varIdx : integer; TraceVert : boolean); var Id : byte; PalBmp : TBitmap; Color : TColor; BmpName : string; function VisualText : string; begin result := TextureNames[TLandClass(txA)] + LandTypeToStr(clType) + IntToStr(varIdx); end; function InvertLand( Id : TLandVisualClassId ) : TLandVisualClassId; var c : TLandClass; t : TLandType; v : byte; begin c := LandClassOf( Id ); t := LandTypeOf( Id ); v := LandVarOf( Id ); case t of ldtNEo : t := ldtNEi; ldtSEo : t := ldtSEi; ldtSWo : t := ldtSWi; ldtNWo : t := ldtNWi; ldtNEi : t := ldtNEo; ldtSEi : t := ldtSEo; ldtSWi : t := ldtSWo; ldtNWi : t := ldtNWo; end; result := LandIdOf( c, t, v ); end; begin //Id := Land.LandIdOf(TLandClass(txA), TLandClass(txB), clType, varIdx); Id := Land.LandIdOf(TLandClass(txA), clType, varIdx); // TLandClass(txA), TLandClass(txB), clType, varIdx); //Id := InvertLand( Id ); PalBmp := ConvertToPalettedBitmap(Bmp, false, Color); BmpName := 'land.' + IntToStr(Id) + '.' + VisualText + '.bmp'; SaveBitmap(fOutputPath + BmpName, PalBmp); SaveIniClass(fClassesPath, Id, Color, BmpName); // PalBmp.Free; end; procedure TLandClassInfo.GenCenters; var i : integer; txIdx : integer; Templ : TBitmap; Bmp : TBitmap; begin // Center for i := 1 to fCenterCount do begin Templ := TBitmap(fClassTypes[ldtCenter][0]); for txIdx := 0 to pred(fTextures.Count) do begin Bmp := MixTextures(Templ, TMapTexture(fTextures[txIdx]).fBmp, TMapTexture(fTextures[txIdx]).fBmp, 100, 100, false); SaveClass('center', Bmp, ldtCenter, txIdx, txIdx, i-1, true); Bmp.Free; end; end; end; procedure TLandClassInfo.GenOtherTypes; var txCount : integer; txAIdx : integer; txBIdx : integer; varIdx : integer; Templ : TBitmap; Bmp : TBitmap; ldType : TLandType; TextureA : TMapTexture; TextureB : TMapTexture; BorderA : byte; BorderB : byte; Dither : boolean; begin // Center txCount := fTextures.Count; for txAIdx := pred(txCount) downto 0 do begin TextureA := TMapTexture(fTextures[txAIdx]); for txBIdx := pred(txCount) downto 0 do begin TextureB := TMapTexture(fTextures[txBIdx]); if TextureA.fRelations[txBIdx] <> trNone then begin if TextureA.fRelations[txBIdx] = trBorder then BorderA := 70 else BorderA := 100; if TextureB.fRelations[txAIdx] = trBorder then BorderB := 70 else BorderB := 100; Dither := TextureA.fRelations[txBIdx] = trDither; // Straights for ldType := ldtN to ldtW do for varIdx := 0 to pred(fStrghtCount) do begin Templ := TBitmap(fClassTypes[ldType][Random(fClassTypes[ldType].Count)]); Bmp := MixTextures(Templ, TextureA.fBmp, TextureB.fBmp, BorderA, BorderB, Dither); SaveClass('straight', Bmp, ldType, txAIdx, txBIdx, varIdx, true); Bmp.Free; end; // Corners for ldType := ldtNEo to ldtNWi do for varIdx := 0 to pred(fCornerCount) do begin Templ := TBitmap(fClassTypes[ldType][Random(fClassTypes[ldType].Count)]); Bmp := MixTextures(Templ, TextureA.fBmp, TextureB.fBmp, BorderA, BorderB, Dither); SaveClass('corner', Bmp, ldType, txAIdx, txBIdx, varIdx, false); Bmp.Free; end; end; end; end; end; procedure TLandClassInfo.Run; begin GenCenters; GenOtherTypes; end; initialization Randomize; end.
//Exercicio 15: Assuma que o trabalhador do exercício 08 deve pagar 10% de imposto se o seu salário anual for menor ou //igual a R$ 12.000,00. Caso o salário seja maior que este valor o imposto devido é igual a 10% sobre R$ 12.000,00 mais //25% sobre o que passar de R$ 12.000,00. Escreva um algoritmo que calcule e exiba o imposto devido pelo trabalhador. { Solução em Portugol Algoritmo Exercicio 15; Const valor_hora_normal = 10; valor_hora_extra = 15; Var salario_anual, hora_normal, hora_extra: real; Inicio exiba("Programa que calcula o salário anual de um trabalhador."); exiba("Digite a quantidade de horas normais trabalhadas no ano: "); leia(hora_normal); exiba("Digite a quantidade de horas extras trabalhadas no ano: "); leia(hora_extra); salario_anual <- hora_normal * valor_hora_normal + hora_extra * valor_hora _extra; se(salario_anual < 12000) então exiba("O trabalhador deve pagar: ", salario_anual * 0,1," reais de imposto."); fimse; se(salario_anual >= 12000) então exiba("O trabalhador deve pagar: ", 1200 + 0,25 * (salario_anual - 12000), " reais de imposto."); fimse; Fim. } // Solução em Pascal Program Exercicio15; uses crt; Const valor_hora_normal = 10; valor_hora_extra = 15; var salario_anual, hora_normal, hora_extra: real; begin clrscr; writeln('Programa que calcula o salário anual de um trabalhador.'); writeln('Digite a quantidade de horas normais trabalhadas no ano: '); readln(hora_normal); writeln('Digite a quantidade de horas extras trabalhadas no ano: '); readln(hora_extra); salario_anual := hora_normal * valor_hora_normal + hora_extra * valor_hora_extra; if(salario_anual < 12000) then writeln('O trabalhador deve pagar: ', (salario_anual * 0.1):0:2,' reais de imposto.'); if(salario_anual >= 12000) then writeln('O trabalhador deve pagar: ', (1200 + 0.25 * (salario_anual - 12000)):0:2, ' reais de imposto.'); repeat until keypressed; end.
{ *************************************************************************** Copyright (c) 2016-2018 Kike Pérez Unit : Quick.Format Description : String Format functions Author : Kike Pérez Version : 1.4 Created : 14/07/2017 Modified : 19/07/2018 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.Format; {$i QuickLib.inc} interface uses SysUtils, Math; //converts a number to thousand delimeter string function NumberToStr(const Number : Int64) : string; //convert bytes to KB, MB, TB... function FormatBytes(const aBytes : Int64; Spaced : Boolean = False) : string; implementation function NumberToStr(const Number : Int64) : string; begin try Result := FormatFloat('0,',Number); except Result := '#Error'; end; end; function FormatBytes(const aBytes : Int64; Spaced : Boolean = False) : string; const mesure : array [0..8] of string = ('Byte(s)', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); var i : Integer; bfmt : string; cspace : Char; begin i := 0; while aBytes > Power(1024, i + 1) do Inc(i); if Spaced then cspace := Char(32) else cspace := Char(0); // bfmt := '%.2f %s' //else bfmt := '%.2f%s'; if i < 2 then bfmt := '%.0f%s%s' else bfmt := '%.2f%s%s'; Result := Format(bfmt,[aBytes / IntPower(1024, i),cspace,mesure[i]]); end; end.
//** unit uImage; interface uses Graphics, JPEG, GIFImage, PNGImage; type //** TImages = array of TBitmap; //** TImage = class private //** FJPG: TJpegImage; //** FGIF: TGIFImage; //** FPNG: TPNGObject; public //** procedure Gamma(Bitmap: TBitmap; L: Double); //** procedure Scale(Bitmap: TBitmap; Width, Height: Integer); //** procedure MixColors(Bitmap: TBitmap; Color: Integer); //** function Load(const APath: string; Bitmap: TBitmap): Boolean; //** procedure Split(const APath: string; var AImages: TImages; CellSize: Integer; ATransparent: Boolean = False); end; implementation uses SysUtils, Types; { TImage } procedure TImage.Scale(Bitmap: TBitmap; Width, Height: Integer); var FTemp: TBitmap; ARect: TRect; begin FTemp := TBitmap.Create; try FTemp.Width := Width; FTemp.Height := Height; ARect := Rect(0, 0, Width, Height); FTemp.Canvas.StretchDraw(ARect, Bitmap); Bitmap.Assign(FTemp); finally FTemp.Free; end; end; procedure TImage.Gamma(Bitmap: TBitmap; L: Double); function Power(Base, Exponent: Extended): Extended; begin Result := Exp(Exponent * Ln(Base)); end; type TRGB = record B, G, R: Byte; end; pRGB = ^TRGB; var Dest: pRGB; X, Y: Word; GT: array[0..255] of Byte; begin Bitmap.PixelFormat := pf24Bit; GT[0] := 0; if L = 0 then L := 0.01; for X := 1 to 255 do GT[X] := Round(255 * Power(X / 255, 1 / L)); for Y := 0 to Bitmap.Height - 1 do begin Dest := Bitmap.ScanLine[y]; for X := 0 to Bitmap.Width - 1 do begin with Dest^ do begin R := GT[R]; G := GT[G]; B := GT[B]; end; Inc(Dest); end; end; end; procedure TImage.MixColors(Bitmap: TBitmap; Color: Integer); function GetR(const Color: TColor): Byte; begin Result := Lo(Color); end; function GetG(const Color: TColor): Byte; begin Result := Lo(Color shr 8); end; function GetB(const Color: TColor): Byte; begin Result := Lo((Color shr 8) shr 8); end; function BLimit(B: Integer): Byte; begin if B < 0 then Result := 0 else if B > 255 then Result := 255 else Result := B; end; type TRGB = record B, G, R: Byte; end; pRGB = ^TRGB; var r1, g1, b1: Byte; x, y: Integer; Dest: pRGB; A: Double; begin Bitmap.PixelFormat := pf24Bit; r1 := Round(255 / 100 * GetR(Color)); g1 := Round(255 / 100 * GetG(Color)); b1 := Round(255 / 100 * GetB(Color)); for y := 0 to Bitmap.Height - 1 do begin Dest := Bitmap.ScanLine[y]; for x := 0 to Bitmap.Width - 1 do begin with Dest^ do begin A := (r + b + g) / 300; with Dest^ do begin R := BLimit(Round(r1 * A)); G := BLimit(Round(g1 * A)); B := BLimit(Round(b1 * A)); if (R=255) and (G=255) and (B=255) then begin R:= 216; G:= 212; B:= 240; end; end; end; Inc(Dest); end; end; end; function TImage.Load(const APath: string; Bitmap: TBitmap): Boolean; function FileExt: string; begin Result := Copy(APath, Length(APath) - 3, Length(APath)); end; begin Result := False; if FileExists(APath) then begin if (LowerCase(FileExt) = '.bmp') then begin Result := True; Bitmap.LoadFromFile(APath); end else if (LowerCase(FileExt) = '.png') then begin Result := True; FPNG := TPNGObject.Create; try FPNG.LoadFromFile(APath); Bitmap.Assign(FPNG); finally FPNG.Free; end; end else if (LowerCase(FileExt) = '.jpg') then begin Result := True; FJPG := TJpegImage.Create; try FJPG.LoadFromFile(APath); Bitmap.Assign(FJPG); finally FJPG.Free; end; end else if (LowerCase(FileExt) = '.gif') then begin Result := True; FGIF := TGIFImage.Create; try FGIF.LoadFromFile(APath); Bitmap.Assign(FGIF); finally FGIF.Free; end; end; end; end; procedure TImage.Split(const APath: string; var AImages: TImages; CellSize: Integer; ATransparent: Boolean = False); var I, J, U: Integer; FTemp: TBitmap; begin FTemp := Graphics.TBitmap.Create; try Load(APath, FTemp); SetLength(AImages, (FTemp.Width div CellSize) * (FTemp.Height div CellSize)); for I := 0 to Length(AImages) - 1 do AImages[I] := TBitmap.Create; U := 0; for J := 0 to (FTemp.Height div CellSize) - 1 do for I := 0 to (FTemp.Width div CellSize) - 1 do with AImages[U] do begin Width := CellSize; Height := CellSize; PixelFormat := pf24Bit; Canvas.CopyRect(Bounds(0, 0, CellSize, CellSize), FTemp.Canvas, Bounds(I * CellSize, J * CellSize, CellSize, CellSize)); Inc(U); end; if ATransparent then for I := 0 to High(AImages) do begin AImages[I].TransparentColor := AImages[I].Canvas.Pixels[1, 1]; AImages[I].Transparent := True; end; finally FTemp.Free; end; end; end.
unit FFSLENDGRPTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TFFSLENDGRPRecord = record PName: String[4]; PLender1: String[240]; PLender2: String[240]; PLender3: String[240]; PLender4: String[240]; PSearchable: Boolean; PDescription: String[40]; End; TFFSLENDGRPBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TFFSLENDGRPRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIFFSLENDGRP = (FFSLENDGRPPrimaryKey); TFFSLENDGRPTable = class( TDBISAMTableAU ) private FDFName: TStringField; FDFLender1: TStringField; FDFLender2: TStringField; FDFLender3: TStringField; FDFLender4: TStringField; FDFSearchable: TBooleanField; FDFDescription: TStringField; procedure SetPName(const Value: String); function GetPName:String; procedure SetPLender1(const Value: String); function GetPLender1:String; procedure SetPLender2(const Value: String); function GetPLender2:String; procedure SetPLender3(const Value: String); function GetPLender3:String; procedure SetPLender4(const Value: String); function GetPLender4:String; procedure SetPSearchable(const Value: Boolean); function GetPSearchable:Boolean; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetEnumIndex(Value: TEIFFSLENDGRP); function GetEnumIndex: TEIFFSLENDGRP; protected procedure CreateFields; override; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TFFSLENDGRPRecord; procedure StoreDataBuffer(ABuffer:TFFSLENDGRPRecord); property DFName: TStringField read FDFName; property DFLender1: TStringField read FDFLender1; property DFLender2: TStringField read FDFLender2; property DFLender3: TStringField read FDFLender3; property DFLender4: TStringField read FDFLender4; property DFSearchable: TBooleanField read FDFSearchable; property DFDescription: TStringField read FDFDescription; property PName: String read GetPName write SetPName; property PLender1: String read GetPLender1 write SetPLender1; property PLender2: String read GetPLender2 write SetPLender2; property PLender3: String read GetPLender3 write SetPLender3; property PLender4: String read GetPLender4 write SetPLender4; property PSearchable: Boolean read GetPSearchable write SetPSearchable; property PDescription: String read GetPDescription write SetPDescription; published property Active write SetActive; property EnumIndex: TEIFFSLENDGRP read GetEnumIndex write SetEnumIndex; end; { TFFSLENDGRPTable } procedure Register; implementation procedure TFFSLENDGRPTable.CreateFields; begin FDFName := CreateField( 'Name' ) as TStringField; FDFLender1 := CreateField( 'Lender1' ) as TStringField; FDFLender2 := CreateField( 'Lender2' ) as TStringField; FDFLender3 := CreateField( 'Lender3' ) as TStringField; FDFLender4 := CreateField( 'Lender4' ) as TStringField; FDFSearchable := CreateField( 'Searchable' ) as TBooleanField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TFFSLENDGRPTable.CreateFields } procedure TFFSLENDGRPTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TFFSLENDGRPTable.SetActive } procedure TFFSLENDGRPTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TFFSLENDGRPTable.GetPName:String; begin result := DFName.Value; end; procedure TFFSLENDGRPTable.SetPLender1(const Value: String); begin DFLender1.Value := Value; end; function TFFSLENDGRPTable.GetPLender1:String; begin result := DFLender1.Value; end; procedure TFFSLENDGRPTable.SetPLender2(const Value: String); begin DFLender2.Value := Value; end; function TFFSLENDGRPTable.GetPLender2:String; begin result := DFLender2.Value; end; procedure TFFSLENDGRPTable.SetPLender3(const Value: String); begin DFLender3.Value := Value; end; function TFFSLENDGRPTable.GetPLender3:String; begin result := DFLender3.Value; end; procedure TFFSLENDGRPTable.SetPLender4(const Value: String); begin DFLender4.Value := Value; end; function TFFSLENDGRPTable.GetPLender4:String; begin result := DFLender4.Value; end; procedure TFFSLENDGRPTable.SetPSearchable(const Value: Boolean); begin DFSearchable.Value := Value; end; function TFFSLENDGRPTable.GetPSearchable:Boolean; begin result := DFSearchable.Value; end; procedure TFFSLENDGRPTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TFFSLENDGRPTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TFFSLENDGRPTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Name, String, 4, N'); Add('Lender1, String, 240, N'); Add('Lender2, String, 240, N'); Add('Lender3, String, 240, N'); Add('Lender4, String, 240, N'); Add('Searchable, Boolean, 0, N'); Add('Description, String, 40, N'); end; end; procedure TFFSLENDGRPTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Name, Y, Y, N, N'); end; end; procedure TFFSLENDGRPTable.SetEnumIndex(Value: TEIFFSLENDGRP); begin case Value of FFSLENDGRPPrimaryKey : IndexName := ''; end; end; function TFFSLENDGRPTable.GetDataBuffer:TFFSLENDGRPRecord; var buf: TFFSLENDGRPRecord; begin fillchar(buf, sizeof(buf), 0); buf.PName := DFName.Value; buf.PLender1 := DFLender1.Value; buf.PLender2 := DFLender2.Value; buf.PLender3 := DFLender3.Value; buf.PLender4 := DFLender4.Value; buf.PSearchable := DFSearchable.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TFFSLENDGRPTable.StoreDataBuffer(ABuffer:TFFSLENDGRPRecord); begin DFName.Value := ABuffer.PName; DFLender1.Value := ABuffer.PLender1; DFLender2.Value := ABuffer.PLender2; DFLender3.Value := ABuffer.PLender3; DFLender4.Value := ABuffer.PLender4; DFSearchable.Value := ABuffer.PSearchable; DFDescription.Value := ABuffer.PDescription; end; function TFFSLENDGRPTable.GetEnumIndex: TEIFFSLENDGRP; begin //VG 220318: No checks because there are no other key types defined Result := FFSLENDGRPPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'FFS Tables', [ TFFSLENDGRPTable, TFFSLENDGRPBuffer ] ); end; { Register } function TFFSLENDGRPBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..7] of string = ('NAME','LENDER1','LENDER2','LENDER3','LENDER4','SEARCHABLE' ,'DESCRIPTION' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 7) and (flist[x] <> s) do inc(x); if x <= 7 then result := x else result := 0; end; function TFFSLENDGRPBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftBoolean; 7 : result := ftString; end; end; function TFFSLENDGRPBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PName; 2 : result := @Data.PLender1; 3 : result := @Data.PLender2; 4 : result := @Data.PLender3; 5 : result := @Data.PLender4; 6 : result := @Data.PSearchable; 7 : result := @Data.PDescription; end; end; end.
{ Subroutine SST_CALL (SYM) * * Create an opcode for a call to the subroutine is indicated by the * symbol SYM. } module sst_call; define sst_call; %include 'sst2.ins.pas'; procedure sst_call ( {create subroutine call opcode} in sym: sst_symbol_t); {symbol for name of subroutine to call} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if sym.symtype <> sst_symtype_proc_k then begin {symbol not a subroutine ?} sys_msg_parm_vstr (msg_parm[1], sym.name_in_p^); sys_message_bomb ('sst', 'symbol_not_subr_in_call', msg_parm, 1); end; sst_opcode_new; {create new opcode for subroutine call} sst_opc_p^.opcode := sst_opc_call_k; sst_opc_p^.call_proct_p := addr(sym.proc); { * Create "variable" reference to subroutine entry point and link * in to opcode. } sst_mem_alloc_scope (sizeof(sst_opc_p^.call_var_p^), sst_opc_p^.call_var_p); sst_opc_p^.call_var_p^.mod1.next_p := nil; sst_opc_p^.call_var_p^.mod1.modtyp := sst_var_modtyp_top_k; sst_opc_p^.call_var_p^.mod1.top_str_h := sst_opc_p^.str_h; sst_opc_p^.call_var_p^.mod1.top_sym_p := addr(sym); sst_opc_p^.call_var_p^.dtype_p := nil; sst_opc_p^.call_var_p^.rwflag := [sst_rwflag_read_k]; sst_opc_p^.call_var_p^.vtype := sst_vtype_rout_k; sst_opc_p^.call_var_p^.rout_proc_p := addr(sym.proc); { * Create initial called routine descriptor and link into opcode. * The descriptor will be initialized with no arguments. } sst_mem_alloc_scope (sizeof(sst_opc_p^.call_proc_p^), sst_opc_p^.call_proc_p); sst_opc_p^.call_proc_p^.sym_p := addr(sym); sst_opc_p^.call_proc_p^.dtype_func_p := nil; sst_opc_p^.call_proc_p^.n_args := 0; sst_opc_p^.call_proc_p^.flags := []; sst_opc_p^.call_proc_p^.first_arg_p := nil; end;
{ ---------------------------------------------------------------------------- zbnc - Multi user IRC bouncer Copyright (c) Michael "Zipplet" Nixon 2009. Licensed under the MIT license, see license.txt in the project trunk. Unit: compilets.pas Purpose: Implements compile timestamp support (along with writestamp) ---------------------------------------------------------------------------- } unit compilets; interface uses sysutils, btime; function compiletimestr: string; function compiletimesecondsdiff: integer; implementation const {$ifdef compiletime} {$include compiletime.inc} {$else} COMPILE_TIME: longint = 0; {$endif} function compiletimestr: string; var y, m, d, h, min, sec, ms: word; t: tdatetime; begin if compile_time = 0 then begin result := 'no compile time data'; end else begin btime.init; t := unixtoole(compile_time + timezone); decodedate(t, y, m, d); decodetime(t, h, min, sec, ms); result := inttostr(y) + '-' + inttostr(m div 10) + inttostr(m mod 10) + '-' + inttostr(d div 10) + inttostr(d mod 10) + ' ' + inttostr(h div 10) + inttostr(h mod 10) + ':' + inttostr(min div 10) + inttostr(min mod 10) + ' GMT' + timezonestr; end; end; function compiletimesecondsdiff: integer; begin if compile_time = 0 then begin result := 0; end else begin result := unixtimeint - compile_time; end; end; end.
unit cmdlinelazcompopt; {$mode delphi}{$H+} interface // this unit depends on IDEIntf package (CompOptsIntf.pas) ! uses Classes, SysUtils, CompOptsIntf, cmdlinecfg, cmdlinecfgutils, cmdlinecfgparser, contnrs; { Either procedures depends on a certain names/keys used for the FPC options. This has to be caferully maintained in the configuration file. } procedure LazCompOptToVals(opt: TLazCompilerOptions; cfg: TCmdLineCfg; list: TList {of TCmdLineValueOpts}); procedure ValsToLazCompOpt(list: TList {of TCmdLineValueOpts}; opt: TLazCompilerOptions); implementation // hash all values - make their copies and "join" multi values (if available) function AllocLookup(list: TList): TFPHashObjectList; var i : integer; v : TCmdLineOptionValue; lv : TCmdLineOptionValue; d : string; begin Result:=TFPHashObjectList.Create(true); for i:=0 to list.Count-1 do begin v:=TCmdLineOptionValue(list[i]); if not Assigned(v) or not Assigned(v.Option) then Continue; lv:=TCmdLineOptionValue(Result.Find(v.Option.Name)); if v.Option.isMultiple then begin if not Assigned(lv) then begin lv:=TCmdLineOptionValue.Create(v.Option, v.Value); Result.Add(v.Option.Name, lv); end else begin if (v.Option.OptType='filepath') or (v.Option.OptType='dirpath') then d:=';' else d:=' '; if lv.Value='' then lv.Value:=v.Value else lv.Value:=lv.Value+d+v.Value; end; end else begin if not Assigned(lv) then begin lv:=TCmdLineOptionValue.Create(v.Option, v.Value); Result.Add(v.Option.Name, lv); end else lv.Value:=v.Value; end; end; end; function LookupStr(lp: TFPHashObjectList; const Name: string; const Default: string = ''; Remove: Boolean = true): string; var v: TCmdLineOptionValue; i: integer; begin i:=lp.FindIndexOf(Name); if i>=0 then begin v:=TCmdLineOptionValue(lp.Items[i]); Result:=v.Value; if Remove then lp.Delete(i); // frees the object end else Result:=Default; end; function LookupBool(lp: TFPHashObjectList; const Name: string; const Default: Boolean = false; Remove: Boolean = true): Boolean; var v: TCmdLineOptionValue; i: integer; begin i:=lp.FindIndexOf(Name); if i>=0 then begin v:=TCmdLineOptionValue(lp.Items[i]); Result:=v.Value<>''; if Remove then lp.Delete(i); // frees the object end else Result:=Default; end; function LookupInt(lp: TFPHashObjectList; const Name: string; const Default: Integer = 0; Remove: Boolean = true): Integer; var v: TCmdLineOptionValue; i: integer; begin i:=lp.FindIndexOf(Name); if i>=0 then begin v:=TCmdLineOptionValue(lp.Items[i]); Result:=StrToIntDef(v.Value,Default); if Remove then lp.Delete(i); // frees the object end else Result:=Default; end; function StrToDbgSymbolType(const vals: string): TCompilerDbgSymbolType; var v : string; begin v:=AnsiLowerCase(vals); if v='s' then Result:=dsStabs else if v='w2' then Result:=dsDwarf2 else if v='w' then Result:=dsDwarf2Set // ??? else if v='w3' then Result:=dsDwarf3; end; procedure ValsToLazCompOpt(list: TList {of TCmdLineValueOpts}; opt: TLazCompilerOptions); var lookup : TFPHashObjectList; i : Integer; l : TList; begin lookup:=AllocLookup(list); try // search paths: opt.IncludePath:=LookupStr(lookup, '-Fi'); opt.Libraries:=LookupStr(lookup, '-Fl'); opt.ObjectPath:=LookupStr(lookup, '-Fo'); opt.OtherUnitFiles:=LookupStr(lookup, '-Fu'); //opt.SrcPath (not in compiler options) //opt.DebugPath opt.UnitOutputDirectory:=LookupStr(lookup, '-FU'); // target: opt.TargetFilename:=LookupStr(lookup, '-o'); //opt.TargetFilenameApplyConventions // parsing: opt.SyntaxMode:=LookupStr(lookup, '-M'); //property AssemblerStyle: Integer read fAssemblerStyle write SetAssemblerStyle; opt.CStyleOperators:=LookupBool(lookup, '-Sc'); opt.IncludeAssertionCode:=LookupBool(lookup, '-Sa'); opt.AllowLabel:=LookupBool(lookup,'-Sg'); opt.UseAnsiStrings:=LookupBool(lookup,'-Sh'); opt.CPPInline:=LookupBool(lookup,'-Si'); opt.CStyleMacros:=LookupBool(lookup,'-Sm'); opt.InitConstructor:=LookupBool(lookup,'-Ss'); // -St is obsolete option ... so shouldn't be available opt.StaticKeyword:=LookupBool(lookup,'-St'); // code generation: opt.IOChecks:=LookupBool(lookup,'-Ci'); opt.RangeChecks:=LookupBool(lookup,'-Cr'); opt.OverflowChecks:=LookupBool(lookup,'-Co'); opt.StackChecks:=LookupBool(lookup,'-Ct'); opt.SmartLinkUnit:=LookupBool(lookup,'-CX'); opt.RelocatableUnit:=LookupBool(lookup,'-WR'); opt.EmulatedFloatOpcodes:=LookupBool(lookup,'-Ce'); opt.HeapSize:=LookupInt(lookup, '-Ch'); opt.StackSize:=LookupInt(lookup, '-Cs'); opt.VerifyObjMethodCall:=LookupBool(lookup,'-CR'); opt.SmallerCode :=LookupBool(lookup, '-Os'); opt.TargetCPU :=LookupStr(lookup, '-P'); opt.TargetProcessor:=LookupStr(lookup, '-Op'); opt.TargetOS:=LookupStr(lookup, '-T'); opt.VariablesInRegisters:=LookupBool(lookup, '-Or'); opt.UncertainOptimizations:=LookupBool(lookup, '-Ou'); opt.OptimizationLevel:=StrToIntDef(LookupStr(lookup, '-O'),0); // linking: opt.GenerateDebugInfo:=LookupBool(lookup, '-g'); opt.DebugInfoType:=StrToDbgSymbolType(LookupStr(lookup, '-g')); //opt.DebugInfoTypeStr: String read GetDebugInfoTypeStr; opt.UseLineInfoUnit:=LookupBool(lookup, '-gl'); opt.UseHeaptrc:=LookupBool(lookup, '-gh'); opt.UseValgrind:=LookupBool(lookup, '-gv'); opt.GenGProfCode:=LookupBool(lookup, '-pg'); opt.StripSymbols:=LookupBool(lookup, '-Xs'); opt.LinkSmart:=LookupBool(lookup, '-XX'); opt.LinkerOptions:=LookupStr(lookup, '-k'); opt.PassLinkerOptions:=opt.LinkerOptions<>''; //todo:! opt.Win32GraphicApp:=LookupBool(lookup, '-WG'); //ExecutableType: TCompilationExecutableType read FExecutableType write SetExecutableType; opt.UseExternalDbgSyms:=LookupBool(lookup, '-Xg'); // messages: opt.ShowErrors:=LookupBool(lookup, '-ve'); opt.ShowWarn:=LookupBool(lookup, '-vw'); opt.ShowNotes:=LookupBool(lookup, '-vn'); opt.ShowHints:=LookupBool(lookup, '-vh'); opt.ShowGenInfo:=LookupBool(lookup, '-vi'); opt.ShowLineNum:=LookupBool(lookup, '-vl'); opt.ShowAll:=LookupBool(lookup, '-va'); opt.ShowAllProcsOnError:=LookupBool(lookup, '-Xs'); opt.ShowDebugInfo:=LookupBool(lookup, '-vd'); opt.ShowUsedFiles:=LookupBool(lookup, '-vu'); opt.ShowTriedFiles:=LookupBool(lookup, '-vt'); opt.ShowCompProc:=LookupBool(lookup, '-vp'); opt.ShowCond:=LookupBool(lookup, '-vc'); opt.ShowExecInfo:=LookupBool(lookup, '-vx'); opt.ShowNothing:=LookupBool(lookup, '-v0'); //opt.ShowSummary //opt.ShowHintsForUnusedUnitsInMainSrc //opt.ShowHintsForSenderNotUsed opt.WriteFPCLogo:=LookupBool(lookup, '-l'); opt.StopAfterErrCount:=LookupInt(lookup, '-Se'); // other opt.DontUseConfigFile:=LookupBool(lookup, '-n'); //opt.ConfigFilePath:=LookupStr(lookup, '@'); //opt.CustomConfigFile:=opt.ConfigFilePath<>''; if lookup.Count>0 then begin l:=TList.Create; try for i:=0 to lookup.Count-1 do l.Add(lookup.Items[i]); opt.CustomOptions:=CmdLineMakeOptions(l); finally l.Free; // values, will be freed with lookup end; end; finally lookup.Free; end; end; procedure AddBoolValue(cfg: TCmdLineCfg; const Key: string; AVal: Boolean; list: TList; var Other: string); var o : TCmdLineCfgOption; begin if not AVal then Exit; o:=cfg.FindOption(Key); if Assigned(o) then list.Add(TCmdLineOptionValue.Create(o, '1')); end; procedure AddStrValue(cfg: TCmdLineCfg; const Key, AVal: string; list: TList; var Other: string); var o : TCmdLineCfgOption; begin if AVal='' then Exit; o:=cfg.FindOption(Key); if Assigned(o) then list.Add(TCmdLineOptionValue.Create(o, AVal)); end; procedure AddIntValue(cfg: TCmdLineCfg; const Key: string; AVal: Integer; list: TList; var Other: string); var o : TCmdLineCfgOption; begin if AVal<=0 then Exit; o:=cfg.FindOption(Key); if Assigned(o) then list.Add(TCmdLineOptionValue.Create(o, IntToStr(AVal))); end; procedure AddMultiStrValue(cfg: TCmdLineCfg; const Key, AVal, Delim: string; list: TList; var Other: string); var o : TCmdLineCfgOption; ch : Char; begin if AVal='' then Exit; o:=cfg.FindOption(Key); if Assigned(o) then begin if length(DElim)>0 then ch:=Delim[1] else ch:=#0; CmdLineAllocMultiValues(o, AVal, ch, list); end; end; procedure LazCompOptToVals(opt: TLazCompilerOptions; cfg: TCmdLineCfg; list: TList {of TCmdLineValueOpts}); var other : string; begin other := ''; AddMultiStrValue(cfg, '-Fi', opt.IncludePath, ';', list, Other); AddMultiStrValue(cfg, '-Fl', opt.Libraries, ';', list, Other); AddMultiStrValue(cfg, '-Fo', opt.ObjectPath, ';', list, Other); AddMultiStrValue(cfg, '-Fu', opt.OtherUnitFiles, ';', list, Other); // opt.SrcPath (not in compiler options) ?? -sources for Lazarus itself? //opt.DebugPath AddStrValue(cfg, '-FU', opt.UnitOutputDirectory, list, other); // target: AddStrValue(cfg, '-o', opt.TargetFilename, list, other); // parsing: AddStrValue(cfg, '-M', opt.UnitOutputDirectory, list, other); //property AssemblerStyle: Integer read fAssemblerStyle write SetAssemblerStyle; AddBoolValue(cfg, '-Sc', opt.CStyleOperators, list, other); AddBoolValue(cfg, '-Sa', opt.IncludeAssertionCode, list, other); AddBoolValue(cfg, '-Sg', opt.AllowLabel, list, other); AddBoolValue(cfg, '-Sh', opt.UseAnsiStrings, list, other); AddBoolValue(cfg, '-Si', opt.CPPInline, list, other); AddBoolValue(cfg, '-Sm', opt.CStyleMacros, list, other); AddBoolValue(cfg, '-Ss', opt.InitConstructor, list, other); // -St is obsolete option ... so shouldn't be available AddBoolValue(cfg, '-St', opt.StaticKeyword, list, other); // code generation: AddBoolValue(cfg, '-Ci', opt.IOChecks, list, other); AddBoolValue(cfg, '-Cr', opt.RangeChecks, list, other); AddBoolValue(cfg, '-Co', opt.OverflowChecks, list, other); AddBoolValue(cfg, '-Ct', opt.StackChecks, list, other); AddBoolValue(cfg, '-CX', opt.SmartLinkUnit, list, other); AddBoolValue(cfg, '-WR', opt.RelocatableUnit, list, other); AddBoolValue(cfg, '-Ce', opt.EmulatedFloatOpcodes, list, other); AddIntValue(cfg, '-Ch', opt.HeapSize, list, other); AddIntValue(cfg, '-Cs', opt.StackSize, list, other); AddBoolValue(cfg, '-CR', opt.VerifyObjMethodCall, list, other); AddBoolValue(cfg, '-CR', opt.SmallerCode, list, other); AddStrValue(cfg, '-P', opt.TargetCPU, list, other); AddStrValue(cfg, '-Op', opt.TargetProcessor, list, other); AddStrValue(cfg, '-T', opt.TargetOS, list, other); AddBoolValue(cfg, '-Or', opt.VariablesInRegisters, list, other); AddBoolValue(cfg, '-Ou', opt.UncertainOptimizations, list, other); AddStrValue(cfg, '-O', IntToStr(opt.OptimizationLevel), list, other); // linking: AddBoolValue(cfg, '-g', opt.GenerateDebugInfo, list, other); //todo: EPIC TODO //AddStrValue(cfg, '-g', opt.DebugInfoType, list, other); //opt.DebugInfoTypeStr: String read GetDebugInfoTypeStr; AddBoolValue(cfg, '-gl', opt.UseLineInfoUnit, list, other); AddBoolValue(cfg, '-gh', opt.UseHeaptrc, list, other); AddBoolValue(cfg, '-gv', opt.UseValgrind, list, other); AddBoolValue(cfg, '-pg', opt.GenGProfCode, list, other); AddBoolValue(cfg, '-Xs', opt.StripSymbols, list, other); AddBoolValue(cfg, '-XX', opt.LinkSmart, list, other); AddMultiStrValue(cfg, '-k', opt.LinkerOptions, ' ', list, other); {opt.LinkerOptions:=LookupStr(lookup, '-k'); opt.PassLinkerOptions:=opt.LinkerOptions<>''; //todo:!} AddBoolValue(cfg, '-WG', opt.Win32GraphicApp, list, other); //ExecutableType: TCompilationExecutableType read FExecutableType write SetExecutableType; AddBoolValue(cfg, '-Xg', opt.UseExternalDbgSyms, list, other); // messages: AddBoolValue(cfg, '-ve', opt.ShowErrors, list, other); AddBoolValue(cfg, '-vw', opt.ShowWarn, list, other); AddBoolValue(cfg, '-vn', opt.ShowNotes, list, other); AddBoolValue(cfg, '-vh', opt.ShowHints, list, other); AddBoolValue(cfg, '-vi', opt.ShowGenInfo, list, other); AddBoolValue(cfg, '-vl', opt.ShowLineNum, list, other); AddBoolValue(cfg, '-va', opt.ShowAll, list, other); AddBoolValue(cfg, '-Xs', opt.ShowAllProcsOnError, list, other); AddBoolValue(cfg, '-vd', opt.ShowDebugInfo, list, other); AddBoolValue(cfg, '-vu', opt.ShowUsedFiles, list, other); AddBoolValue(cfg, '-vt', opt.ShowTriedFiles, list, other); AddBoolValue(cfg, '-vp', opt.ShowCompProc, list, other); AddBoolValue(cfg, '-vc', opt.ShowCond, list, other); AddBoolValue(cfg, '-vx', opt.ShowExecInfo, list, other); AddBoolValue(cfg, '-v0', opt.ShowNothing, list, other); //opt.ShowSummary //opt.ShowHintsForUnusedUnitsInMainSrc //opt.ShowHintsForSenderNotUsed AddBoolValue(cfg, '-l' , opt.WriteFPCLogo, list, other); AddIntValue(cfg, '-Se', opt.StopAfterErrCount, list, other); // other AddBoolValue(cfg, '-n', opt.DontUseConfigFile, list, other); CmdLineMatchArgsToOpts(cfg, opt.CustomOptions, list); end; end.
unit TestWSInvokers; {$mode objfpc}{$H+} interface uses typinfo, Classes, fpcunit, JCoreWSInvokers; type { TTestWSMethodData } TTestWSMethodData = class(TTestCase) private FMethodData: TJCoreWSMethodData; procedure P01; procedure P02(AObject: TObject); procedure P03(var AObject: TObject); procedure P04(const AObject: TObject); procedure P05(const AObject: TInterfacedObject); procedure P06(const AObject: TObject; const AMsg: string); procedure P07(const AObject: TObject); cdecl; procedure P08(const APersistent: TPersistent; const AList: TList; const AString: string); function F01: TObject; function F02: TInterfacedObject; function F03: string; function F04(const AObject: TObject): string; function F05(const AMsg: string): TObject; function F06(const AMsg1, AMsg2: string): TObject; function F07(const AMsg: string): TObject; cdecl; function F08(const APersistent: TPersistent; const AList: TList; const AString: string): Boolean; protected procedure TearDown; override; function CreateMethodData(const AMethodTypeInfo: PTypeInfo): TJCoreWSMethodData; published procedure ValidP01; procedure ValidP02; procedure ValidP03; procedure ValidP04; procedure ValidP05; procedure ValidP06; procedure ValidP07; procedure ValidP08; procedure ValidF01; procedure ValidF02; procedure ValidF03; procedure ValidF04; procedure ValidF05; procedure ValidF06; procedure ValidF07; procedure ValidF08; procedure InvalidTypeInfo; procedure IsProcedureConstObject; procedure IsFunctionAsObject; procedure IsProcedureThreeParams; procedure IsFunctionThreeParamsAsBoolean; end; implementation uses sysutils, testregistry, JCoreClasses; { TTestWSMethodData } procedure TTestWSMethodData.P01; begin end; procedure TTestWSMethodData.P02(AObject: TObject); begin end; procedure TTestWSMethodData.P03(var AObject: TObject); begin end; procedure TTestWSMethodData.P04(const AObject: TObject); begin end; procedure TTestWSMethodData.P05(const AObject: TInterfacedObject); begin end; procedure TTestWSMethodData.P06(const AObject: TObject; const AMsg: string); begin end; procedure TTestWSMethodData.P07(const AObject: TObject); cdecl; begin end; procedure TTestWSMethodData.P08(const APersistent: TPersistent; const AList: TList; const AString: string); begin end; function TTestWSMethodData.F01: TObject; begin Result := nil; end; function TTestWSMethodData.F02: TInterfacedObject; begin Result := nil; end; function TTestWSMethodData.F03: string; begin Result := ''; end; function TTestWSMethodData.F04(const AObject: TObject): string; begin Result := ''; end; function TTestWSMethodData.F05(const AMsg: string): TObject; begin Result := nil; end; function TTestWSMethodData.F06(const AMsg1, AMsg2: string): TObject; begin Result := nil; end; function TTestWSMethodData.F07(const AMsg: string): TObject; cdecl; begin Result := nil; end; function TTestWSMethodData.F08(const APersistent: TPersistent; const AList: TList; const AString: string): Boolean; begin Result := False; end; procedure TTestWSMethodData.TearDown; begin inherited TearDown; FreeAndNil(FMethodData); end; function TTestWSMethodData.CreateMethodData(const AMethodTypeInfo: PTypeInfo): TJCoreWSMethodData; begin FreeAndNil(FMethodData); FMethodData := TJCoreWSMethodData.Create(AMethodTypeInfo); Result := FMethodData; end; procedure TTestWSMethodData.ValidP01; var VMethod: TJCoreWSMethodData; begin //procedure P01; VMethod := CreateMethodData(TypeInfo(@P01)); AssertEquals('type', Ord(mkProcedure), Ord(VMethod.MethodKind)); AssertEquals('param count', 0, Length(VMethod.Params)); AssertEquals('call conv', Ord(ccReg), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidP02; var VMethod: TJCoreWSMethodData; begin //procedure P02(AObject: TObject); VMethod := CreateMethodData(TypeInfo(@P02)); AssertEquals('type', Ord(mkProcedure), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertFalse('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertFalse('param[0] flag var', pfVar in VMethod.Params[0].Flags); AssertEquals('param[0] name', 'AObject', VMethod.Params[0].ParamName); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertEquals('call conv', Ord(ccReg), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidP03; var VMethod: TJCoreWSMethodData; begin //procedure P03(var AObject: TObject); VMethod := CreateMethodData(TypeInfo(@P03)); AssertEquals('type', Ord(mkProcedure), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag var', pfVar in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertEquals('call conv', Ord(ccReg), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidP04; var VMethod: TJCoreWSMethodData; begin //procedure P04(const AObject: TObject); VMethod := CreateMethodData(TypeInfo(@P04)); AssertEquals('type', Ord(mkProcedure), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); end; procedure TTestWSMethodData.ValidP05; var VMethod: TJCoreWSMethodData; begin //procedure P05(const AObject: TInterfacedObject); VMethod := CreateMethodData(TypeInfo(@P05)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TInterfacedObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); end; procedure TTestWSMethodData.ValidP06; var VMethod: TJCoreWSMethodData; begin //procedure P06(const AObject: TObject; const AMsg: string); VMethod := CreateMethodData(TypeInfo(@P06)); AssertEquals('param count', 2, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertTrue('param[1] flag const', pfConst in VMethod.Params[1].Flags); AssertEquals('param[1] name', 'AMsg', VMethod.Params[1].ParamName); AssertEquals('param[1] kind', Ord(tkAString), Ord(VMethod.Params[1].ParamTypeInfo^.Kind)); end; procedure TTestWSMethodData.ValidP07; var VMethod: TJCoreWSMethodData; begin //procedure P07(const AObject: TObject); cdecl; VMethod := CreateMethodData(TypeInfo(@P07)); AssertEquals('type', Ord(mkProcedure), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertEquals('call conv', Ord(ccCdecl), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidP08; var VMethod: TJCoreWSMethodData; begin //procedure P08(const APersistent: TPersistent; const AList: TList; const AString: string); VMethod := CreateMethodData(TypeInfo(@P08)); AssertEquals('type', Ord(mkProcedure), Ord(VMethod.MethodKind)); AssertEquals('param count', 3, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TPersistent, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertTrue('param[1] flag const', pfConst in VMethod.Params[1].Flags); AssertEquals('param[1] kind', Ord(tkClass), Ord(VMethod.Params[1].ParamTypeInfo^.Kind)); AssertEquals('param[1] type', TList, GetTypeData(VMethod.Params[1].ParamTypeInfo)^.ClassType); AssertTrue('param[2] flag const', pfConst in VMethod.Params[2].Flags); AssertEquals('param[2] kind', Ord(tkAString), Ord(VMethod.Params[2].ParamTypeInfo^.Kind)); AssertEquals('call conv', Ord(ccReg), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidF01; var VMethod: TJCoreWSMethodData; begin //function F01: TObject; VMethod := CreateMethodData(TypeInfo(@F01)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 0, Length(VMethod.Params)); AssertEquals('result kind', Ord(tkClass), Ord(VMethod.ResultType^.Kind)); AssertEquals('result type', TObject, GetTypeData(VMethod.ResultType)^.ClassType); AssertEquals('call conv', Ord(ccReg), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidF02; var VMethod: TJCoreWSMethodData; begin //function F02: TInterfacedObject; VMethod := CreateMethodData(TypeInfo(@F02)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 0, Length(VMethod.Params)); AssertEquals('result kind', Ord(tkClass), Ord(VMethod.ResultType^.Kind)); AssertEquals('result type', TInterfacedObject, GetTypeData(VMethod.ResultType)^.ClassType); end; procedure TTestWSMethodData.ValidF03; var VMethod: TJCoreWSMethodData; begin //function F03: string; VMethod := CreateMethodData(TypeInfo(@F03)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 0, Length(VMethod.Params)); AssertEquals('result kind', Ord(tkAString), Ord(VMethod.ResultType^.Kind)); end; procedure TTestWSMethodData.ValidF04; var VMethod: TJCoreWSMethodData; begin //function F04(const AObject: TObject): string; VMethod := CreateMethodData(TypeInfo(@F04)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] name', 'AObject', VMethod.Params[0].ParamName); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TObject, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertEquals('result kind', Ord(tkAString), Ord(VMethod.ResultType^.Kind)); end; procedure TTestWSMethodData.ValidF05; var VMethod: TJCoreWSMethodData; begin //function F05(const AMsg: string): TObject; VMethod := CreateMethodData(TypeInfo(@F05)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] name', 'AMsg', VMethod.Params[0].ParamName); AssertEquals('param[0] kind', Ord(tkAString), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('result kind', Ord(tkClass), Ord(VMethod.ResultType^.Kind)); AssertEquals('result type', TObject, GetTypeData(VMethod.ResultType)^.ClassType); end; procedure TTestWSMethodData.ValidF06; var VMethod: TJCoreWSMethodData; begin //function F06(const AMsg1, AMsg2: string): TObject; VMethod := CreateMethodData(TypeInfo(@F06)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 2, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] name', 'AMsg1', VMethod.Params[0].ParamName); AssertEquals('param[0] kind', Ord(tkAString), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertTrue('param[1] flag const', pfConst in VMethod.Params[1].Flags); AssertEquals('param[1] name', 'AMsg2', VMethod.Params[1].ParamName); AssertEquals('param[1] kind', Ord(tkAString), Ord(VMethod.Params[1].ParamTypeInfo^.Kind)); AssertEquals('result kind', Ord(tkClass), Ord(VMethod.ResultType^.Kind)); AssertEquals('result type', TObject, GetTypeData(VMethod.ResultType)^.ClassType); end; procedure TTestWSMethodData.ValidF07; var VMethod: TJCoreWSMethodData; begin //function F07(const AMsg: string): TObject; cdecl; VMethod := CreateMethodData(TypeInfo(@F07)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 1, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkAString), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('result kind', Ord(tkClass), Ord(VMethod.ResultType^.Kind)); AssertEquals('result type', TObject, GetTypeData(VMethod.ResultType)^.ClassType); AssertEquals('call conv', Ord(ccCdecl), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.ValidF08; var VMethod: TJCoreWSMethodData; begin //function F08(const APersistent: TPersistent; const AList: TList; const AString: string): Boolean; VMethod := CreateMethodData(TypeInfo(@F08)); AssertEquals('type', Ord(mkFunction), Ord(VMethod.MethodKind)); AssertEquals('param count', 3, Length(VMethod.Params)); AssertTrue('param[0] flag const', pfConst in VMethod.Params[0].Flags); AssertEquals('param[0] kind', Ord(tkClass), Ord(VMethod.Params[0].ParamTypeInfo^.Kind)); AssertEquals('param[0] type', TPersistent, GetTypeData(VMethod.Params[0].ParamTypeInfo)^.ClassType); AssertTrue('param[1] flag const', pfConst in VMethod.Params[1].Flags); AssertEquals('param[1] kind', Ord(tkClass), Ord(VMethod.Params[1].ParamTypeInfo^.Kind)); AssertEquals('param[1] type', TList, GetTypeData(VMethod.Params[1].ParamTypeInfo)^.ClassType); AssertTrue('param[2] flag const', pfConst in VMethod.Params[2].Flags); AssertEquals('param[2] kind', Ord(tkAString), Ord(VMethod.Params[2].ParamTypeInfo^.Kind)); AssertEquals('result kind', Ord(tkBool), Ord(VMethod.ResultType^.Kind)); AssertEquals('call conv', Ord(ccReg), Ord(VMethod.CConv)); end; procedure TTestWSMethodData.InvalidTypeInfo; begin try CreateMethodData(TypeInfo(string)); Fail('EJCoreWS(3103) expected'); except on E: EJCoreWS do if E.Code <> 3103 then raise; end; end; procedure TTestWSMethodData.IsProcedureConstObject; var VMethod: TJCoreWSMethodData; begin //procedure P04(const AObject: TObject); VMethod := CreateMethodData(TypeInfo(@P04)); AssertTrue(VMethod.MatchProcedure([TObject])); end; procedure TTestWSMethodData.IsFunctionAsObject; var VMethod: TJCoreWSMethodData; begin //function F01: TObject; VMethod := CreateMethodData(TypeInfo(@F01)); AssertTrue(VMethod.MatchFunction([], TObject)); end; procedure TTestWSMethodData.IsProcedureThreeParams; var VMethod: TJCoreWSMethodData; begin //procedure P08(const APersistent: TPersistent; const AList: TList; const AString: string); VMethod := CreateMethodData(TypeInfo(@P08)); AssertTrue(VMethod.MatchProcedure([TPersistent, TList, tkAString])); end; procedure TTestWSMethodData.IsFunctionThreeParamsAsBoolean; var VMethod: TJCoreWSMethodData; begin //function F08(const APersistent: TPersistent; const AList: TList; const AString: string): Boolean; VMethod := CreateMethodData(TypeInfo(@F08)); AssertTrue(VMethod.MatchFunction([TPersistent, TList, tkAString], tkBool)); end; initialization RegisterTest('jcore.ws.invokers', TTestWSMethodData); end.
unit UpdateTerritoryUnit; interface uses SysUtils, BaseExampleUnit; type TUpdateTerritory = class(TBaseExample) public procedure Execute(TerritoryId: String); end; implementation uses TerritoryUnit, TerritoryContourUnit; procedure TUpdateTerritory.Execute(TerritoryId: String); var ErrorString: String; Territory: TTerritory; TerritoryContour: TTerritoryContour; NewTerritory: TTerritory; TerritoryName, TerritoryColor: String; begin TerritoryName := 'Test Territory Updated'; TerritoryColor := 'ff00ff'; TerritoryContour := TerritoryContour.MakeCircleContour( 38.4132225905681, -78.501953234, 3000); Territory := TTerritory.Create(TerritoryName, TerritoryColor, TerritoryContour); try Territory.Id := TerritoryId; NewTerritory := Route4MeManager.Territory.Update(Territory, ErrorString); try WriteLn(''); if (NewTerritory <> nil) then begin WriteLn('UpdateTerritory executed successfully'); WriteLn(Format('Territory ID: %s', [NewTerritory.Id.Value])); end else WriteLn(Format('UpdateTerritory error: "%s"', [ErrorString])); finally FreeAndNil(NewTerritory); end; finally FreeAndNil(Territory); end; end; end.
unit ExampleBehaviorNodes; interface uses System.JSON, Vcl.Graphics, Behavior3.Project, Behavior3.Core.Condition,Behavior3.Core.Action, Behavior3.Core.Tick, Behavior3; type TB3IsMouseOver = class(TB3Condition) public constructor Create; override; function Tick(Tick: TB3Tick): TB3Status; override; end; TB3ChangeColor = class(TB3Action) public Color: TColor; constructor Create; override; procedure Load(JsonNode: TJSONValue); override; function Tick(Tick: TB3Tick): TB3Status; override; end; TB3ChangePosition = class(TB3Action) public constructor Create; override; function Tick(Tick: TB3Tick): TB3Status; override; end; implementation { TB3IsMouseOver } uses System.Types, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms; constructor TB3IsMouseOver.Create; begin inherited; Name := 'IsMouseOver'; end; function TB3IsMouseOver.Tick(Tick: TB3Tick): TB3Status; var Shape: TShape; ParentForm: TForm; Point: TPoint; begin Shape := Tick.Target as TShape; ParentForm := Shape.Parent as TForm; Point := ParentForm.ScreenToClient(Mouse.CursorPos); if Shape.BoundsRect.Contains(Point) then Result := Behavior3.Success else Result := Behavior3.Failure; end; { TB3ChangeColor } constructor TB3ChangeColor.Create; begin inherited; Name := 'ChangeColor'; end; procedure TB3ChangeColor.Load(JsonNode: TJSONValue); var ColorName: String; begin inherited; ColorName := LoadProperty(JsonNode, 'color', 'purple'); Color := StringToColor('cl' + ColorName); end; function TB3ChangeColor.Tick(Tick: TB3Tick): TB3Status; var Shape: TShape; begin Shape := Tick.Target as TShape; Shape.Brush.Color := Color; Result := Behavior3.Success; end; { TB3ChangePosition } constructor TB3ChangePosition.Create; begin inherited; Name := 'ChangePosition'; end; function TB3ChangePosition.Tick(Tick: TB3Tick): TB3Status; var Shape: TShape; ParentForm: TForm; begin Shape := Tick.Target as TShape; ParentForm := Shape.Parent as TForm; Shape.Left := Random(ParentForm.ClientWidth - Shape.Width); Shape.Top := Random(ParentForm.ClientHeight - Shape.Height); Result := Behavior3.Success; end; end.
{ ************************************************************* www: http://sourceforge.net/projects/alcinoe/ svn: svn checkout svn://svn.code.sf.net/p/alcinoe/code/ alcinoe-code Author(s): Stéphane Vander Clock (alcinoe@arkadia.com) Sponsor(s): Arkadia SA (http://www.arkadia.com) product: Alcinoe Winsock Functions Version: 4.00 Description: Misc function that use winsock (for exempple ALHostToIP, ALIPAddrToName or ALgetLocalIPs) Legal issues: Copyright (C) 1999-2013 by Arkadia Software Engineering This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Know bug : History : 26/06/2012: Add xe2 support Link : * Please send all your feedback to alcinoe@arkadia.com * If you have downloaded this source from a website different from sourceforge.net, please get the last version on http://sourceforge.net/projects/alcinoe/ * Please, help us to keep the development of these components free by promoting the sponsor on http://static.arkadia.com/html/alcinoe_like.html ************************************************************** } unit ALWinSock; interface {$IF CompilerVersion >= 25} { Delphi XE4 } {$LEGACYIFEND ON} // http://docwiki.embarcadero.com/RADStudio/XE4/en/Legacy_IFEND_(Delphi) {$IFEND} uses AlStringList; function ALHostToIP(HostName: AnsiString; var Ip: AnsiString): Boolean; function ALIPAddrToName(IPAddr: AnsiString): AnsiString; function ALgetLocalIPs: TALStrings; function ALgetLocalHostName: AnsiString; implementation uses {$IF CompilerVersion >= 23} {Delphi XE2} Winapi.Windows, System.SysUtils, Winapi.WinSock2, {$IF CompilerVersion >= 24}{Delphi XE3} System.Ansistrings, {$IFEND} {$ELSE} Windows, SysUtils, WinSock, {$IFEND} ALString; { ********************************************************************* } function ALHostToIP(HostName: AnsiString; var Ip: AnsiString): Boolean; var WSAData: TWSAData; hostEnt: PHostEnt; addr: PAnsiChar; begin if WSAStartup(MAKEWORD(2, 2), WSAData) <> 0 then raiseLastOsError; try hostEnt := gethostbyname(PAnsiChar(HostName)); if Assigned(hostEnt) then begin if Assigned(hostEnt^.h_addr_list) then begin addr := hostEnt^.h_addr_list^; if Assigned(addr) then begin Ip := ALFormat('%d.%d.%d.%d', [byte(addr[0]), byte(addr[1]), byte(addr[2]), byte(addr[3])]); Result := True; end else Result := False; end else Result := False end else Result := False; finally WSACleanup; end end; { ******************************************************* } function ALIPAddrToName(IPAddr: AnsiString): AnsiString; var SockAddrIn: TSockAddrIn; hostEnt: PHostEnt; WSAData: TWSAData; begin if WSAStartup(MAKEWORD(2, 2), WSAData) <> 0 then raiseLastOsError; Try SockAddrIn.sin_addr.s_addr := inet_addr(PAnsiChar(IPAddr)); hostEnt := gethostbyaddr(@SockAddrIn.sin_addr.s_addr, 4, AF_INET); if hostEnt <> nil then Result := {$IF CompilerVersion >= 24}{ Delphi XE3 } System. Ansistrings.{$IFEND}StrPas(hostEnt^.h_name) else Result := ''; finally WSACleanup; end; end; { ********************************* } function ALgetLocalIPs: TALStrings; type TaPInAddr = array [0 .. 10] of PInAddr; PaPInAddr = ^TaPInAddr; var phe: PHostEnt; pptr: PaPInAddr; Buffer: array [0 .. 255] of AnsiChar; I: Integer; WSAData: TWSAData; begin if WSAStartup(MAKEWORD(2, 2), WSAData) <> 0 then raiseLastOsError; Try Result := TALStringList.Create; Result.Clear; GetHostName(Buffer, SizeOf(Buffer)); phe := gethostbyname(Buffer); if phe = nil then Exit; pptr := PaPInAddr(phe^.h_addr_list); I := 0; while pptr^[I] <> nil do begin Result.Add(inet_ntoa(pptr^[I]^)); Inc(I); end; finally WSACleanup; end; end; { *************************************** } function ALgetLocalHostName: AnsiString; var Buffer: array [0 .. 255] of AnsiChar; WSAData: TWSAData; begin if WSAStartup(MAKEWORD(2, 2), WSAData) <> 0 then raiseLastOsError; Try if GetHostName(Buffer, SizeOf(Buffer)) <> 0 then raise EALException.Create('Winsock GetHostName failed'); Result := {$IF CompilerVersion >= 24}{ Delphi XE3 } System. Ansistrings.{$IFEND}StrPas(Buffer); finally WSACleanup; end; end; end.
unit MFichas.Model.Empresa.Interfaces; interface uses System.Generics.Collections, MFichas.Model.Entidade.EMPRESA, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.DataSet.interfaces, FireDAC.Comp.Client; type iModelEmpresa = interface; iModelEmpresaMetodos = interface; iModelEmpresaMetodosEditarView = interface; iModelEmpresaMetodosBuscarModel = interface; iModelEmpresaMetodosBuscarView = interface; iModelEmpresa = interface ['{CCD68DC9-037A-4D2E-A58C-E4CEB5349B60}'] function Metodos : iModelEmpresaMetodos; function DAO : iContainerObjectSet<TEMPRESA>; function DAODataSet: iContainerDataSet<TEMPRESA>; end; iModelEmpresaMetodos = interface ['{F4145C48-8209-43E8-A388-C0359E62558F}'] function BuscarModel: iModelEmpresaMetodosBuscarModel; function EditarView : iModelEmpresaMetodosEditarView; function BuscarView : iModelEmpresaMetodosBuscarView; function &End : iModelEmpresa; end; iModelEmpresaMetodosBuscarModel = interface ['{070A5592-6D5D-41CC-884F-2757C8E7C9FE}'] function NomeDaEmpresa: String; function &End : iModelEmpresaMetodos; end; iModelEmpresaMetodosEditarView = interface ['{3FD6FD21-EF3A-4D8F-9785-7FCC7B097311}'] function Descricao(ANomeEmpresa: String): iModelEmpresaMetodosEditarView; function LogoTipo(ALogoEmpresa: String) : iModelEmpresaMetodosEditarView; function &End : iModelEmpresaMetodos; end; iModelEmpresaMetodosBuscarView = interface ['{09CFFA6C-2D8F-4F2E-8D5F-5951BA2209F4}'] function FDMemTable(AFDMemTable: TFDMemTable): iModelEmpresaMetodosBuscarView; function BuscarEmpresa : iModelEmpresaMetodosBuscarView; function &End : iModelEmpresaMetodos; end; implementation end.
unit ScriptClasses_C; { Inno Setup Copyright (C) 1997-2011 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Script support classes (compile time) $Id: ScriptClasses_C.pas,v 1.69 2012/02/05 18:59:23 mlaan Exp $ } interface {$I VERSION.INC} uses uPSCompiler; procedure ScriptClassesLibraryRegister_C(Cl: TPSPascalCompiler); implementation uses SetupTypes, uPSC_std, uPSC_classes, uPSC_graphics, uPSC_controls, uPSC_stdctrls, uPSC_forms, uPSC_extctrls, uPSC_comobj; procedure RegisterWinControl_C(Cl: TPSPascalCompiler); begin SIRegisterTWinControl(Cl); with Cl.FindClass('TWinControl') do begin RegisterProperty('ParentBackground', 'Boolean', iptrw); end; end; procedure RegisterNewStaticText_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TWinControl'), 'TNewStaticText') do begin RegisterMethod('function AdjustHeight: Integer'); RegisterProperty('AutoSize', 'Boolean', iptrw); RegisterProperty('Caption', 'String', iptrw); RegisterProperty('Color', 'TColor', iptrw); RegisterProperty('FocusControl', 'TWinControl', iptrw); RegisterProperty('Font', 'TFont', iptrw); RegisterProperty('ParentColor', 'Boolean', iptrw); RegisterProperty('ParentFont', 'Boolean', iptrw); RegisterProperty('ShowAccelChar', 'Boolean', iptrw); RegisterProperty('WordWrap', 'Boolean', iptrw); RegisterProperty('OnClick', 'TNotifyEvent', iptrw); RegisterProperty('OnDblClick', 'TNotifyEvent', iptrw); {$IFNDEF PS_MINIVCL} RegisterProperty('DragCursor', 'Longint', iptrw); RegisterProperty('DragMode', 'TDragMode', iptrw); RegisterProperty('ParentShowHint', 'Boolean', iptrw); RegisterProperty('PopupMenu', 'TPopupMenu', iptrw); RegisterProperty('OnDragDrop', 'TDragDropEvent', iptrw); RegisterProperty('OnDragOver', 'TDragOverEvent', iptrw); RegisterProperty('OnEndDrag', 'TEndDragEvent', iptrw); RegisterProperty('OnMouseDown', 'TMouseEvent', iptrw); RegisterProperty('OnMouseMove', 'TMouseMoveEvent', iptrw); RegisterProperty('OnMouseUp', 'TMouseEvent', iptrw); RegisterProperty('OnStartDrag', 'TStartDragEvent', iptrw); {$ENDIF} end; end; procedure RegisterNewCheckListBox_C(Cl: TPSPascalCompiler); begin Cl.AddTypeS('TCheckItemOperation', '(coUncheck, coCheck, coCheckWithChildren)'); with Cl.AddClassN(Cl.FindClass('TCustomListBox'), 'TNewCheckListBox') do begin RegisterMethod('function AddCheckBox(const ACaption, ASubItem: string; ALevel: Byte; AChecked, AEnabled, AHasInternalChildren, ACheckWhenParentChecked: Boolean; AObject: TObject): Integer'); RegisterMethod('function AddGroup(const ACaption, ASubItem: string; ALevel: Byte; AObject: TObject): Integer'); RegisterMethod('function AddRadioButton(const ACaption, ASubItem: string; ALevel: Byte; AChecked, AEnabled: Boolean; AObject: TObject): Integer'); RegisterMethod('function CheckItem(const Index: Integer; const AOperation: TCheckItemOperation): Boolean'); RegisterProperty('Checked', 'Boolean Integer', iptrw); RegisterProperty('State', 'TCheckBoxState Integer', iptr); RegisterProperty('ItemCaption', 'String Integer', iptrw); RegisterProperty('ItemEnabled', 'Boolean Integer', iptrw); RegisterProperty('ItemLevel', 'Byte Integer', iptr); RegisterProperty('ItemObject', 'TObject Integer', iptrw); RegisterProperty('ItemSubItem', 'String Integer', iptrw); RegisterProperty('Flat', 'Boolean', iptrw); RegisterProperty('MinItemHeight', 'Integer', iptrw); RegisterProperty('Offset', 'Integer', iptrw); RegisterProperty('OnClickCheck', 'TNotifyEvent', iptrw); RegisterProperty('BorderStyle', 'TBorderStyle', iptrw); RegisterProperty('Color', 'TColor', iptrw); RegisterProperty('Font', 'TFont', iptrw); RegisterProperty('ParentColor', 'Boolean', iptrw); RegisterProperty('ParentFont', 'Boolean', iptrw); RegisterProperty('OnClick', 'TNotifyEvent', iptrw); RegisterProperty('OnDblClick', 'TNotifyEvent', iptrw); RegisterProperty('OnKeyDown', 'TKeyEvent', iptrw); RegisterProperty('OnKeyPress', 'TKeyPressEvent', iptrw); RegisterProperty('OnKeyUp', 'TKeyEvent', iptrw); RegisterProperty('ShowLines', 'Boolean', iptrw); RegisterProperty('WantTabs', 'Boolean', iptrw); RegisterProperty('OnEnter', 'TNotifyEvent', iptrw); RegisterProperty('OnExit', 'TNotifyEvent', iptrw); {$IFNDEF PS_MINIVCL} RegisterProperty('Ctl3D', 'Boolean', iptrw); RegisterProperty('DragCursor', 'Longint', iptrw); RegisterProperty('DragMode', 'TDragMode', iptrw); RegisterProperty('ParentCtl3D', 'Boolean', iptrw); RegisterProperty('ParentShowHint', 'Boolean', iptrw); RegisterProperty('PopupMenu', 'TPopupMenu', iptrw); RegisterProperty('OnDragDrop', 'TDragDropEvent', iptrw); RegisterProperty('OnDragOver', 'TDragOverEvent', iptrw); RegisterProperty('OnEndDrag', 'TEndDragEvent', iptrw); RegisterProperty('OnMouseDown', 'TMouseEvent', iptrw); RegisterProperty('OnMouseMove', 'TMouseMoveEvent', iptrw); RegisterProperty('OnMouseUp', 'TMouseEvent', iptrw); RegisterProperty('OnStartDrag', 'TStartDragEvent', iptrw); {$ENDIF} end; end; procedure RegisterNewProgressBar_C(Cl: TPSPascalCompiler); begin cl.AddTypeS('TNewProgressBarState', '(npbsNormal, npbsError, npbsPaused)'); cl.AddTypeS('TNewProgressBarStyle', '(npbstNormal, npbstMarquee)'); with Cl.AddClassN(Cl.FindClass('TWinControl'), 'TNewProgressBar') do begin RegisterProperty('Min', 'Longint', iptrw); RegisterProperty('Max', 'Longint', iptrw); RegisterProperty('Position', 'Longint', iptrw); RegisterProperty('State', 'TNewProgressBarState', iptrw); RegisterProperty('Style', 'TNewProgressBarStyle', iptrw); end; end; procedure RegisterRichEditViewer_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TMemo'), 'TRichEditViewer') do begin RegisterProperty('RTFText', 'AnsiString', iptw); RegisterProperty('UseRichEdit', 'Boolean', iptrw); end; end; procedure RegisterPasswordEdit_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(cl.FindClass('TCustomEdit'), 'TPasswordEdit') do begin RegisterProperty('AutoSelect', 'Boolean', iptrw); RegisterProperty('AutoSize', 'Boolean', iptrw); RegisterProperty('BorderStyle', 'TBorderStyle', iptrw); RegisterProperty('Color', 'TColor', iptrw); RegisterProperty('Font', 'TFont', iptrw); RegisterProperty('HideSelection', 'Boolean', iptrw); RegisterProperty('MaxLength', 'Integer', iptrw); RegisterProperty('ParentColor', 'Boolean', iptrw); RegisterProperty('ParentFont', 'Boolean', iptrw); RegisterProperty('Password', 'Boolean', iptrw); RegisterProperty('ReadOnly', 'Boolean', iptrw); RegisterProperty('Text', 'string', iptrw); RegisterProperty('OnChange', 'TNotifyEvent', iptrw); RegisterProperty('OnClick', 'TNotifyEvent', iptrw); RegisterProperty('OnDblClick', 'TNotifyEvent', iptrw); RegisterProperty('OnKeyDown', 'TKeyEvent', iptrw); RegisterProperty('OnKeyPress', 'TKeyPressEvent', iptrw); RegisterProperty('OnKeyUp', 'TKeyEvent', iptrw); RegisterProperty('OnEnter', 'TNotifyEvent', iptrw); RegisterProperty('OnExit', 'TNotifyEvent', iptrw); {$IFNDEF PS_MINIVCL} RegisterProperty('CharCase', 'TEditCharCase', iptrw); RegisterProperty('Ctl3D', 'Boolean', iptrw); RegisterProperty('DragCursor', 'Longint', iptrw); RegisterProperty('DragMode', 'TDragMode', iptrw); RegisterProperty('OEMConvert', 'Boolean', iptrw); RegisterProperty('ParentCtl3D', 'Boolean', iptrw); RegisterProperty('ParentShowHint', 'Boolean', iptrw); RegisterProperty('PopupMenu', 'TPopupMenu', iptrw); RegisterProperty('OnDragDrop', 'TDragDropEvent', iptrw); RegisterProperty('OnDragOver', 'TDragOverEvent', iptrw); RegisterProperty('OnEndDrag', 'TEndDragEvent', iptrw); RegisterProperty('OnMouseDown', 'TMouseEvent', iptrw); RegisterProperty('OnMouseMove', 'TMouseMoveEvent', iptrw); RegisterProperty('OnMouseUp', 'TMouseEvent', iptrw); RegisterProperty('OnStartDrag', 'TStartDragEvent', iptrw); {$ENDIF} end; end; procedure RegisterCustomFolderTreeView_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TWinControl'),'TCustomFolderTreeView') do begin RegisterMethod('Procedure ChangeDirectory( const Value : String; const CreateNewItems : Boolean)'); RegisterMethod('Procedure CreateNewDirectory( const ADefaultName : String)'); RegisterProperty('Directory', 'String', iptrw); end; CL.AddTypeS('TFolderRenameEvent', 'Procedure ( Sender : TCustomFolderTreeView; var NewName : String; var Accept : Boolean)'); end; procedure RegisterFolderTreeView_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TCustomFolderTreeView'),'TFolderTreeView') do begin RegisterProperty('OnChange', 'TNotifyEvent', iptrw); RegisterProperty('OnRename', 'TFolderRenameEvent', iptrw); end; end; procedure RegisterStartMenuFolderTreeView_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TCustomFolderTreeView'),'TStartMenuFolderTreeView') do begin RegisterMethod('Procedure SetPaths( const AUserPrograms, ACommonPrograms, AUserStartup, ACommonStartup : String)'); RegisterProperty('OnChange', 'TNotifyEvent', iptrw); RegisterProperty('OnRename', 'TFolderRenameEvent', iptrw); end; end; procedure RegisterBitmapImage_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(CL.FindClass('TGraphicControl'),'TBitmapImage') do begin RegisterProperty('AutoSize', 'Boolean', iptrw); RegisterProperty('BackColor', 'TColor', iptrw); RegisterProperty('Center', 'Boolean', iptrw); RegisterProperty('Bitmap', 'TBitmap', iptrw); RegisterProperty('ReplaceColor', 'TColor', iptrw); RegisterProperty('ReplaceWithColor', 'TColor', iptrw); RegisterProperty('Stretch', 'Boolean', iptrw); RegisterProperty('OnClick', 'TNotifyEvent', iptrw); RegisterProperty('OnDblClick', 'TNotifyEvent', iptrw); end; end; procedure RegisterBidiCtrls_C(Cl: TPSPascalCompiler); begin Cl.AddClassN(Cl.FindClass('TEdit'), 'TNewEdit'); Cl.AddClassN(Cl.FindClass('TMemo'), 'TNewMemo'); Cl.AddClassN(Cl.FindClass('TComboBox'), 'TNewComboBox'); Cl.AddClassN(Cl.FindClass('TListBox'), 'TNewListBox'); Cl.AddClassN(Cl.FindClass('TButton'), 'TNewButton'); Cl.AddClassN(Cl.FindClass('TCheckBox'), 'TNewCheckBox'); Cl.AddClassN(Cl.FindClass('TRadioButton'), 'TNewRadioButton'); end; procedure RegisterNewNotebook_C(Cl: TPSPascalCompiler); begin Cl.AddClassN(Cl.FindClass('TCustomControl'),'TNewNotebookPage'); with Cl.AddClassN(Cl.FindClass('TWinControl'),'TNewNotebook') do begin RegisterMethod('Function FindNextPage( CurPage : TNewNotebookPage; GoForward : Boolean) : TNewNotebookPage'); RegisterProperty('PageCount', 'Integer', iptr); RegisterProperty('Pages', 'TNewNotebookPage Integer', iptr); RegisterProperty('ActivePage', 'TNewNotebookPage', iptrw); end; end; procedure RegisterNewNotebookPage_C(Cl: TPSPascalCompiler); begin with Cl.FindClass('TNewNotebookPage') do begin RegisterProperty('Color', 'TColor', iptrw); RegisterProperty('Notebook', 'TNewNotebook', iptrw); RegisterProperty('PageIndex', 'Integer', iptrw); end; end; procedure RegisterUIStateForm_C(Cl: TPSPascalCompiler); begin Cl.AddClassN(Cl.FindClass('TForm'), 'TUIStateForm'); end; procedure RegisterSetupForm_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TUIStateForm'), 'TSetupForm') do begin RegisterMethod('procedure Center'); RegisterMethod('procedure CenterInsideControl(const Ctl: TWinControl; const InsideClientArea: Boolean)'); RegisterProperty('ControlsFlipped', 'Boolean', iptr); RegisterProperty('FlipControlsOnShow', 'Boolean', iptrw); RegisterProperty('RightToLeft', 'Boolean', iptr); end; end; procedure RegisterMainForm_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(CL.FindClass('TSetupForm'), 'TMainForm') do begin RegisterMethod('Procedure ShowAboutBox'); end; end; procedure RegisterWizardForm_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TSetupForm'), 'TWizardForm') do begin RegisterProperty('CancelButton', 'TNewButton', iptr); RegisterProperty('NextButton', 'TNewButton', iptr); RegisterProperty('BackButton', 'TNewButton', iptr); RegisterProperty('OuterNotebook', 'TNewNotebook', iptr); RegisterProperty('InnerNotebook', 'TNewNotebook', iptr); RegisterProperty('WelcomePage', 'TNewNotebookPage', iptr); RegisterProperty('InnerPage', 'TNewNotebookPage', iptr); RegisterProperty('FinishedPage', 'TNewNotebookPage', iptr); RegisterProperty('LicensePage', 'TNewNotebookPage', iptr); RegisterProperty('PasswordPage', 'TNewNotebookPage', iptr); RegisterProperty('InfoBeforePage', 'TNewNotebookPage', iptr); RegisterProperty('UserInfoPage', 'TNewNotebookPage', iptr); RegisterProperty('SelectDirPage', 'TNewNotebookPage', iptr); RegisterProperty('SelectComponentsPage', 'TNewNotebookPage', iptr); RegisterProperty('SelectProgramGroupPage', 'TNewNotebookPage', iptr); RegisterProperty('SelectTasksPage', 'TNewNotebookPage', iptr); RegisterProperty('ReadyPage', 'TNewNotebookPage', iptr); RegisterProperty('PreparingPage', 'TNewNotebookPage', iptr); RegisterProperty('InstallingPage', 'TNewNotebookPage', iptr); RegisterProperty('InfoAfterPage', 'TNewNotebookPage', iptr); RegisterProperty('DiskSpaceLabel', 'TNewStaticText', iptr); RegisterProperty('DirEdit', 'TEdit', iptr); RegisterProperty('GroupEdit', 'TNewEdit', iptr); RegisterProperty('NoIconsCheck', 'TNewCheckBox', iptr); RegisterProperty('PasswordLabel', 'TNewStaticText', iptr); RegisterProperty('PasswordEdit', 'TPasswordEdit', iptr); RegisterProperty('PasswordEditLabel', 'TNewStaticText', iptr); RegisterProperty('ReadyMemo', 'TNewMemo', iptr); RegisterProperty('TypesCombo', 'TNewComboBox', iptr); RegisterProperty('Bevel', 'TBevel', iptr); RegisterProperty('WizardBitmapImage', 'TBitmapImage', iptr); RegisterProperty('WelcomeLabel1', 'TNewStaticText', iptr); RegisterProperty('InfoBeforeMemo', 'TRichEditViewer', iptr); RegisterProperty('InfoBeforeClickLabel', 'TNewStaticText', iptr); RegisterProperty('MainPanel', 'TPanel', iptr); RegisterProperty('Bevel1', 'TBevel', iptr); RegisterProperty('PageNameLabel', 'TNewStaticText', iptr); RegisterProperty('PageDescriptionLabel', 'TNewStaticText', iptr); RegisterProperty('WizardSmallBitmapImage', 'TBitmapImage', iptr); RegisterProperty('ReadyLabel', 'TNewStaticText', iptr); RegisterProperty('FinishedLabel', 'TNewStaticText', iptr); RegisterProperty('YesRadio', 'TNewRadioButton', iptr); RegisterProperty('NoRadio', 'TNewRadioButton', iptr); RegisterProperty('WizardBitmapImage2', 'TBitmapImage', iptr); RegisterProperty('WelcomeLabel2', 'TNewStaticText', iptr); RegisterProperty('LicenseLabel1', 'TNewStaticText', iptr); RegisterProperty('LicenseMemo', 'TRichEditViewer', iptr); RegisterProperty('InfoAfterMemo', 'TRichEditViewer', iptr); RegisterProperty('InfoAfterClickLabel', 'TNewStaticText', iptr); RegisterProperty('ComponentsList', 'TNewCheckListBox', iptr); RegisterProperty('ComponentsDiskSpaceLabel', 'TNewStaticText', iptr); RegisterProperty('BeveledLabel', 'TNewStaticText', iptr); RegisterProperty('StatusLabel', 'TNewStaticText', iptr); RegisterProperty('FilenameLabel', 'TNewStaticText', iptr); RegisterProperty('ProgressGauge', 'TNewProgressBar', iptr); RegisterProperty('SelectDirLabel', 'TNewStaticText', iptr); RegisterProperty('SelectStartMenuFolderLabel', 'TNewStaticText', iptr); RegisterProperty('SelectComponentsLabel', 'TNewStaticText', iptr); RegisterProperty('SelectTasksLabel', 'TNewStaticText', iptr); RegisterProperty('LicenseAcceptedRadio', 'TNewRadioButton', iptr); RegisterProperty('LicenseNotAcceptedRadio', 'TNewRadioButton', iptr); RegisterProperty('UserInfoNameLabel', 'TNewStaticText', iptr); RegisterProperty('UserInfoNameEdit', 'TNewEdit', iptr); RegisterProperty('UserInfoOrgLabel', 'TNewStaticText', iptr); RegisterProperty('UserInfoOrgEdit', 'TNewEdit', iptr); RegisterProperty('PreparingErrorBitmapImage', 'TBitmapImage', iptr); RegisterProperty('PreparingLabel', 'TNewStaticText', iptr); RegisterProperty('FinishedHeadingLabel', 'TNewStaticText', iptr); RegisterProperty('UserInfoSerialLabel', 'TNewStaticText', iptr); RegisterProperty('UserInfoSerialEdit', 'TNewEdit', iptr); RegisterProperty('TasksList', 'TNewCheckListBox', iptr); RegisterProperty('RunList', 'TNewCheckListBox', iptr); RegisterProperty('DirBrowseButton', 'TNewButton', iptr); RegisterProperty('GroupBrowseButton', 'TNewButton', iptr); RegisterProperty('SelectDirBitmapImage', 'TBitmapImage', iptr); RegisterProperty('SelectGroupBitmapImage', 'TBitmapImage', iptr); RegisterProperty('SelectDirBrowseLabel', 'TNewStaticText', iptr); RegisterProperty('SelectStartMenuFolderBrowseLabel', 'TNewStaticText', iptr); RegisterProperty('PreparingYesRadio', 'TNewRadioButton', iptr); RegisterProperty('PreparingNoRadio', 'TNewRadioButton', iptr); RegisterProperty('PreparingMemo', 'TNewMemo', iptr); RegisterProperty('CurPageID', 'Integer', iptr); RegisterMethod('function AdjustLabelHeight(ALabel:TNewStaticText):Integer'); RegisterMethod('procedure IncTopDecHeight(AControl:TControl;Amount:Integer)'); RegisterProperty('PrevAppDir', 'String', iptr); end; end; procedure RegisterUninstallProgressForm_C(Cl: TPSPascalCompiler); begin with Cl.AddClassN(Cl.FindClass('TSetupForm'), 'TUninstallProgressForm') do begin RegisterProperty('OuterNotebook', 'TNewNotebook', iptr); RegisterProperty('InnerPage', 'TNewNotebookPage', iptr); RegisterProperty('InnerNotebook', 'TNewNotebook', iptr); RegisterProperty('InstallingPage', 'TNewNotebookPage', iptr); RegisterProperty('MainPanel', 'TPanel', iptr); RegisterProperty('PageNameLabel', 'TNewStaticText', iptr); RegisterProperty('PageDescriptionLabel', 'TNewStaticText', iptr); RegisterProperty('WizardSmallBitmapImage', 'TBitmapImage', iptr); RegisterProperty('Bevel1', 'TBevel', iptr); RegisterProperty('StatusLabel', 'TNewStaticText', iptr); RegisterProperty('ProgressBar', 'TNewProgressBar', iptr); RegisterProperty('BeveledLabel', 'TNewStaticText', iptr); RegisterProperty('Bevel', 'TBevel', iptr); RegisterProperty('CancelButton', 'TNewButton', iptr); end; end; procedure RegisterWizardPage_C(Cl: TIFPSPascalCompiler); var NewClass: TPSCompileTimeClass; begin NewClass := Cl.AddClassN(Cl.FindClass('TComponent'), 'TWizardPage'); CL.AddTypeS('TWizardPageNotifyEvent', 'procedure(Sender: TWizardPage)'); CL.AddTypeS('TWizardPageButtonEvent', 'function(Sender: TWizardPage): Boolean'); CL.AddTypeS('TWizardPageCancelEvent', 'procedure(Sender: TWizardPage; var ACancel, AConfirm: Boolean)'); CL.AddTypeS('TWizardPageShouldSkipEvent', 'function(Sender: TWizardPage): Boolean'); with NewClass do begin RegisterProperty('ID', 'Integer', iptr); RegisterProperty('Caption', 'String', iptrw); RegisterProperty('Description', 'String', iptrw); RegisterProperty('Surface', 'TNewNotebookPage', iptr); RegisterProperty('SurfaceHeight', 'Integer', iptr); RegisterProperty('SurfaceWidth', 'Integer', iptr); RegisterProperty('OnActivate', 'TWizardPageNotifyEvent', iptrw); RegisterProperty('OnBackButtonClick', 'TWizardPageButtonEvent', iptrw); RegisterProperty('OnCancelButtonClick', 'TWizardPageCancelEvent', iptrw); RegisterProperty('OnNextButtonClick', 'TWizardPageButtonEvent', iptrw); RegisterProperty('OnShouldSkipPage', 'TWizardPageShouldSkipEvent', iptrw); end; end; procedure RegisterInputQueryWizardPage_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(Cl.FindClass('TWizardPage'),'TInputQueryWizardPage') do begin RegisterMethod('function Add(const APrompt: String; const APassword: Boolean): Integer'); RegisterProperty('Edits', 'TPasswordEdit Integer', iptr); RegisterProperty('PromptLabels', 'TNewStaticText Integer', iptr); RegisterProperty('SubCaptionLabel', 'TNewStaticText', iptr); RegisterProperty('Values', 'String Integer', iptrw); end; end; procedure RegisterInputOptionWizardPage_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(Cl.FindClass('TWizardPage'),'TInputOptionWizardPage') do begin RegisterMethod('function Add(const ACaption: String): Integer'); RegisterMethod('function AddEx(const ACaption: String; const ALevel: Byte; const AExclusive: Boolean): Integer'); RegisterProperty('CheckListBox', 'TNewCheckListBox', iptr); RegisterProperty('SelectedValueIndex', 'Integer', iptrw); RegisterProperty('SubCaptionLabel', 'TNewStaticText', iptr); RegisterProperty('Values', 'Boolean Integer', iptrw); end; end; procedure RegisterInputDirWizardPage_C(CL: TPSPascalCompiler); begin with CL.AddClassN(CL.FindClass('TWizardPage'),'TInputDirWizardPage') do begin RegisterMethod('function Add(const APrompt: String): Integer'); RegisterProperty('Buttons', 'TNewButton Integer', iptr); RegisterProperty('Edits', 'TEdit Integer', iptr); RegisterProperty('PromptLabels', 'TNewStaticText Integer', iptr); RegisterProperty('SubCaptionLabel', 'TNewStaticText', iptr); RegisterProperty('Values', 'String Integer', iptrw); end; end; procedure RegisterInputFileWizardPage_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(Cl.FindClass('TWizardPage'),'TInputFileWizardPage') do begin RegisterMethod('function Add(const APrompt, AFilter, ADefaultExtension: String): Integer'); RegisterProperty('Buttons', 'TNewButton Integer', iptr); RegisterProperty('Edits', 'TEdit Integer', iptr); RegisterProperty('PromptLabels', 'TNewStaticText Integer', iptr); RegisterProperty('SubCaptionLabel', 'TNewStaticText', iptr); RegisterProperty('Values', 'String Integer', iptrw); RegisterProperty('IsSaveButton', 'Boolean Integer', iptrw); end; end; procedure RegisterOutputMsgWizardPage_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(Cl.FindClass('TWizardPage'),'TOutputMsgWizardPage') do begin RegisterProperty('MsgLabel', 'TNewStaticText', iptr); end; end; procedure RegisterOutputMsgMemoWizardPage_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(Cl.FindClass('TWizardPage'),'TOutputMsgMemoWizardPage') do begin RegisterProperty('RichEditViewer', 'TRichEditViewer', iptr); RegisterProperty('SubCaptionLabel', 'TNewStaticText', iptr); end; end; procedure RegisterOutputProgressWizardPage_C(Cl: TPSPascalCompiler); begin with CL.AddClassN(Cl.FindClass('TWizardPage'),'TOutputProgressWizardPage') do begin RegisterMethod('procedure Hide'); RegisterProperty('Msg1Label', 'TNewStaticText', iptr); RegisterProperty('Msg2Label', 'TNewStaticText', iptr); RegisterProperty('ProgressBar', 'TNewProgressBar', iptr); RegisterMethod('procedure SetProgress(const Position, Max: Longint)'); RegisterMethod('procedure SetText(const Msg1, Msg2: String)'); RegisterMethod('procedure Show'); end; end; procedure RegisterHandCursor_C(Cl: TPSPascalCompiler); begin cl.AddConstantN('crHand', 'Integer').Value.ts32 := crHand; end; procedure ScriptClassesLibraryRegister_C(Cl: TPSPascalCompiler); const clSystemColor = {$IFDEF IS_D7} $FF000000 {$ELSE} $80000000 {$ENDIF}; COLOR_HOTLIGHT = 26; begin {$IFNDEF UNICODE} { Temporary: Currently used non Unicode ROPS version doesn't define the AnsiString/PAnsiChar types } Cl.AddTypeS('AnsiString', 'String'); Cl.AddTypeS('PAnsiChar', 'PChar'); {$ENDIF} { Std } SIRegister_Std_TypesAndConsts(Cl); SIRegisterTObject(Cl); SIRegisterTPersistent(Cl); SIRegisterTComponent(Cl); { Classes } SIRegister_Classes_TypesAndConsts(Cl); SIRegisterTStream(Cl); SIRegisterTStrings(Cl, True); SIRegisterTStringList(Cl); SIRegisterTHandleStream(Cl); SIRegisterTFileStream(Cl); { Graphics } SIRegister_Graphics_TypesAndConsts(Cl); cl.AddConstantN('clHotLight', 'Integer').Value.ts32 := Integer(clSystemColor or COLOR_HOTLIGHT); SIRegisterTGraphicsObject(Cl); SIRegisterTFont(Cl); SIRegisterTPen(Cl); SIRegisterTBrush(Cl); SIRegisterTCanvas(Cl); SIRegisterTGraphic(Cl); SIRegisterTBitmap(Cl, True); { Controls } SIRegister_Controls_TypesAndConsts(Cl); SIRegisterTDragObject(Cl); SIRegisterTControl(Cl); RegisterWinControl_C(Cl); SIRegisterTGraphicControl(Cl); SIRegisterTCustomControl(Cl); { Forms } SIRegister_Forms_TypesAndConsts(Cl); SIRegisterTScrollingWinControl(Cl); SIRegisterTForm(Cl); { StdCtrls } SIRegister_StdCtrls_TypesAndConsts(Cl); SIRegisterTCustomLabel(Cl); SIRegisterTLabel(Cl); SIRegisterTCustomEdit(Cl); SIRegisterTEdit(Cl); SIRegisterTCustomMemo(Cl); SIRegisterTMemo(Cl); SIRegisterTCustomComboBox(Cl); SIRegisterTComboBox(Cl); SIRegisterTButtonControl(Cl); SIRegisterTButton(Cl); SIRegisterTCustomCheckBox(Cl); SIRegisterTCheckBox(Cl); SIRegisterTRadioButton(Cl); SIRegisterTCustomListBox(Cl); SIRegisterTListBox(Cl); { ExtCtrls } SIRegister_ExtCtrls_TypesAndConsts(cl); SIRegisterTBevel(Cl); SIRegisterTCustomPanel(Cl); SIRegisterTPanel(Cl); { ComObj } SIRegister_ComObj(Cl); RegisterNewStaticText_C(Cl); RegisterNewCheckListBox_C(Cl); RegisterNewProgressBar_C(Cl); RegisterRichEditViewer_C(Cl); RegisterPasswordEdit_C(Cl); RegisterCustomFolderTreeView_C(Cl); RegisterFolderTreeView_C(Cl); RegisterStartMenuFolderTreeView_C(Cl); RegisterBitmapImage_C(Cl); RegisterBidiCtrls_C(Cl); RegisterNewNotebook_C(Cl); RegisterNewNotebookPage_C(Cl); RegisterUIStateForm_C(Cl); RegisterSetupForm_C(Cl); RegisterMainForm_C(Cl); RegisterWizardForm_C(Cl); RegisterUninstallProgressForm_C(Cl); RegisterWizardPage_C(Cl); RegisterInputQueryWizardPage_C(Cl); RegisterInputOptionWizardPage_C(Cl); RegisterInputDirWizardPage_C(Cl); RegisterInputFileWizardPage_C(Cl); RegisterOutputMsgWizardPage_C(Cl); RegisterOutputMsgMemoWizardPage_C(Cl); RegisterOutputProgressWizardPage_C(Cl); RegisterHandCursor_C(Cl); end; end.
unit StageOptionPart; interface uses SearchOption_Intf, Classes, FMX.Controls, UIWappedPartUnit; type TStageOptionPart = class(TAbsSearchOptionPart) private FTitle: String; FLogData_Start: ILogData; FLogData_End: ILogData; public function GetValues(key: String): String; override; procedure SetValues(key, val: String); override; property StageName: String read FTitle write FTitle; property StartLog: ILogData read FLogData_Start write FLogData_Start; property EndLog: ILogData read FLogData_End write FLogData_End; end; implementation uses SysUtils; { TStageOption } function TStageOptionPart.GetValues(key: String): String; begin if key = 'stage.use' then begin result := IsUseToString; exit; end else if IsUse = true then begin if key = 'stage.title' then result := FTitle else if key = 'stage.start' then result := FLogData_Start.GetDate else if key = 'stage.start_msg' then result := FLogData_End.GetMsg else if key = 'stage.end' then result := FLogData_End.GetDate else if key = 'stage.end_msg' then result := FLogData_End.GetMsg; end else result := ''; end; procedure TStageOptionPart.SetValues(key, val: String); begin if key = 'stage.title' then FTitle := val; end; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VipNet, JwaWinCrypt, WCryptHelper; type TfrmMain = class(TForm) cbDeattached: TCheckBox; cbTSA: TCheckBox; edTSAUrl: TEdit; btSign: TButton; mLog: TMemo; OpenDialog: TOpenDialog; Label1: TLabel; edCert: TEdit; btSelectCert: TButton; procedure btSignClick(Sender: TObject); procedure btSelectCertClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.btSignClick(Sender: TObject); var Cert: PCCERT_CONTEXT; certName: array[0..255] of char; TSPUrl: String; begin if not OpenDialog.Execute then Exit; mLog.Clear; Cert := nil; if edCert.Text <> '' then Cert := FindSignerCert(MY_CERT_STORE_NAME, edCert.Text); if not Assigned(Cert) then Cert := GetSignerCert(Self.Handle, MY_CERT_STORE_NAME); if not Assigned(Cert) then Exit; try if edCert.Text = '' then begin if (CertGetNameString(Cert, CERT_NAME_ATTR_TYPE, 0, nil, @certName, 128) <> 0) then begin edCert.Text := certName; end; end; if cbTSA.Checked then TSPUrl := edTSAUrl.Text else TSPUrl := ''; SignFileSimple(Cert, OpenDialog.FileName, cbDeattached.Checked, TSPUrl); mLog.Lines.Add('Signed ' + OpenDialog.FileName); finally CertFreeCertificateContext(Cert); end; end; procedure TfrmMain.btSelectCertClick(Sender: TObject); var Cert: PCCERT_CONTEXT; certName: array[0..255] of char; begin Cert := GetSignerCert(Self.Handle, MY_CERT_STORE_NAME); if not Assigned(Cert) then Exit; try if (CertGetNameString(Cert, CERT_NAME_ATTR_TYPE, 0, nil, @certName, 128) <> 0) then begin edCert.Text := certName; end; finally CertFreeCertificateContext(Cert); end; end; end.
(* JCore WebServices, Method Invoker Classes Copyright (C) 2015 Joao Morais See the file LICENSE.txt, included in this distribution, for details about the copyright. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *) unit JCoreWSInvokers; {$I jcore.inc} {$WARN 5024 OFF} // hint 'parameter not used' interface uses typinfo, fgl, HTTPDefs; type { TJCoreWSMethodParam } TJCoreWSMethodParam = record Flags: TParamFlags; ParamName: string; ParamType: string; ParamTypeInfo: PTypeInfo; end; TJCoreWSMethodParamArray = array of TJCoreWSMethodParam; { TJCoreWSMethodData } TJCoreWSMethodData = class(TObject) private FCConv: TCallConv; FMethodKind: TMethodKind; FParams: TJCoreWSMethodParamArray; FResultType: PTypeInfo; procedure ReadTypeInfo(const ATypeInfo: PTypeInfo); public constructor Create(const ATypeInfo: PTypeInfo); function MatchFunction(const AParams: array of const; const AResult: TTypeKind): Boolean; function MatchFunction(const AParams: array of const; const AResult: TClass): Boolean; function MatchParams(const AParams: array of const): Boolean; function MatchProcedure(const AParams: array of const): Boolean; property CConv: TCallConv read FCConv; property MethodKind: TMethodKind read FMethodKind; property Params: TJCoreWSMethodParamArray read FParams; property ResultType: PTypeInfo read FResultType; end; { TJCoreWSMethodInvoker } TJCoreWSMethodInvoker = class(TObject) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; virtual; abstract; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); virtual; abstract; end; TJCoreWSMethodInvokerClass = class of TJCoreWSMethodInvoker; TJCoreWSMethodInvokerList = specialize TFPGObjectList<TJCoreWSMethodInvoker>; { TJCoreWSProcObjectInvoker } TJCoreWSProcObjectInvoker = class(TJCoreWSMethodInvoker) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; { TJCoreWSFncObjectInvoker } TJCoreWSFncObjectInvoker = class(TJCoreWSMethodInvoker) public function Match(const AMethodData: TJCoreWSMethodData): Boolean; override; procedure Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); override; end; implementation uses sysutils, JCoreConsts, JCoreClasses, JCoreWSJSON; { TJCoreWSMethodData } procedure TJCoreWSMethodData.ReadTypeInfo(const ATypeInfo: PTypeInfo); { Lay out of ParamList from FPC 3.0 ParamCount: Byte; ParamList: array[1..ParamCount] of record Flags: TParamFlags; ParamName: ShortString; TypeName: ShortString; end; ResultType: ShortString; // for mkFunction and mkClassFunction only ResultTypeRef: PTypeInfo; // for mkFunction and mkClassFunction only CC: TCallConv; ParamTypeRefs: array[1..ParamCount] of PTypeInfo; } var VTypeData: PTypeData; VParamItem: PByte; I: Integer; begin VTypeData := GetTypeData(ATypeInfo); FMethodKind := VTypeData^.MethodKind; VParamItem := PByte(@VTypeData^.ParamList[0]); SetLength(FParams, VTypeData^.ParamCount); for I := Low(FParams) to High(FParams) do begin FParams[I].Flags := TParamFlags(VParamItem^); Inc(VParamItem, SizeOf(TParamFlags)); FParams[I].ParamName := PShortString(VParamItem)^; Inc(VParamItem, VParamItem^ + 1); FParams[I].ParamType := PShortString(VParamItem)^; Inc(VParamItem, VParamItem^ + 1); end; if FMethodKind in [mkFunction, mkClassFunction] then begin Inc(VParamItem, VParamItem^ + 1); // skip shortstring of result type FResultType := PPTypeInfo(VParamItem)^; Inc(VParamItem, SizeOf(PTypeInfo)); end else FResultType := nil; FCConv := TCallConv(VParamItem^); Inc(VParamItem, SizeOf(TCallConv)); for I := Low(FParams) to High(FParams) do begin FParams[I].ParamTypeInfo := PPTypeInfo(VParamItem)^; Inc(VParamItem, SizeOf(PTypeInfo)); end; end; constructor TJCoreWSMethodData.Create(const ATypeInfo: PTypeInfo); begin if ATypeInfo^.Kind <> tkMethod then raise EJCoreWS.Create(3103, S3103_TypeinfoIsNotMethod, []); inherited Create; ReadTypeInfo(ATypeInfo); end; function TJCoreWSMethodData.MatchFunction(const AParams: array of const; const AResult: TTypeKind): Boolean; begin Result := (MethodKind = mkFunction) and (ResultType^.Kind = AResult) and (CConv = ccReg) and MatchParams(AParams); end; function TJCoreWSMethodData.MatchFunction(const AParams: array of const; const AResult: TClass): Boolean; begin Result := (MethodKind = mkFunction) and (ResultType^.Kind = tkClass) and (CConv = ccReg) and (GetTypeData(ResultType)^.ClassType.InheritsFrom(AResult)) and MatchParams(AParams); end; function TJCoreWSMethodData.MatchParams(const AParams: array of const): Boolean; var VKind: TTypeKind; I: Integer; begin Result := Length(AParams) = Length(Params); if Result then for I := Low(AParams) to High(AParams) do begin Result := pfConst in Params[I].Flags; if Result then begin VKind := Params[I].ParamTypeInfo^.Kind; case AParams[I].VType of vtInteger{TTypeKind}: Result := VKind = TTypeKind(AParams[I].VInteger); vtClass: Result := (VKind = tkClass) and (GetTypeData(Params[I].ParamTypeInfo)^.ClassType.InheritsFrom(AParams[I].VClass)); else Result := False; end; end; if not Result then Exit; end; end; function TJCoreWSMethodData.MatchProcedure(const AParams: array of const): Boolean; begin Result := (MethodKind = mkProcedure) and (CConv = ccReg) and MatchParams(AParams); end; { TJCoreWSProcObjectInvoker } function TJCoreWSProcObjectInvoker.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := AMethodData.MatchProcedure([TObject]); end; procedure TJCoreWSProcObjectInvoker.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); type TInvokeMethod = procedure(const AObj: TObject) of object; var VUnserializer: TJCoreWSJSONUnserializer; VContent: string; VObj: TObject; begin VObj := nil; try VUnserializer := TJCoreWSJSONUnserializer.Create(nil); try VContent := ARequest.Content; if VContent <> '' then begin VObj := GetTypeData(AMethodData.Params[0].ParamTypeInfo)^.ClassType.Create; VUnserializer.JSONToObject(VContent, VObj); end; TInvokeMethod(AMethod)(VObj); finally FreeAndNil(VUnserializer); end; finally FreeAndNil(VObj); end; end; { TJCoreWSFncObjectInvoker } function TJCoreWSFncObjectInvoker.Match(const AMethodData: TJCoreWSMethodData): Boolean; begin Result := AMethodData.MatchFunction([], TObject); end; procedure TJCoreWSFncObjectInvoker.Invoke(const AMethodData: TJCoreWSMethodData; const ARequest: TRequest; const AResponse: TResponse; const AMethod: TMethod); type TInvokeMethod = function: TObject of object; var VObj: TObject; VSerializer: TJCoreWSJSONSerializer; begin AResponse.ContentType := 'application/json'; VObj := TInvokeMethod(AMethod)(); if Assigned(VObj) then begin try VSerializer := TJCoreWSJSONSerializer.Create(nil); try AResponse.Content := VSerializer.ObjectToJSONString(VObj); finally FreeAndNil(VSerializer); end; finally FreeAndNil(VObj); end; end else AResponse.Content := ''; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Collections, RemObjects.Elements.EUnit; type ListTest = public class (Test) private Data: Sugar.Collections.List<String>; public method Setup; override; method Constructors; method &Add; method AddRange; method Clear; method Contains; method Exists; method FindIndex; method Find; method FindAll; method TrueForAll; method IndexOf; method Insert; method LastIndexOf; method &Remove; method RemoveAt; method RemoveRange; method ToArray; method Count; method Item; method Enumerator; method ForEach; method Sort; end; implementation method ListTest.Setup; begin Data := new Sugar.Collections.List<String>; Data.Add("One"); Data.Add("Two"); Data.Add("Three"); end; method ListTest.Constructors; begin var Actual := new Sugar.Collections.List<String>(Data); Assert.IsNotNil(Actual); Assert.AreEqual(Actual.Count, 3); Assert.AreEqual(Actual[0], "One"); var Expected: array of String := ["A", "B", "C"]; Actual := new Sugar.Collections.List<String>(Expected); Assert.IsNotNil(Actual); Assert.AreEqual(Actual.Count, 3); Assert.AreEqual(Actual, Expected, true); end; method ListTest.&Add; begin Assert.AreEqual(Data.Count, 3); Data.Add("Four"); Assert.AreEqual(Data.Count, 4); Assert.Contains<String>("Four", Data); Data.Add("Four"); Assert.AreEqual(Data.Count, 5); Data.Add(nil); Assert.AreEqual(Data.Count, 6); Assert.IsNil(Data[5]); end; method ListTest.AddRange; begin var Value := new Sugar.Collections.List<String>; Value.Add("Item1"); Value.Add("Item2"); Data.AddRange(Value); Assert.AreEqual(Data.Count, 5); Assert.Contains("Item1", Data); Assert.Contains("Item2", Data); Data.AddRange(new Sugar.Collections.List<String>); Assert.AreEqual(Data.Count, 5); end; method ListTest.Clear; begin Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method ListTest.Contains; begin Assert.IsTrue(Data.Contains("One")); Assert.IsTrue(Data.Contains("Two")); Assert.IsTrue(Data.Contains("Three")); Assert.IsFalse(Data.Contains("one")); Assert.IsFalse(Data.Contains(nil)); Data.Add(nil); Assert.IsTrue(Data.Contains(nil)); end; method ListTest.Exists; begin Assert.IsTrue(Data.Exists(x -> x = "Two")); Assert.IsFalse(Data.Exists(x -> x = "tWo")); Assert.IsTrue(Data.Exists(x -> x.EqualsIgnoreCase("tWo"))); end; method ListTest.FindIndex; begin Assert.AreEqual(Data.FindIndex(x -> x = "Two"), 1); Assert.AreEqual(Data.FindIndex(x -> x = "two"), -1); Assert.AreEqual(Data.FindIndex(1, x -> x = "Two"), 1); Assert.AreEqual(Data.FindIndex(1, x -> x = "two"), -1); Assert.AreEqual(Data.FindIndex(2, x -> x = "Two"), -1); Assert.AreEqual(Data.FindIndex(1, 2, x -> x = "Two"), 1); Assert.AreEqual(Data.FindIndex(1, 2, x -> x = "two"), -1); Assert.AreEqual(Data.FindIndex(0, 1, x -> x = "Two"), -1); Assert.Throws(->Data.FindIndex(-1, x -> x = "Two")); Assert.Throws(->Data.FindIndex(55, x -> x = "Two")); Assert.Throws(->Data.FindIndex(-1, 3, x -> x = "Two")); Assert.Throws(->Data.FindIndex(55, 3, x -> x = "Two")); Assert.Throws(->Data.FindIndex(0, 55, x -> x = "Two")); Assert.Throws(->Data.FindIndex(0, -1, x -> x = "Two")); end; method ListTest.Find; begin Assert.AreEqual(Data.Find(x -> x = "Two"), "Two"); Assert.IsNil(Data.Find(x -> x = "!Two!")); end; method ListTest.FindAll; begin Data.Add("Two"); Assert.AreEqual(Data.Count, 4); var Actual := Data.FindAll(x -> x = "Two"); Assert.IsNotNil(Actual); Assert.AreEqual(Actual.Count, 2); for Item: String in Actual do Assert.AreEqual(Item, "Two"); Actual := Data.FindAll(x -> x = "!Two!"); Assert.IsNotNil(Actual); Assert.AreEqual(Actual.Count, 0); end; method ListTest.TrueForAll; begin Assert.IsTrue(Data.TrueForAll(x -> x <> "")); Assert.IsFalse(Data.TrueForAll(x -> x = "")); end; method ListTest.IndexOf; begin Assert.AreEqual(Data.IndexOf("One"), 0); Assert.AreEqual(Data.IndexOf("Two"), 1); Assert.AreEqual(Data.IndexOf("Three"), 2); Assert.AreEqual(Data.IndexOf("one"), -1); Assert.AreEqual(Data.IndexOf(nil), -1); end; method ListTest.Insert; begin Assert.AreEqual(Data.IndexOf("Two"), 1); Data.Insert(1, "Item"); Assert.AreEqual(Data.Count, 4); Assert.AreEqual(Data.IndexOf("Item"), 1); Assert.AreEqual(Data.IndexOf("Two"), 2); //added to end of list Data.Insert(Data.Count, "Item2"); Assert.AreEqual(Data.IndexOf("Item2"), 4); Data.Insert(1, nil); Assert.AreEqual(Data.IndexOf(nil), 1); Assert.Throws(->Data.Insert(-1, "item")); Assert.Throws(->Data.Insert(555, "item")); end; method ListTest.LastIndexOf; begin Assert.AreEqual(Data.LastIndexOf("Two"), 1); Data.Add("Two"); Assert.AreEqual(Data.LastIndexOf("Two"), 3); Assert.AreEqual(Data.LastIndexOf("two"), -1); Assert.AreEqual(Data.LastIndexOf(nil), -1); end; method ListTest.&Remove; begin Assert.IsTrue(Data.Remove("One")); Assert.AreEqual(Data.Count, 2); Assert.IsFalse(Data.Contains("One")); Assert.IsFalse(Data.Remove("qwerty")); Assert.IsFalse(Data.Remove(nil)); Data.Clear; Data.Add("Item"); Data.Add("Item"); Assert.AreEqual(Data.Count, 2); Assert.IsTrue(Data.Remove("Item")); //removes first occurense Assert.AreEqual(Data.Count, 1); Assert.IsTrue( Data.Remove("Item")); Assert.AreEqual(Data.Count, 0); Assert.IsFalse( Data.Remove("Item")); end; method ListTest.RemoveAt; begin Data.RemoveAt(1); Assert.AreEqual(Data.Count, 2); Assert.IsFalse(Data.Contains("Two")); Assert.Throws(->Data.RemoveAt(-1)); Assert.Throws(->Data.RemoveAt(Data.Count)); end; method ListTest.RemoveRange; begin Data.RemoveRange(1, 2); Assert.AreEqual(Data.Count, 1); Assert.IsFalse(Data.Contains("Two")); Assert.IsFalse(Data.Contains("Three")); Data.Add("Item"); Data.RemoveRange(1, 0); Assert.AreEqual(Data.Count, 2); Assert.IsTrue(Data.Contains("Item")); Data.RemoveRange(1, 1); Assert.AreEqual(Data.Count, 1); Assert.IsFalse(Data.Contains("Item")); Assert.Throws(->Data.RemoveRange(-1, 1)); Assert.Throws(->Data.RemoveRange(1, -1)); Assert.Throws(->Data.RemoveRange(1, 55)); Assert.Throws(->Data.RemoveRange(55, 1)); end; method ListTest.ToArray; begin var Expected: array of String := ["One", "Two", "Three"]; var Actual := Data.ToArray; Assert.AreEqual(length(Actual), 3); Assert.AreEqual(Actual, Expected, true); end; method ListTest.Count; begin Assert.AreEqual(Data.Count,3 ); Data.RemoveAt(0); Assert.AreEqual(Data.Count, 2); Data.Add("Item"); Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method ListTest.Item; begin Assert.AreEqual(Data.Item[0], "One"); Assert.AreEqual(Data[0], "One"); Assert.AreEqual(Data.Item[1], "Two"); Data.Insert(1, "Item"); Assert.AreEqual(Data.Item[1], "Item"); Data[1] := "Item1"; Assert.AreEqual(Data.Item[1], "Item1"); Data[1] := nil; Assert.IsNil(Data.Item[1]); Assert.Throws(->Data[-1]); Assert.Throws(->Data[55]); end; method ListTest.Enumerator; begin var Expected: array of String := ["One", "Two", "Three"]; var &Index: Integer := 0; for Item: String in Data do begin Assert.AreEqual(Item, Expected[&Index]); inc(&Index); end; Assert.AreEqual(&Index, 3); end; method ListTest.ForEach; begin var Expected: array of String := ["One", "Two", "Three"]; var &Index: Integer := 0; Data.ForEach(x -> begin Assert.AreEqual(x, Expected[&Index]); &Index := &Index + 1; end); Assert.AreEqual(&Index, 3); end; method ListTest.Sort; begin var Expected: array of String := ["A", "C", "b"]; Data.Clear; Data.Add("C"); Data.Add("A"); Data.Add("b"); Assert.AreEqual(Data.Count, 3); Data.Sort((x, y) -> x.CompareTo(y)); for i: Integer := 0 to Data.Count - 1 do Assert.AreEqual(Data[i], Expected[i]); Expected := ["A", "b", "C"]; Data.Sort((x, y) -> x.CompareToIgnoreCase(y)); for i: Integer := 0 to Data.Count - 1 do Assert.AreEqual(Data[i], Expected[i]); end; end.
{$MODE OBJFPC} {$IFNDEF DEBUG} {$R-,Q-,S-,I-} {$OPTIMIZATION LEVEL2} {$INLINE ON} {$ELSE} {$INLINE OFF} {$ENDIF} program Task; const InputFile = 'WATERMOV.INP'; OutputFile = 'WATERMOV.OUT'; maxN = Round(1E6); type TVector = record x, y: Int64; end; TPoint = TVector; var fi, fo: TextFile; a: array[1..maxN] of Integer; b: array[0..maxN] of Int64; stack: array[1..maxN + 1] of TPoint; n, top: Integer; procedure Enter; var i: Integer; begin ReadLn(fi, n); b[0] := 0; for i := 1 to n do begin Read(fi, a[i]); b[i] := b[Pred(i)] + a[i]; end; end; function Point(x, y: Int64): TPoint; inline; begin Result.x := x; Result.y := y; end; operator -(const u, v: TVector): TVector; inline; begin Result.x := u.x - v.x; Result.y := u.y - v.y; end; operator ><(const u, v: TVector): Int64; inline; begin Result := u.x * v.y - u.y * v.x; end; function CCW(const a, b, c: TPoint): Boolean; inline; begin Result := (b - a) >< (c - b) > 0; end; procedure Solve; var i: Integer; p: TPoint; begin top := 1; stack[1] := Point(0, 0); for i := 1 to n do begin P := Point(i, b[i]); while (top > 1) and not CCW(stack[top - 1], stack[top], P) do Dec(top); Inc(top); stack[top] := P; end; end; procedure CalCost; var i: Integer; res, res1, res2: Int64; p, q: TPoint; begin res1 := 0; for i := 1 to n do Inc(res1, b[i] + b[i - 1]); res2 := 0; for i := 1 to top - 1 do begin p := stack[i]; q := stack[i + 1]; Inc(res2, (p.y + q.y) * (q.x - p.x)); end; res := res1 - res2; if res mod 2 = 0 then Write(fo, res div 2, '.0') else Write(fo, res div 2, '.5'); end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try Enter; Solve; CalCost; finally CloseFile(fi); CloseFile(fo); end; end.
unit SimpleMainMenu_Form; // Библиотека : Проект Немезис; // Название : enSimpleMainMenu // Автор : Морозов М.А. // Назначение : Простое основное меню; // Версия : $Id: SimpleMainMenu_Form.pas,v 1.30 2013/01/22 15:59:55 kostitsin Exp $ (*------------------------------------------------------------------------------- $Log: SimpleMainMenu_Form.pas,v $ Revision 1.30 2013/01/22 15:59:55 kostitsin [$424399029] Revision 1.29 2010/05/26 12:08:23 oman Warning fix Revision 1.28 2010/04/30 17:43:44 lulin {RequestLink:207389954}. Revision 1.27 2010/04/30 15:27:06 lulin {RequestLink:207389954}. - чистка кода. Revision 1.26 2010/02/04 16:09:51 lulin {RequestLink:185834848}. Revision 1.25 2010/02/01 08:46:40 oman - fix: {RequestLink:185827991} Revision 1.24 2009/12/07 19:13:55 lulin - удалил ненужный модуль. Revision 1.23 2009/11/18 13:06:32 lulin - используем базовые параметры операции. Revision 1.22 2009/10/12 11:27:49 lulin - коммитим после падения CVS. Revision 1.22 2009/10/08 11:37:12 lulin - показываем баннеры. Revision 1.21 2009/10/07 12:12:18 lulin - подготавливаемся к чистке формы основного меню. Revision 1.20 2009/10/05 18:42:53 lulin {RequestLink:162596818}. Первые штрихи. Revision 1.19 2009/10/05 11:15:24 lulin {RequestLink:162596818}. Подготавливаем инфраструктуру. Revision 1.18 2009/09/30 17:25:14 lulin - переименовываем операцию установки текущей формы, чтобы её проще было искать. Revision 1.17 2009/09/28 19:36:42 lulin - убираем из StdRes константы для операций модулей. Revision 1.16 2009/09/28 18:51:08 lulin - убираем лишние ручки для вызова операций. Revision 1.15 2009/09/24 16:41:20 lulin - продолжаем переносить на модель модуль Common. Revision 1.90 2009/09/18 12:21:45 lulin - невоплощённое убиваем, ошмётки переносим на модель. Revision 1.89 2009/09/09 18:55:32 lulin - переносим на модель код проектов. Revision 1.88 2009/09/03 18:49:28 lulin - реструктуризируем поиски и удаляем ненужное. Revision 1.87 2009/09/03 13:26:27 lulin - делаем прецеденты более изолированными друг от друга. Revision 1.86 2009/08/21 12:44:33 lulin {RequestLink:159360578}. №8. Revision 1.85 2009/08/13 12:16:32 oman - new: Более правильная нотификация - {RequestLink:159355458} Revision 1.84 2009/08/13 07:13:08 oman - new: Более правильная нотификация - {RequestLink:159355458} Revision 1.83 2009/08/12 10:48:09 oman - new: Первое приближение - {RequestLink:159355458} Revision 1.82 2009/08/06 17:18:10 lulin - добавляем операцию сравнения редакций в список редакций. Revision 1.81 2009/08/06 16:08:33 lulin {RequestLink:159352843}. Revision 1.80 2009/02/20 10:12:54 lulin - чистка комментариев. Revision 1.79 2009/02/10 19:03:50 lulin - <K>: 133891247. Вычищаем морально устаревший модуль. Revision 1.78 2009/02/09 15:51:04 lulin - <K>: 133891247. Выделяем интерфейсы основного меню. Revision 1.77 2009/01/19 11:22:23 lulin - <K>: 135597923. Revision 1.76 2009/01/16 12:37:41 lulin - bug fix: http://mdp.garant.ru/pages/viewpage.action?pageId=135597923 Revision 1.75 2009/01/12 15:58:31 lulin - <K>: 133138664. № 22. Revision 1.74 2008/12/29 16:40:59 lulin - <K>: 134316705. Revision 1.73 2008/12/29 15:26:39 lulin - <K>: 133891773. Revision 1.72 2008/12/25 12:20:05 lulin - <K>: 121153186. Revision 1.71 2008/12/24 19:49:38 lulin - <K>: 121153186. Revision 1.70 2008/11/07 14:20:09 lulin - <K>: 121167570. Revision 1.69 2008/11/01 11:19:53 lulin - <K>: 121167580. Revision 1.68 2008/11/01 10:58:28 lulin - <K>: 121167580. Revision 1.67 2008/11/01 10:37:54 lulin - <K>: 121167580. Revision 1.66 2008/11/01 10:08:55 lulin - <K>: 121167580. Revision 1.65 2008/10/31 11:55:07 lulin - <K>: 121167580. Revision 1.64 2008/07/07 14:27:06 lulin - подготавливаемся к переименованию. Revision 1.63 2008/06/18 10:33:00 mmorozov - new: последние открытые препараты (CQ: OIT5-29385); Revision 1.62 2008/05/22 07:05:59 mmorozov - new: основное меню Инфарм. Revision 1.61 2008/05/15 18:16:27 lulin - вычищаем ненужное. Revision 1.60 2008/05/13 16:24:26 lulin - изменения в рамках <K>: 90441490. Revision 1.59 2008/04/08 08:12:50 oman - new: Откручиваем БП для инфарма Revision 1.58 2007/12/28 17:49:53 lulin - удален ненужный глобальный метод. Revision 1.57 2007/12/25 12:27:28 mmorozov - new: используем прямо приведение объекта к интерфейсу вместо AS (в рамках CQ: OIT5-27823); Revision 1.56 2007/12/25 11:32:20 mmorozov - new: подписка на обновление данных приложения (CQ: OIT5-27823); Revision 1.55 2007/12/17 12:22:32 mmorozov - уведомления о начале редактирования, а также изменения пользовательских настроек + избавляемся от операции enSystem.opConfigUpdated (в рамках CQ: OIT5-27823); Revision 1.54 2007/12/12 12:21:23 mmorozov - cleanup: вычищаем операции enSystem (opActiveConfigChange, _opSetActive) (в рамках работы над CQ: OIT5-27823); Revision 1.53 2007/12/04 12:36:38 oman - new: Меняем логику расстановки фокуса для БП (cq27326) Revision 1.52 2007/11/13 13:37:55 mmorozov - new: прокрутка колесом мыши в простом основном меню (CQ: OIT5-27201); Revision 1.51 2007/10/30 12:39:44 mmorozov - rename field; Revision 1.50 2007/10/22 11:53:26 mmorozov - bugfix: не показываем контекстные операции для деревьев (CQ: OIT5-27167); Revision 1.49 2007/10/16 12:29:36 mmorozov - new behviour: используем TnscTreeView (в рамках работы над CQ: OIT5-26997); Revision 1.48 2007/10/10 12:55:27 mmorozov - bugfix: обрабатывали событие изменения формы, а нужно было обрабатывать изменение размеров подложки, на которой лежит сетка контролов, ошибка проявлялась при переключении конфигурации (связанно с правками CQ: OIT5-26991); Revision 1.47 2007/08/28 10:33:50 oman - new: Ссылка на правила работы В ППР (cq26503) Revision 1.46 2007/08/28 07:26:04 oman - fix: Вызывалась не та страница хелпа (cq26511) Revision 1.45 2007/08/13 05:53:47 mmorozov - change: группа последних открытых документов сделана несворачиваемой (CQ: OIT5-26279); Revision 1.44 2007/08/09 10:05:47 oman - new: Успешный БП из ОМ трактуем как ручной вызов БП - т.е. в открывшемся списке появиться панель БП (cq26300) Revision 1.43 2007/07/30 09:24:32 mmorozov - new: используем таблицу стилей для устновки цвета фона заголовка скрываемого поля; Revision 1.42 2007/06/14 13:50:15 mmorozov - change: порядок модулей; Revision 1.41 2007/05/08 11:17:37 oman - fix: Для карточки базового поиска (cq25145) Revision 1.40 2007/05/07 14:31:18 mmorozov - new: реакция на изменение типа основного меню в настройках (CQ: OIT5-24871); Revision 1.39 2007/05/04 10:55:06 oman - fix: Терялся фокус - по аналогии с ОМ грязно хачим Revision 1.38 2007/05/04 07:45:47 oman - fix: Интерфейсы для базового поиска перенесены в проект (cq25145) Revision 1.37 2007/05/03 15:01:32 oman - fix: Таки переключаем внешний вид при смене фокуса (cq25149) Revision 1.36 2007/05/03 14:25:00 oman - fix: Пытаемся переключать внешний вид (cq25149) Revision 1.35 2007/05/03 09:44:21 mmorozov - change: отрезаем заголовок "продвинутого основного меню" (CQ: OIT5-25061); Revision 1.34 2007/05/03 08:24:03 oman - new: Убрал базовый поиск из простейшего основного меню (cq25149) Revision 1.33 2007/05/03 06:57:56 oman - new: Окончательный вариант обработки закрытия окна базового поиска (cq25145) Revision 1.32 2007/05/02 14:23:22 oman - fix: Более правильная механика закрытия/автооткрытия окна (cq25145) Revision 1.31 2007/05/02 09:07:00 oman - new: Механика закрытия/автооткрытия окна (cq25145) Revision 1.30 2007/04/28 12:05:54 oman - new: Первоначальная поддержка механизма нотификации для базового поиска (cq25145) Revision 1.29 2007/04/17 12:31:51 mmorozov - bugfix: формирование имени; Revision 1.28 2007/04/17 12:08:56 mmorozov - change: используем правильные функции при подготовке названия формы; Revision 1.27 2007/04/17 11:50:00 lulin - cleanup. Revision 1.26 2007/04/17 10:49:20 mmorozov - new: изменяем ОМ (CQ: OIT5-25062); Revision 1.25 2007/04/16 10:41:48 oman - fix: Переименовываем "Правовая поддержка" в "Правовая поддержка онлайн" (cq25059) Revision 1.24 2007/04/11 15:15:37 mmorozov - new: в простом основном меню показываем полные названия в списке последних открытых (CQ: OIT5-24958); - change: фокус перехода; Revision 1.23 2007/04/09 13:04:00 mmorozov - bugfix: при поиске в основном меню используем правильную функцию поиска (CQ: OIT5-24547); Revision 1.22 2007/04/06 08:29:48 mmorozov - new: в деревьях включён перенос строк + форма не пишет данные в историю, строим сетку контролов после загрузки (Loaded) (CQ: OIT5-24903); Revision 1.21 2007/04/06 07:52:07 mmorozov - change: изменены формулировки, положение групп (CQ: OIT5-24602); Revision 1.20 2007/04/05 13:42:45 lulin - избавляемся от лишних преобразований строк. Revision 1.19 2007/03/28 19:43:02 lulin - ЭлПаковский редактор переводим на строки с кодировкой. Revision 1.18 2007/03/28 11:40:39 mmorozov - rename method; Revision 1.17 2007/03/28 11:04:56 mmorozov - "таблица перехода фокуса" перенесена в библиотеку визуальных компонентов проекта Немезис; Revision 1.16 2007/03/22 12:29:34 mmorozov - change: ячейка сетки контролов в виде скрываемого поля с деревом перенесена в общее место; Revision 1.15 2007/03/20 11:38:15 lulin - не теряем кодировку при присваивании заголовков форм и контролов. Revision 1.14 2007/03/02 13:15:48 lulin - присваимваем строку с кодировкой, без преобразования ее к родной дельфийской. Revision 1.13 2007/02/16 19:19:18 lulin - в выпадающих списках используем родной список строк. Revision 1.12 2007/02/09 15:56:18 mmorozov - new: правильно реализуем поиск по контексту в простом основном меню (CQ: OIT5-24353); Revision 1.11 2007/02/08 13:36:12 mmorozov - new: реакция на поиск по пустому контексту (CQ: OIT5-24293); Revision 1.10 2007/02/08 12:39:43 mmorozov - change: обобщена и упрощена логика по работе с элементами дерева навигатора (CQ: OIT5-23939); Revision 1.9 2007/02/07 14:30:43 lulin - переводим на строки с кодировкой. Revision 1.8 2007/02/05 12:06:09 mmorozov - opt: не строим лишний раз таблицу контролов; Revision 1.7 2007/02/05 11:08:29 mmorozov - new behaviour: перестраиваем меню после перехода по истории; Revision 1.6 2007/02/02 14:55:09 mmorozov - new: используем новые типы узлов рубрикатора; Revision 1.5 2007/02/02 08:39:11 lulin - переводим на строки с кодировкой. Revision 1.4 2007/01/29 14:29:23 mmorozov - new: введем историю поисков; добавления операция поиска; (в рамках CQ: OIT5-24234); Revision 1.3 2007/01/29 10:08:33 mmorozov - new: в рамках работы над CQ: OIT5-24234; - bugfix: не обновляли деревья после переключения базы; Revision 1.2 2007/01/19 14:35:45 mmorozov - new: поиск по контексту в простом варианте основного меню (CQ: OIT5-23939); Revision 1.1 2007/01/18 12:57:20 mmorozov - new: Простое основное меню (CQ: OIT5-23939); -------------------------------------------------------------------------------*) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, afwControl, afwInputControl, afwInterfaces, afwCustomCommonControl, l3Interfaces, l3TreeInterfaces, vtLabel, vtLister, vtOutliner, vtOutlinerWithQuickSearch, vtOutlinerWithDragDrop, vtHideField, OvcBase, vtPanel, ElXPThemedControl, absdrop, treedrop, eeTreeViewExport, eeTreeView, nscInterfaces, nscCombobox, vcmInterfaces, vcmBase, vcmEntityForm, vcmEntities, vcmComponent, vcmBaseEntities, vcmExternalInterfaces, nscHideField, nscTreeView, nsMainMenuNew, MainMenuNewRes, afwControlPrim, afwBaseControl, afwTextControlPrim, afwTextControl, bsInterfaces, WorkJournalInterfaces, PrimSimpleMainMenu_Form, l3InterfacedComponent, BaseSearchInterfaces, nscTreeViewHotTruck ; type Ten_SimpleMainMenu = class(TvcmEntityFormRef) Entities : TvcmEntities; pnlMain: TvtPanel; hfSearch: TnscHideField; hfLawNews: TnscHideField; hfLawSupport: TnscHideField; hfReferences: TnscHideField; hfLastOpenDocs: TnscHideField; tvSearch: TnscTreeView; tvLawSupport: TnscTreeView; tvLastOpenDocs: TnscTreeViewHotTruck; tvReferences: TnscTreeViewHotTruck; tvLawNews: TnscTreeViewHotTruck; procedure lblCompNameClick(Sender: TObject); protected // methods procedure DoInitKeyboardNavigation(const aTable : InscTabTable); override; {-} procedure LoadLastOpenDocs; override; {* - загрузить список последних открытых документов. } function DoBuildGrid: InscArrangeGrid; override; {* - построить сетку контролов. } procedure LoadTrees; override; {-} end;//Ten_SimpleMainMenu implementation uses l3Base, l3String, l3Chars, afwFacade, lgTypes, vcmStringList, nscArrangeGrid, nscArrangeGridCell, StartUnit, nsTypes, nsUtils, nsSettings, nsConst, nscTabTable, nscTabTableCell, nsOpenUtils, DataAdapter, StdRes, nsLastOpenDocTree, smSearchTree, smLawNewsTree, smLawSupport, smReferencesTree, MainMenuDomainInterfaces ; {$R *.DFM} function Ten_SimpleMainMenu.DoBuildGrid: InscArrangeGrid; begin Result := TnscArrangeGrid.Make(False); with Result do begin AddColumn; AddColumn; AddRow; AddRow; Cell[0, 0] := TnscHideFieldCell.Make(hfSearch, True); Cell[0, 1] := TnscHideFieldCell.Make(hfReferences, True); Cell[1, 0] := TnscHideFieldCell.Make(hfLawNews, True); Cell[1, 1] := TnscHideFieldCell.Make(hfLawSupport, True); MergeCells(2, 0, 1, TnscHideFieldCell.Make(hfLastOpenDocs)); end;//with Result do end;//BuildGrid procedure Ten_SimpleMainMenu.LoadTrees; begin inherited; tvSearch.TreeStruct := TsmSearchTree.Make; tvLawSupport.TreeStruct := TsmLawSupport.Make; end; procedure Ten_SimpleMainMenu.DoInitKeyboardNavigation(const aTable : InscTabTable); begin // Навигация с помощью клавиатуры with aTable.AddColumn do begin AddItem(TnscTreeViewTabCell.Make(tvSearch)); AddItem(TnscTreeViewTabCell.Make(tvLawNews)); AddItem(TnscTreeViewTabCell.Make(tvLastOpenDocs)); end;//with aTable.AddItem do with aTable.AddColumn do begin AddItem(TnscTreeViewTabCell.Make(tvReferences)); AddItem(TnscTreeViewTabCell.Make(tvLawSupport)); end;//with aTable.AddItem do end;//KeyboardNavigation procedure Ten_SimpleMainMenu.lblCompNameClick(Sender: TObject); begin Dispatcher.ModuleOperation(TdmStdRes.mod_opcode_Common_ComplectInfo); end;//lblCompNameClick procedure Ten_SimpleMainMenu.LoadLastOpenDocs; begin tvLastOpenDocs.TreeStruct := TnsLastOpenDocTree.Make(afw.Settings.LoadInteger( pi_RecentlyOpenDocumentsCount, dv_RecentlyOpenDocumentsCount), False, True); end;//LoadLastOpenDocs end.
unit ce_todolist; {$I ce_defines.inc} interface uses Classes, SysUtils, FileUtil, ListFilterEdit, Forms, Controls, strutils, Graphics, Dialogs, ExtCtrls, Menus, Buttons, ComCtrls, ce_widget, process, ce_common, ce_interfaces, ce_synmemo, ce_project, ce_symstring, ce_writableComponent, ce_observer; type TCETodoOptions = class(TWritableLfmTextComponent) private fAutoRefresh: boolean; fSingleClick: boolean; published property autoRefresh: boolean read fAutoRefresh write fAutoRefresh; property singleClickSelect: boolean read fSingleClick write fSingleClick; public procedure AssignTo(Dest: TPersistent); override; procedure Assign(Src: TPersistent); override; end; TTodoContext = (tcNone, tcProject, tcFile); // represents a TODO item // warning: the props names must be kept in sync with the values set in the tool. TTodoItem = class(TCollectionItem) private fFile: string; fLine: string; fText: string; fPriority: string; fAssignee: string; fCategory: string; fStatus: string; published property filename: string read fFile write fFile; property line: string read fLine write fLine; property Text: string read fText write fText; property assignee: string read fAssignee write fAssignee; property category: string read fCategory write fCategory; property status: string read fStatus write fStatus; property priority: string read fPriority write fPriority; end; // encapsulates / makes serializable a collection of TODO item. // warning: the class name must be kept in sync with the value set in the tool. TTodoItems = class(TComponent) private fItems: TCollection; procedure setItems(aValue: TCollection); function getItem(index: Integer): TTodoItem; function getCount: integer; published // warning, "items" must be kept in sync with... property items: TCollection read fItems write setItems; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // str is the output stream of the tool process. procedure loadFromTxtStream(str: TMemoryStream); property Count: integer read getCount; property item[index: integer]: TTodoItem read getItem; default; end; { TCETodoListWidget } TCETodoListWidget = class(TCEWidget, ICEMultiDocObserver, ICEProjectObserver, ICEEditableOptions) btnRefresh: TBitBtn; btnGo: TBitBtn; lstItems: TListView; lstfilter: TListFilterEdit; mnuAutoRefresh: TMenuItem; Panel1: TPanel; procedure handleListClick(Sender: TObject); procedure mnuAutoRefreshClick(Sender: TObject); private fToolOutput: TMemoryStream; fAutoRefresh: Boolean; fSingleClick: Boolean; fProj: TCEProject; fDoc: TCESynMemo; fToolProc: TCheckedAsyncProcess; fTodos: TTodoItems; fMsgs: ICEMessagesDisplay; fOptions: TCETodoOptions; // ICEMultiDocObserver procedure docNew(aDoc: TCESynMemo); procedure docFocused(aDoc: TCESynMemo); procedure docChanged(aDoc: TCESynMemo); procedure docClosing(aDoc: TCESynMemo); // ICEProjectObserver procedure projNew(aProject: TCEProject); procedure projChanged(aProject: TCEProject); procedure projClosing(aProject: TCEProject); procedure projFocused(aProject: TCEProject); procedure projCompiling(aProject: TCEProject); // ICEEditableOptions function optionedWantCategory(): string; function optionedWantEditorKind: TOptionEditorKind; function optionedWantContainer: TPersistent; procedure optionedEvent(anEvent: TOptionEditorEvent); function optionedOptionsModified: boolean; // TODOlist things function getContext: TTodoContext; procedure killToolProcess; procedure callToolProcess; procedure toolTerminated(Sender: TObject); procedure toolOutputData(Sender: TObject); procedure procOutputDbg(Sender: TObject); procedure clearTodoList; procedure fillTodoList; procedure lstItemsColumnClick(Sender: TObject; Column: TListColumn); procedure lstItemsCompare(Sender: TObject; item1, item2: TListItem; Data: Integer; var Compare: Integer); procedure btnRefreshClick(Sender: TObject); procedure filterItems(Sender: TObject); procedure setSingleClick(aValue: boolean); procedure setAutoRefresh(aValue: boolean); protected procedure SetVisible(Value: boolean); override; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; // property singleClickSelect: boolean read fSingleClick write setSingleClick; property autoRefresh: boolean read fAutoRefresh write setAutoRefresh; end; implementation {$R *.lfm} const ToolExeName = 'cetodo' + exeExt; OptFname = 'todolist.txt'; {$REGION TTodoItems ------------------------------------------------------------} constructor TTodoItems.Create(aOwner: TComponent); begin inherited; fItems := TCollection.Create(TTodoItem); end; destructor TTodoItems.Destroy; begin fItems.Free; inherited; end; procedure TTodoItems.setItems(aValue: TCollection); begin fItems.Assign(aValue); end; function TTodoItems.getItem(index: Integer): TTodoItem; begin Result := TTodoItem(fItems.Items[index]); end; function TTodoItems.getCount: integer; begin Result := fItems.Count; end; procedure TTodoItems.loadFromTxtStream(str: TMemoryStream); var bin: TMemoryStream; begin // empty collection ~ length if str.Size < 50 then exit; // try bin := TMemoryStream.Create; try str.Position := 0; ObjectTextToBinary(str, bin); bin.Position := 0; bin.ReadComponent(self); finally bin.Free; end; except fItems.Clear; end; end; {$ENDREGIOn} {$REGION Standard Comp/Obj -----------------------------------------------------} constructor TCETodoListWidget.Create(aOwner: TComponent); var png: TPortableNetworkGraphic; fname: string; begin inherited; // fToolOutput := TMemoryStream.Create; fOptions := TCETodoOptions.Create(self); fOptions.autoRefresh := True; fOptions.Name := 'todolistOptions'; // fTodos := TTodoItems.Create(self); lstItems.OnDblClick := @handleListClick; btnRefresh.OnClick := @btnRefreshClick; lstItems.OnColumnClick := @lstItemsColumnClick; lstItems.OnCompare := @lstItemsCompare; fAutoRefresh := True; fSingleClick := False; mnuAutoRefresh.Checked := True; lstfilter.OnChange := @filterItems; btnGo.OnClick := @handleListClick; // png := TPortableNetworkGraphic.Create; try png.LoadFromLazarusResource('arrow_update'); btnRefresh.Glyph.Assign(png); png.LoadFromLazarusResource('arrow_pen'); btnGo.Glyph.Assign(png); finally png.Free; end; // fname := getCoeditDocPath + OptFname; if FileExists(fname) then fOptions.loadFromFile(fname); fOptions.AssignTo(self); // EntitiesConnector.addObserver(self); end; destructor TCETodoListWidget.Destroy; begin fOptions.saveToFile(getCoeditDocPath + OptFname); killToolProcess; fToolOutput.Free; inherited; end; procedure TCETodoListWidget.SetVisible(Value: boolean); begin inherited; if Value and fAutoRefresh then callToolProcess; end; {$ENDREGION} {$REGION ICEEditableOptions ----------------------------------------------------} procedure TCETodoOptions.AssignTo(Dest: TPersistent); var widg: TCETodoListWidget; begin if Dest is TCETodoListWidget then begin widg := TCETodoListWidget(Dest); widg.singleClickSelect := fSingleClick; widg.autoRefresh := fAutoRefresh; end else inherited; end; procedure TCETodoOptions.Assign(Src: TPersistent); var widg: TCETodoListWidget; begin if Src is TCETodoListWidget then begin widg := TCETodoListWidget(Src); fSingleClick := widg.singleClickSelect; fAutoRefresh := widg.autoRefresh; end else inherited; end; function TCETodoListWidget.optionedWantCategory(): string; begin exit('Todo list'); end; function TCETodoListWidget.optionedWantEditorKind: TOptionEditorKind; begin exit(oekGeneric); end; function TCETodoListWidget.optionedWantContainer: TPersistent; begin fOptions.Assign(self); exit(fOptions); end; procedure TCETodoListWidget.optionedEvent(anEvent: TOptionEditorEvent); begin if anEvent <> oeeAccept then exit; fOptions.AssignTo(self); end; function TCETodoListWidget.optionedOptionsModified: boolean; begin exit(false); end; {$ENDREGION} {$REGION ICEMultiDocObserver ---------------------------------------------------} procedure TCETodoListWidget.docNew(aDoc: TCESynMemo); begin end; procedure TCETodoListWidget.docFocused(aDoc: TCESynMemo); begin if aDoc = fDoc then exit; fDoc := aDoc; if Visible and fAutoRefresh then callToolProcess; end; procedure TCETodoListWidget.docChanged(aDoc: TCESynMemo); begin end; procedure TCETodoListWidget.docClosing(aDoc: TCESynMemo); begin if fDoc <> aDoc then exit; fDoc := nil; if Visible and fAutoRefresh then callToolProcess; end; {$ENDREGION} {$REGION ICEProjectObserver ----------------------------------------------------} procedure TCETodoListWidget.projNew(aProject: TCEProject); begin fProj := aProject; end; procedure TCETodoListWidget.projChanged(aProject: TCEProject); begin if fProj <> aProject then exit; if Visible and fAutoRefresh then callToolProcess; end; procedure TCETodoListWidget.projClosing(aProject: TCEProject); begin if fProj <> aProject then exit; fProj := nil; if Visible and fAutoRefresh then callToolProcess; end; procedure TCETodoListWidget.projFocused(aProject: TCEProject); begin if aProject = fProj then exit; fProj := aProject; if Visible and fAutoRefresh then callToolProcess; end; procedure TCETodoListWidget.projCompiling(aProject: TCEProject); begin end; {$ENDREGION} {$REGION Todo list things ------------------------------------------------------} function TCETodoListWidget.getContext: TTodoContext; begin if ((fProj = nil) and (fDoc = nil)) then exit(tcNone); if ((fProj = nil) and (fDoc <> nil)) then exit(tcFile); if ((fProj <> nil) and (fDoc = nil)) then exit(tcProject); // if fProj.isProjectSource(fDoc.fileName) then exit(tcProject) else exit(tcFile); end; procedure TCETodoListWidget.killToolProcess; begin if fToolProc = nil then exit; // fToolProc.Terminate(0); fToolProc.Free; fToolProc := nil; end; procedure TCETodoListWidget.callToolProcess; var ctxt: TTodoContext; begin clearTodoList; if not exeInSysPath(ToolExeName) then exit; ctxt := getContext; if ctxt = tcNone then exit; // killToolProcess; // process parameter fToolProc := TCheckedAsyncProcess.Create(nil); fToolProc.Executable := exeFullName(ToolExeName); fToolProc.Options := [poUsePipes]; fToolProc.ShowWindow := swoHIDE; fToolProc.CurrentDirectory := ExtractFileDir(Application.ExeName); fToolProc.OnTerminate := @toolTerminated; fToolProc.OnReadData := @toolOutputData; // files passed to the tool argument if ctxt = tcProject then fToolProc.Parameters.AddText(symbolExpander.get('<CPFS>')) else fToolProc.Parameters.Add(symbolExpander.get('<CFF>')); // fToolProc.Execute; end; procedure TCETodoListWidget.procOutputDbg(Sender: TObject); var str: TStringList; msg: string; ctxt: TTodoContext; begin getMessageDisplay(fMsgs); str := TStringList.Create; try processOutputToStrings(fToolProc, str); ctxt := getContext; for msg in str do case ctxt of tcNone: fMsgs.message(msg, nil, amcMisc, amkAuto); tcFile: fMsgs.message(msg, fDoc, amcEdit, amkAuto); tcProject: fMsgs.message(msg, fProj, amcProj, amkAuto); end; finally str.Free; end; end; procedure TCETodoListWidget.toolOutputData(Sender: TObject); begin processOutputToStream(fToolProc, fToolOutput); end; procedure TCETodoListWidget.toolTerminated(Sender: TObject); begin processOutputToStream(fToolProc, fToolOutput); fToolOutput.Position := 0; //TODO-cbugfix: UTF chars in TODO comments bug either in the widget or the tool, symptom: empty todo list, conditions: to determine. //fToolOutput.SaveToFile('C:\cetodo_widgetside.txt'); fTodos.loadFromTxtStream(fToolOutput); fillTodoList; fToolProc.OnTerminate := nil; fToolProc.OnReadData := nil; fToolOutput.Clear; end; procedure TCETodoListWidget.clearTodoList; begin lstItems.Clear; fTodos.items.Clear; end; procedure TCETodoListWidget.fillTodoList; var i: integer; src: TTodoItem; trg: TListItem; flt: string; begin lstItems.Clear; lstItems.Column[1].Visible := False; lstItems.Column[2].Visible := False; lstItems.Column[3].Visible := False; lstItems.Column[4].Visible := False; flt := lstfilter.Text; for i := 0 to fTodos.Count - 1 do begin src := fTodos[i]; trg := lstItems.Items.Add; trg.Data := src; trg.Caption := src.Text; trg.SubItems.Add(src.category); trg.SubItems.Add(src.assignee); trg.SubItems.Add(src.status); trg.SubItems.Add(src.priority); // if flt <> '' then if flt <> '(filter)' then if not AnsiContainsText(src.Text, flt) then if not AnsiContainsText(src.category, flt) then if not AnsiContainsText(src.assignee, flt) then if not AnsiContainsText(src.status, flt) then if not AnsiContainsText(src.priority, flt) then begin lstItems.Items.Delete(trg.Index); continue; end; // if src.category <> '' then lstItems.Column[1].Visible := True; if src.assignee <> '' then lstItems.Column[2].Visible := True; if src.status <> '' then lstItems.Column[3].Visible := True; if src.priority <> '' then lstItems.Column[4].Visible := True; end; end; procedure TCETodoListWidget.handleListClick(Sender: TObject); var itm: TTodoItem; fname, ln: string; begin if lstItems.Selected = nil then exit; if lstItems.Selected.Data = nil then exit; // the collection will be cleared if a file is opened // docFocused->callToolProcess->fTodos....clear // so line and filename must be copied itm := TTodoItem(lstItems.Selected.Data); fname := itm.filename; ln := itm.line; getMultiDocHandler.openDocument(fname); // if fDoc = nil then exit; fDoc.CaretY := StrToInt(ln); fDoc.SelectLine; end; procedure TCETodoListWidget.mnuAutoRefreshClick(Sender: TObject); begin autoRefresh := mnuAutoRefresh.Checked; fOptions.autoRefresh := autoRefresh; end; procedure TCETodoListWidget.lstItemsColumnClick(Sender: TObject; Column: TListColumn); var curr: TListItem; begin if lstItems.Selected = nil then exit; curr := lstItems.Selected; // if lstItems.SortDirection = sdAscending then lstItems.SortDirection := sdDescending else lstItems.SortDirection := sdAscending; lstItems.SortColumn := Column.Index; lstItems.Selected := nil; lstItems.Selected := curr; lstItems.Update; end; procedure TCETodoListWidget.lstItemsCompare(Sender: TObject; item1, item2: TListItem; Data: Integer; var Compare: Integer); var txt1, txt2: string; col: Integer; begin txt1 := ''; txt2 := ''; col := lstItems.SortColumn; if col = 0 then begin txt1 := item1.Caption; txt2 := item2.Caption; end else begin if col < item1.SubItems.Count then txt1 := item1.SubItems.Strings[col]; if col < item2.SubItems.Count then txt2 := item2.SubItems.Strings[col]; end; Compare := AnsiCompareStr(txt1, txt2); if lstItems.SortDirection = sdDescending then Compare := -Compare; end; procedure TCETodoListWidget.btnRefreshClick(Sender: TObject); begin callToolProcess; end; procedure TCETodoListWidget.filterItems(Sender: TObject); begin fillTodoList; end; procedure TCETodoListWidget.setSingleClick(aValue: boolean); begin fSingleClick := aValue; if fSingleClick then begin lstItems.OnClick := @handleListClick; lstItems.OnDblClick := nil; end else begin lstItems.OnClick := nil; lstItems.OnDblClick := @handleListClick; end; end; procedure TCETodoListWidget.setAutoRefresh(aValue: boolean); begin fAutoRefresh := aValue; mnuAutoRefresh.Checked := aValue; if fAutoRefresh then callToolProcess; end; {$ENDREGION} end.
unit Concrete; interface uses GameTypes; const cCenter = 0; cUp = -1; cDown = 1; cLeft = -1; cRight = 1; type TConcreteConfig = array [cUp..cDown, cLeft..cRight] of boolean; const cMaxConcreteConfigs = 16; const cFullConcrete = 15; cSpecialConcrete = 16; type TConcrete = byte; const concreteNone = high(TConcrete); function GetConcreteId(const concreteconfig : TConcreteConfig) : TConcrete; function PlaceSpecialConcrete(i, j : integer) : boolean; function RotateConcreteId(id : integer; rotation : TRotation) : integer; implementation const cConcreteConfigs : array [0..pred(cMaxConcreteConfigs)] of TConcreteConfig = ( ( ( false, false, false ), //0 ( false, true, false ), ( false, false, false ) ), ( ( false, false, false ), //1 ( false, true, false ), ( false, true, false ) ), ( ( false, false, false ), //2 ( false, true, true ), ( false, false, false ) ), ( ( false, false, false ), //3 ( false, true, true ), ( false, true, false ) ), ( ( false, false, false ), //4 ( true, true, false ), ( false, false, false ) ), ( ( false, false, false ), //5 ( true, true, false ), ( false, true, false ) ), ( ( false, false, false ), //6 ( true, true, true ), ( false, false, false ) ), ( ( false, false, false ), //7 ( true, true, true ), ( false, true, false ) ), ( ( false, true, false ), //8 ( false, true, false ), ( false, false, false ) ), ( ( false, true, false ), //9 ( false, true, false ), ( false, true, false ) ), ( ( false, true, false ), //10 ( false, true, true ), ( false, false, false ) ), ( ( false, true, false ), //11 ( false, true, true ), ( false, true, false ) ), ( ( false, true, false ), //12 ( true, true, false ), ( false, false, false ) ), ( ( false, true, false ), //13 ( true, true, false ), ( false, true, false ) ), ( ( false, true, false ), //14 ( true, true, true ), ( false, false, false ) ), ( ( false, true, false ), //15 ( true, true, true ), ( false, true, false ) ) ); function GetConcreteId(const concreteconfig : TConcreteConfig) : TConcrete; var match : boolean; i : TConcrete; begin match := false; i := low(cConcreteConfigs); while not match do begin match := (not (cConcreteConfigs[i][cUp, cCenter] xor concreteconfig[cUp, cCenter])) and (not (cConcreteConfigs[i][cDown, cCenter] xor concreteconfig[cDown, cCenter])) and (not (cConcreteConfigs[i][cCenter, cLeft] xor concreteconfig[cCenter, cLeft])) and (not (cConcreteConfigs[i][cCenter, cRight] xor concreteconfig[cCenter, cRight])); if not match then inc(i); end; Result := i; end; function PlaceSpecialConcrete(i, j : integer) : boolean; begin Result := ((i mod 2) = 0) and ((j mod 2) = 0); end; function RotateConcreteId(id : integer; rotation : TRotation) : integer; const cRotatedConcreteIds : array [TRotation, 0..cMaxConcreteConfigs] of TConcrete = ( (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), (0, 2, 8, 10, 1, 3, 9, 7, 4, 6, 12, 11, 5, 13, 14, 15, 16), (0, 8, 4, 12, 2, 10, 6, 7, 1, 9, 5, 11, 3, 13, 14, 15, 16), (0, 4, 1, 5, 8, 12, 9, 7, 2, 6, 3, 11, 10, 13, 14, 15, 16) ); // The following ids are not rotated: 7, 11, 13, 14 begin Result := cRotatedConcreteIds[rotation, id]; end; end.
unit evGeneratorsInterfaces; {* Интерфейсы для поддержки работы генераторов } // Модуль: "w:\common\components\gui\Garant\Everest\evGeneratorsInterfaces.pas" // Стереотип: "UtilityPack" // Элемент модели: "evGeneratorsInterfaces" MUID: (4A253C760202) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3Base , l3Variant , nevBase ; type IevTextPainter = interface ['{4840242F-084A-4805-9EB0-90C1126C5137}'] procedure PaintLine(ParaVisible: Boolean; ParaStyle: Integer; S: Tl3String; Ob: Tl3Variant; First: Boolean; Last: Boolean); {* Процедура для "покраски" сегментов текста } procedure ValidateLine(aLine: Tl3String; aCodePage: Integer); {* Процедура для проверки корректности строки } procedure ValidateText(aText: Tl3String; aValidateText: Tl3String = nil); {* Проверяет строку на наличие одинаковых сегментов "утратил силу" и "Не вступил в силу" и если возможно объединяет их (пририсовывая ко всему тексту). Если aValidateText <> nil проверяем по этой строке, а aText только изменяем. } function IsStyleEqual(aParaStyle: Integer; aSegmentStyle: Integer): Boolean; {* Сравнивает два стиля с точки зрения выливки в NSRC. } end;//IevTextPainter IevJoinGenerator = interface {* Объект определяющий надо ли объединять параграфы при вставке } ['{8772A98D-28F8-446E-9879-9B32BE75D08D}'] procedure pm_SetNeedJoin(aValue: Boolean); procedure pm_SetAtEnd(aValue: Boolean); procedure pm_SetNeedSkipSubDocuments(aValue: Boolean); procedure Set_LoadFlags(aValue: TevLoadFlags); property NeedJoin: Boolean write pm_SetNeedJoin; {* Свойство определяющее надо ли объединять параграфы при вставке } property AtEnd: Boolean write pm_SetAtEnd; property NeedSkipSubDocuments: Boolean write pm_SetNeedSkipSubDocuments; property LoadFlags: TevLoadFlags write Set_LoadFlags; {* Флаги загрузки } end;//IevJoinGenerator IevNSRCExport = interface ['{E627D909-251B-410E-95CF-C8BAD64F222A}'] procedure SetExportDirectory(const aDirName: AnsiString); procedure SetExternalDocHandle(anID: Integer); end;//IevNSRCExport implementation uses l3ImplUses //#UC START# *4A253C760202impl_uses* //#UC END# *4A253C760202impl_uses* ; end.
unit Providers.Mascara.Hora; interface uses Providers.Mascaras.Intf, System.MaskUtils, System.SysUtils; type TMascaraHora = class(TInterfacedObject, IMascaras) private procedure RemoveDoisPontos(var Value: string); public function ExecMask(Value: string): string; end; implementation { TMascaraHora } function TMascaraHora.ExecMask(Value: string): string; begin RemoveDoisPontos(Value); Result := FormatMaskText('00\:00;0;', Value); end; procedure TMascaraHora.RemoveDoisPontos(var Value: string); begin Delete(Value, AnsiPos(':', Value), 1); end; end.
unit ChromeLikeTabSetUtils; interface uses Windows, SysUtils, Controls, Classes, Graphics, Messages, ExtCtrls, Forms, GraphUtil, Math, GDIPObj, GDIPAPI, ImgList, ActiveX, ChromeLikeTabSetTypes; function IsPtInRect(const aPoint: TPoint; const aRect: TRect): Boolean; function MakeGDIPColor(aColor: TColor; aAlpha: Byte = 255): Cardinal; function SameRect(const aRect1: TRect; const aRect2: TRect): Boolean; function ColorBetween(aColorA: TColor; aColorB: TColor; aPercent: Integer): TColor; function IntegerBetween(aIntA: Integer;aIntB: Integer; aPercent: Integer): Integer; function SingleBetween(aSingA: Single; aSingB: Single; aPercent: Integer): Single; function ImageListToTGPImage(aImageList: TCustomImageList; aImageIndex: Integer): TGPImage; function RectToGPRectF(const aRect: TRect): TGPRectF; function RectToGPRect(const aRect: TRect): TGPRect; function GPRectToRect(const aRect: TGPRect): TRect; function PointToGPPoint(const aPt: TPoint): TGPPoint; function IconToGPImage(aIcon: TIcon): TGPImage; function BitmapToGPBitmap(aBitmap: TBitmap): TGPBitmap; procedure ClearBitmap(aBitmap: TBitmap); function ContrastingColor(Color: TColor): TColor; function RectHeight(Rect: TRect): Integer; function RectWidth(Rect: TRect): Integer; function RectInflate(const aRect: TRect; aValue: Integer): TRect; procedure SetColorAlpha(aBitmap: TBitmap; aColor: TColor; aNewAlpha: Byte); function TransformRect(const aStartRect: TRect; const aEndRect: TRect; aCurrentTicks: Cardinal; aEndTicks: Cardinal; aEaseType: TChromeLikeTabEaseType): TRect; function CalculateEase(CurrentTime, StartValue, ChangeInValue, Duration: Real; EaseType: TChromeLikeTabEaseType): Real; overload; function CalculateEase(StartPos, EndPos, PositionPct: Real; EaseType: TChromeLikeTabEaseType): Real; overload; procedure ResetMouseControl; function PlaceRectInCenter(const aSize: TSize; const aOuterRect: TRect; aLeftMargin: Integer; aTopMargin: Integer; aRightMargin: Integer; aBottomMargin: Integer): TRect; function MakeTSize(aCx: Integer; aCy: Integer): TSize; implementation uses Types, vtInterfaces, l3Memory; function CalculateEase(CurrentTime, StartValue, ChangeInValue, Duration: Real; EaseType: TChromeLikeTabEaseType): Real; begin case EaseType of ttNone: begin Result := 0; end; ttLinearTween: begin Result := ChangeInValue * CurrentTime / Duration + StartValue; end; ttEaseInQuad: begin CurrentTime := CurrentTime / Duration; Result := ChangeInValue * CurrentTime * CurrentTime + StartValue; end; ttEaseOutQuad: begin CurrentTime := CurrentTime / Duration; Result := -ChangeInValue * CurrentTime * (CurrentTime-2) + StartValue; end; ttEaseInOutQuad: begin CurrentTime := CurrentTime / (Duration / 2); if CurrentTime < 1 then Result := ChangeInValue / 2 * CurrentTime * CurrentTime + StartValue else begin CurrentTime := CurrentTime - 1; Result := -ChangeInValue / 2 * (CurrentTime * (CurrentTime - 2) - 1) + StartValue; end; end; ttEaseInCubic: begin CurrentTime := CurrentTime / Duration; Result := ChangeInValue * CurrentTime * CurrentTime * CurrentTime + StartValue; end; ttEaseOutCubic: begin CurrentTime := (CurrentTime / Duration) - 1; Result := ChangeInValue * ( CurrentTime * CurrentTime * CurrentTime + 1) + StartValue; end; ttEaseInOutCubic: begin CurrentTime := CurrentTime / (Duration / 2); if CurrentTime < 1 then Result := ChangeInValue / 2 * CurrentTime * CurrentTime * CurrentTime + StartValue else begin CurrentTime := CurrentTime - 2; Result := ChangeInValue / 2 * (CurrentTime * CurrentTime * CurrentTime + 2) + StartValue; end; end; ttEaseInQuart: begin CurrentTime := CurrentTime / Duration; Result := ChangeInValue * CurrentTime * CurrentTime * CurrentTime * CurrentTime + StartValue; end; ttEaseOutQuart: begin CurrentTime := (CurrentTime / Duration) - 1; Result := -ChangeInValue * (CurrentTime * CurrentTime * CurrentTime * CurrentTime - 1) + StartValue; end; ttEaseInOutQuart: begin CurrentTime := CurrentTime / (Duration / 2); if CurrentTime < 1 then Result := ChangeInValue / 2 * CurrentTime * CurrentTime * CurrentTime * CurrentTime + StartValue else begin CurrentTime := CurrentTime - 2; Result := -ChangeInValue / 2 * (CurrentTime * CurrentTime * CurrentTime * CurrentTime - 2) + StartValue; end; end; ttEaseInQuint: begin CurrentTime := CurrentTime / Duration; Result := ChangeInValue * CurrentTime * CurrentTime * CurrentTime * CurrentTime * CurrentTime + StartValue; end; ttEaseOutQuint: begin CurrentTime := (CurrentTime / Duration) - 1; Result := ChangeInValue * (CurrentTime * CurrentTime * CurrentTime * CurrentTime * CurrentTime + 1) + StartValue; end; ttEaseInOutQuint: begin CurrentTime := CurrentTime / (Duration / 2); if CurrentTime < 1 then Result := ChangeInValue / 2 * CurrentTime * CurrentTime * CurrentTime * CurrentTime * CurrentTime + StartValue else begin CurrentTime := CurrentTime - 2; Result := ChangeInValue / 2 * (CurrentTime * CurrentTime * CurrentTime * CurrentTime * CurrentTime + 2) + StartValue; end; end; ttEaseInSine: begin Result := -ChangeInValue * Cos(CurrentTime / Duration * (PI / 2)) + ChangeInValue + StartValue; end; ttEaseOutSine: begin Result := ChangeInValue * Sin(CurrentTime / Duration * (PI / 2)) + StartValue; end; ttEaseInOutSine: begin Result := -ChangeInValue / 2 * (Cos(PI * CurrentTime / Duration) - 1) + StartValue; end; ttEaseInExpo: begin Result := ChangeInValue * Power(2, 10 * (CurrentTime / Duration - 1) ) + StartValue; end; ttEaseOutExpo: begin Result := ChangeInValue * (-Power(2, -10 * CurrentTime / Duration ) + 1 ) + StartValue; end; ttEaseInOutExpo: begin CurrentTime := CurrentTime / (Duration/2); if CurrentTime < 1 then Result := ChangeInValue / 2 * Power(2, 10 * (CurrentTime - 1) ) + StartValue else begin CurrentTime := CurrentTime - 1; Result := ChangeInValue / 2 * (-Power(2, -10 * CurrentTime) + 2 ) + StartValue; end; end; ttEaseInCirc: begin CurrentTime := CurrentTime / Duration; Result := -ChangeInValue * (Sqrt(1 - CurrentTime * CurrentTime) - 1) + StartValue; end; ttEaseOutCirc: begin CurrentTime := (CurrentTime / Duration) - 1; Result := ChangeInValue * Sqrt(1 - CurrentTime * CurrentTime) + StartValue; end; ttEaseInOutCirc: begin CurrentTime := CurrentTime / (Duration / 2); if CurrentTime < 1 then Result := -ChangeInValue / 2 * (Sqrt(1 - CurrentTime * CurrentTime) - 1) + StartValue else begin CurrentTime := CurrentTime - 2; Result := ChangeInValue / 2 * (Sqrt(1 - CurrentTime * CurrentTime) + 1) + StartValue; end; end; else begin Result := 0; Assert(FALSE, 'Invalid Ease Type'); end; end; end; function CalculateEase(StartPos, EndPos, PositionPct: Real; EaseType: TChromeLikeTabEaseType): Real; var t, b, c, d: Real; begin c := EndPos - StartPos; d := 100; t := PositionPct; b := StartPos; Result := CalculateEase(t, b, c, d, EaseType); end; function TransformRect(const aStartRect: TRect; const aEndRect: TRect; aCurrentTicks: Cardinal; aEndTicks: Cardinal; aEaseType: TChromeLikeTabEaseType): TRect; function TransformInteger(aStartInt: Integer; aEndInt: Integer): Integer; begin TransformInteger := Round(CalculateEase(aCurrentTicks, aStartInt, aEndInt - aStartInt, aEndTicks, aEaseType)); end; begin Result.Left := TransformInteger(aStartRect.Left, aEndRect.Left); Result.Top := TransformInteger(aStartRect.Top, aEndRect.Top); Result.Right := TransformInteger(aStartRect.Right, aEndRect.Right); Result.Bottom := TransformInteger(aStartRect.Bottom, aEndRect.Bottom); end; function ContrastingColor(Color: TColor): TColor; begin Color := ColorToRGB(Color); Result := (Color+$000080) and $0000FF + (Color+$008000) and $00FF00 + (Color+$800000) and $FF0000; end; function RectHeight(Rect: TRect): Integer; begin Result := Rect.Bottom - Rect.Top; end; function RectWidth(Rect: TRect): Integer; begin Result := Rect.Right - Rect.Left; end; procedure ClearBitmap(aBitmap: TBitmap); var l_Graphics: TGPGraphics; l_Brush: TGPBrush; l_Color: TGPColor; begin l_Graphics := TGPGraphics.Create(aBitmap.Handle); try l_Color := MakeGDIPColor(clBlack, 0); l_Brush := TGPLinearGradientBrush.Create(MakePoint(0, 0), MakePoint(0, aBitmap.Height), l_Color, l_Color); try l_Graphics.FillRectangle(l_Brush, 0, 0, aBitmap.Width, aBitmap.Height); finally FreeAndNil(l_Brush); end; finally FreeAndNil(l_Graphics); end; end; function RectInflate(const aRect: TRect; aValue: Integer): TRect; begin Result := Rect(aRect.Left + aValue, aRect.Top + aValue, aRect.Right - aValue, aRect.Bottom - aValue); end; function RectToGPRectF(const aRect: TRect): TGPRectF; begin Result.X := aRect.Left; Result.Y := aRect.Top; Result.Width := RectWidth(aRect); Result.Height := RectHeight(aRect); end; function RectToGPRect(const ARect: TRect): TGPRect; begin Result.X := aRect.Left; Result.Y := aRect.Top; Result.Width := RectWidth(aRect); Result.Height := RectHeight(aRect); end; function GPRectToRect(const aRect: TGPRect): TRect; begin Result.Left := aRect.X; Result.Top := aRect.Y; Result.Right := aRect.X + aRect.Width; Result.Bottom := aRect.Y + aRect.Height; end; function PointToGPPoint(const aPt: TPoint): TGPPoint; begin Result.X := aPt.X; Result.Y := aPt.Y; end; function IconToGPImage(aIcon: TIcon): TGPImage; var l_MemStream: Tl3MemoryStream; begin l_MemStream := Tl3MemoryStream.Create; try aIcon.SaveToStream(l_MemStream); l_MemStream.Position := 0; Result := TGPImage.Create(l_MemStream); finally FreeAndNil(l_MemStream); end; end; function BitmapToGPBitmap(aBitmap: TBitmap): TGPBitmap; var l_MemStream: Tl3MemoryStream; begin l_MemStream := Tl3MemoryStream.Create; try aBitmap.SaveToStream(l_MemStream); l_MemStream.Position := 0; Result := TGPBitmap.Create(l_MemStream); finally FreeAndNil(l_MemStream); end; end; function ImageListToTGPImage(aImageList: TCustomImageList; aImageIndex: Integer): TGPImage; var l_ImageList: IvtFlashImageList; l_MemStream: Tl3MemoryStream; begin if Supports(aImageList, IvtFlashImageList, l_ImageList) then try l_MemStream := Tl3MemoryStream.Create; try l_ImageList.SaveImageToStream(l_MemStream, aImageIndex, bpp24); l_MemStream.Position := 0; Result := TGPBitmap.Create(l_MemStream, True); finally FreeAndNil(l_MemStream); end; finally l_ImageList := nil; end; end; function IntegerBetween(aIntA: Integer; aIntB: Integer; aPercent: Integer): Integer; begin Result := aPercent * (aIntB - aIntA) div 100 + aIntA; end; function SingleBetween(aSingA: Single; aSingB: Single; aPercent: Integer): Single; begin Result := aPercent * (aSingB - aSingA) / 100 + aSingA; end; function ColorBetween(aColorA: TColor; aColorB: TColor; aPercent: Integer): TColor; var l_R1: Byte; l_G1: Byte; l_B1: Byte; l_R2: Byte; l_G2: Byte; l_B2: Byte; begin l_R1:= GetRValue(aColorA); l_G1:= GetGValue(aColorA); l_B1:= GetBValue(aColorA); l_R2:= GetRValue(aColorB); l_G2:= GetGValue(aColorB); l_B2:= GetBValue(aColorB); Result:= RGB(aPercent * (l_R2 - l_R1) div 100 + l_R1, aPercent * (l_G2 - l_G1) div 100 + l_G1, aPercent * (l_B2 - l_B1) div 100 + l_B1); end; function SameRect(const aRect1: TRect; const aRect2: TRect): Boolean; begin Result := (aRect1.Left = aRect2.Left) and (aRect1.Top = aRect2.Top) and (aRect1.Right = aRect2.Right) and (aRect1.Bottom = aRect2.Bottom); end; function IsPtInRect(const aPoint: TPoint; const aRect: TRect): Boolean; begin Result := (aPoint.X >= aRect.Left) and (aPoint.Y >= aRect.Top) and (aPoint.X <= aRect.Right) and (aPoint.Y <= aRect.Bottom); end; function MakeGDIPColor(aColor: TColor; aAlpha: Byte = 255): Cardinal; var l_tmpRGB : TColorRef; begin l_tmpRGB := ColorToRGB(aColor); Result := ((DWORD(GetBValue(l_tmpRGB)) shl BlueShift) or (DWORD(GetGValue(l_tmpRGB)) shl GreenShift) or (DWORD(GetRValue(l_tmpRGB)) shl RedShift) or (DWORD(aAlpha) shl AlphaShift)); end; procedure SetColorAlpha(aBitmap: TBitmap; aColor: TColor; aNewAlpha: Byte); var l_Row, l_Col: Integer; l_p: PRGBQuad; l_PreMult: array[byte, byte] of byte; begin // precalculate all possible values of a*b for l_Row := 0 to 255 do for l_Col := l_Row to 255 do begin l_PreMult[l_Row, l_Col] := l_Row * l_Col div 255; if (l_Row <> l_Col) then l_PreMult[l_Col, l_Row] := l_PreMult[l_Row, l_Col]; // a*b = b*a end; for l_Row := 0 to Pred(aBitmap.Height) do begin l_Col := aBitmap.Width; l_p := aBitmap.ScanLine[l_Row]; while (l_Col > 0) do begin if (GetRed(aColor) = l_p.rgbRed) and (GetBlue(aColor) = l_p.rgbBlue) and (GetGreen(aColor) = l_p.rgbGreen) then begin l_p.rgbReserved := aNewAlpha; l_p.rgbBlue := l_PreMult[l_p.rgbReserved, l_p.rgbBlue]; l_p.rgbGreen := l_PreMult[l_p.rgbReserved, l_p.rgbGreen]; l_p.rgbRed := l_PreMult[l_p.rgbReserved, l_p.rgbRed]; end; Inc(l_p); Dec(l_Col); end; end; end; type THackApplication = class(TComponent) private FHandle: HWnd; FBiDiMode: TBiDiMode; FBiDiKeyboard: string; FNonBiDiKeyboard: string; FObjectInstance: Pointer; FMainForm: TForm; FMouseControl: TControl; end; procedure ResetMouseControl; begin THackApplication(Application).FMouseControl := nil; end; function PlaceRectInCenter(const aSize: TSize; const aOuterRect: TRect; aLeftMargin: Integer; aTopMargin: Integer; aRightMargin: Integer; aBottomMargin: Integer): TRect; var l_Rect: TRect; l_RectCenter: TPoint; l_Offsets: TSize; begin l_Rect := aOuterRect; Inc(l_Rect.Left, aLeftMargin); Inc(l_Rect.Top, aTopMargin); Dec(l_Rect.Right, aRightMargin); Dec(l_Rect.Bottom, aBottomMargin); l_RectCenter := CenterPoint(l_Rect); l_Offsets.cx := aSize.cx div 2; l_Offsets.cy := aSize.cy div 2; with Result do begin TopLeft := Point(l_RectCenter.X - l_Offsets.cx, l_RectCenter.Y - l_Offsets.cy); BottomRight := Point(l_RectCenter.X + l_Offsets.cx, l_RectCenter.Y + l_Offsets.cy); end; end; function MakeTSize(aCx: Integer; aCy: Integer): TSize; begin Result.cx := aCx; Result.cy := aCy; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpStreams; {$I ..\..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes; resourcestring SDataOverflow = 'Data Overflow'; type TStreams = class sealed(TObject) strict private const BufferSize = Int32(512); public class procedure Drain(const inStr: TStream); static; class function ReadAll(const inStr: TStream): TCryptoLibByteArray; static; inline; class function ReadAllLimited(const inStr: TStream; limit: Int32) : TCryptoLibByteArray; static; inline; class function ReadFully(const inStr: TStream; var buf: TCryptoLibByteArray) : Int32; overload; static; inline; class function ReadFully(const inStr: TStream; var buf: TCryptoLibByteArray; off, len: Int32): Int32; overload; static; class procedure PipeAll(const inStr, outStr: TStream); static; /// <summary> /// Pipe all bytes from <c>inStr</c> to <c>outStr</c>, throwing <c> /// EStreamOverflowCryptoLibException</c> if greater than <c>limit</c> bytes in <c> /// inStr</c>. /// </summary> /// <param name="inStr"> /// Input Stream /// </param> /// <param name="limit"> /// Limit /// </param> /// <param name="outStr"> /// Output Stream /// </param> /// <returns> /// The number of bytes actually transferred, if not greater than <c> /// limit</c> /// </returns> /// <exception cref="EStreamOverflowCryptoLibException" /> class function PipeAllLimited(const inStr: TStream; limit: Int64; const outStr: TStream): Int64; static; class procedure WriteBufTo(const buf: TMemoryStream; const output: TStream); overload; static; inline; class function WriteBufTo(const buf: TMemoryStream; const output: TCryptoLibByteArray; offset: Int32): Int32; overload; static; inline; class procedure WriteZeroes(const outStr: TStream; count: Int64); static; end; implementation uses ClpStreamSorter; // included here to avoid circular dependency :) { TStreams } class procedure TStreams.Drain(const inStr: TStream); var bs: TCryptoLibByteArray; begin System.SetLength(bs, BufferSize); while (TStreamSorter.Read(inStr, bs, 0, System.Length(bs)) > 0) do begin // do nothing end; end; class procedure TStreams.PipeAll(const inStr, outStr: TStream); var numRead: Int32; bs: TCryptoLibByteArray; begin System.SetLength(bs, BufferSize); numRead := TStreamSorter.Read(inStr, bs, 0, System.Length(bs)); while ((numRead) > 0) do begin outStr.Write(bs[0], numRead); numRead := TStreamSorter.Read(inStr, bs, 0, System.Length(bs)); end; end; class function TStreams.PipeAllLimited(const inStr: TStream; limit: Int64; const outStr: TStream): Int64; var bs: TCryptoLibByteArray; numRead: Int32; total: Int64; begin System.SetLength(bs, BufferSize); total := 0; numRead := TStreamSorter.Read(inStr, bs, 0, System.Length(bs)); while ((numRead) > 0) do begin if ((limit - total) < numRead) then begin raise EStreamOverflowCryptoLibException.CreateRes(@SDataOverflow); end; total := total + numRead; outStr.Write(bs[0], numRead); numRead := TStreamSorter.Read(inStr, bs, 0, System.Length(bs)); end; Result := total; end; class function TStreams.ReadAll(const inStr: TStream): TCryptoLibByteArray; var buf: TMemoryStream; begin buf := TMemoryStream.Create(); try PipeAll(inStr, buf); System.SetLength(Result, buf.Size); buf.Position := 0; buf.Read(Result[0], buf.Size); finally buf.Free; end; end; class function TStreams.ReadAllLimited(const inStr: TStream; limit: Int32) : TCryptoLibByteArray; var buf: TMemoryStream; begin buf := TMemoryStream.Create(); try PipeAllLimited(inStr, limit, buf); System.SetLength(Result, buf.Size); buf.Position := 0; buf.Read(Result[0], buf.Size); finally buf.Free; end; end; class function TStreams.ReadFully(const inStr: TStream; var buf: TCryptoLibByteArray; off, len: Int32): Int32; var totalRead, numRead: Int32; begin totalRead := 0; while (totalRead < len) do begin numRead := TStreamSorter.Read(inStr, buf, off + totalRead, len - totalRead); if (numRead < 1) then begin break; end; totalRead := totalRead + numRead; end; Result := totalRead; end; class function TStreams.WriteBufTo(const buf: TMemoryStream; const output: TCryptoLibByteArray; offset: Int32): Int32; var bytes: TCryptoLibByteArray; begin buf.Position := 0; System.SetLength(bytes, buf.Size); buf.Read(bytes[0], buf.Size); System.Move(bytes[0], output[offset], System.Length(bytes) * System.SizeOf(Byte)); Result := System.Length(bytes); end; class procedure TStreams.WriteZeroes(const outStr: TStream; count: Int64); var zeroes: TCryptoLibByteArray; begin System.SetLength(zeroes, BufferSize); while (count > BufferSize) do begin outStr.Write(zeroes[0], BufferSize); count := count - BufferSize; end; outStr.Write(zeroes[0], Int32(count)); end; class function TStreams.ReadFully(const inStr: TStream; var buf: TCryptoLibByteArray): Int32; begin Result := ReadFully(inStr, buf, 0, System.Length(buf)); end; class procedure TStreams.WriteBufTo(const buf: TMemoryStream; const output: TStream); begin output.CopyFrom(buf, buf.Size); end; end.
unit aeOBB; interface uses aeBoundingVolume, types, windows, aeMaths, aeConst, math, aetypes, aeVectorBuffer, aeIndexBuffer, aeMesh; type TaeOBB = class(TaeBoundingVolume) public constructor Create; destructor Destroy; override; function calculateBoundingVolume(vio: TaeVertexIndexBuffer; avarageCenter: boolean = false): boolean; override; function collideWith(otherBV: TaeBoundingVolume; var transformMatrix: TaeMatrix44): boolean; override; function Intersect(ray: TaeRay3; transformMatrix: TaeMatrix44): boolean; override; procedure clear; override; /// <remarks> /// Returns the x,y,z direction distances to box insides /// </remarks> function getHalfwidths: TVectorArray; function getBox: TaeMesh; private _calculatedBox: TaeMesh; _halfwidths: TVectorArray; // x,y,z direction distances to box insides end; implementation { TaeAABB } function TaeOBB.calculateBoundingVolume(vio: TaeVertexIndexBuffer; avarageCenter: boolean = false): boolean; var i, c: Integer; tempTri: TVectorArray; tempCenter: TPoint3D; tempCompareDistance: TVectorArray; begin tempCenter.Create(0, 0, 0); tempCompareDistance[0] := 0; tempCompareDistance[1] := 0; tempCompareDistance[2] := 0; c := 0; for i := 0 to vio.indexBuffer.Count - 1 do begin tempTri := vio.vertexBuffer.GetVector(vio.indexBuffer.GetIndex(i)); // tempTri := TaeTVectorArrayPointer(dword(v0) + (i * 12))^; if (avarageCenter) then begin // start calculating the sum of all triangle coordinates, we will use this later for the avarage middle tempCenter.X := tempCenter.X + tempTri[0]; tempCenter.y := tempCenter.y + tempTri[1]; tempCenter.z := tempCenter.z + tempTri[2]; inc(c); end; // start comparing distances. We want the max. if (abs(tempTri[0]) > tempCompareDistance[0]) then tempCompareDistance[0] := abs(tempTri[0]); if (abs(tempTri[1]) > tempCompareDistance[1]) then tempCompareDistance[1] := abs(tempTri[1]); if (abs(tempTri[2]) > tempCompareDistance[2]) then tempCompareDistance[2] := abs(tempTri[2]); end; // take 000 as center, or calculate avarage? if (avarageCenter) then begin // okay, now calculate the middle by avarage vertex position... self._center.X := tempCenter.X / c; self._center.y := tempCenter.y / c; self._center.z := tempCenter.z / c; end else self._center.Create(0, 0, 0); // set the maximums... self._halfwidths[0] := tempCompareDistance[0]; self._halfwidths[1] := tempCompareDistance[1]; self._halfwidths[2] := tempCompareDistance[2]; end; procedure TaeOBB.clear; begin inherited; self._halfwidths[0] := 0; self._halfwidths[1] := 0; self._halfwidths[2] := 0; self._center.Create(0, 0, 0); if (self._calculatedBox.GetVertexBuffer <> nil) then self._calculatedBox.GetVertexBuffer.clear; if (self._calculatedBox.GetIndexBuffer <> nil) then self._calculatedBox.GetIndexBuffer.clear; end; function TaeOBB.collideWith(otherBV: TaeBoundingVolume; var transformMatrix: TaeMatrix44): boolean; begin case otherBV.getType() of AE_BOUNDINGVOLUME_TYPE_OBB: begin // separating axis test end; end; end; constructor TaeOBB.Create; begin inherited Create; self._calculatedBox := TaeMesh.Create; self._type := AE_BOUNDINGVOLUME_TYPE_OBB; self.clear; end; destructor TaeOBB.Destroy; begin self._calculatedBox.Free; inherited; end; function TaeOBB.getBox: TaeMesh; var v: TVectorArray; vb: TaeVectorBuffer; ib: TaeIndexBuffer; begin // birds view, first level = top // first level second level // 0 1 7 6 // 0--0 0--0 // | | | | // 0--0 0--0 // 3 2 4 5 // GL_LINE_STRIP! if (self._calculatedBox.GetVertexBuffer = nil) then begin vb := TaeVectorBuffer.Create; self._calculatedBox.SetVertexBuffer(vb); end else vb := self._calculatedBox.GetVertexBuffer; if (self._calculatedBox.GetIndexBuffer = nil) then begin ib := TaeIndexBuffer.Create; self._calculatedBox.SetIndexBuffer(ib); end else ib := self._calculatedBox.GetIndexBuffer; if vb.Empty then begin vb.clear; ib.clear; ib.PreallocateIndices(20); vb.PreallocateVectors(20); // upper quad v[0] := self._center.X - self._halfwidths[0]; v[1] := self._center.y + self._halfwidths[1]; v[2] := self._center.z + self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(0); v[0] := self._center.X + self._halfwidths[0]; v[1] := self._center.y + self._halfwidths[1]; v[2] := self._center.z + self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(1); v[0] := self._center.X + self._halfwidths[0]; v[1] := self._center.y + self._halfwidths[1]; v[2] := self._center.z - self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(2); v[0] := self._center.X - self._halfwidths[0]; v[1] := self._center.y + self._halfwidths[1]; v[2] := self._center.z - self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(3); ib.AddIndex(0); // lower quad v[0] := self._center.X - self._halfwidths[0]; v[1] := self._center.y - self._halfwidths[1]; v[2] := self._center.z + self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(4); v[0] := self._center.X + self._halfwidths[0]; v[1] := self._center.y - self._halfwidths[1]; v[2] := self._center.z + self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(5); v[0] := self._center.X + self._halfwidths[0]; v[1] := self._center.y - self._halfwidths[1]; v[2] := self._center.z - self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(6); v[0] := self._center.X - self._halfwidths[0]; v[1] := self._center.y - self._halfwidths[1]; v[2] := self._center.z - self._halfwidths[2]; vb.AddVector(v); ib.AddIndex(7); ib.AddIndex(4); ib.AddIndex(5); ib.AddIndex(1); ib.AddIndex(2); ib.AddIndex(6); ib.AddIndex(7); ib.AddIndex(3); ib.Pack; vb.Pack; end; result := self._calculatedBox; end; function TaeOBB.getHalfwidths: TVectorArray; begin result := self._halfwidths; end; function TaeOBB.Intersect(ray: TaeRay3; transformMatrix: TaeMatrix44): boolean; var maxS, minT: single; diff: TPoint3D; i: Integer; axis: TPoint3D; e, f, t1, t2, temp: single; OBBposition_worldspace: TPoint3D; begin maxS := 100000.0; minT := 0.0;; OBBposition_worldspace := self._center * transformMatrix; // compute difference vector diff := OBBposition_worldspace - ray.GetOrgin; // for each axis do for i := 0 to 2 do begin axis := transformMatrix.GetRotationVectorAxis(i); // project relative vector onto axis e := axis.DotProduct(diff); f := ray.GetDirection().DotProduct(axis); // Standard case if (abs(f) > 0.001) then begin t1 := (e - self._halfwidths[i]) / f; // float t1 = (e+aabb_min.x)/f; t2 := (e + self._halfwidths[i]) / f; // float t2 = (e+aabb_max.x)/f; // fix order // We want t1 to represent the nearest intersection, // so if it's not the case, invert t1 and t2 if (t1 > t2) then begin temp := t1; t1 := t2; t2 := temp; end; // tMax is the nearest "far" intersection (amongst the X,Y and Z planes pairs) // adjust min and max values if (t1 > minT) then minT := t1; if (t2 < maxS) then maxS := t2; // ray passes by box? if (maxS < minT) then begin result := false; exit; end; end else begin // Rare case : the ray is almost parallel to the planes, so they don't have any "intersection" if ((-e - self._halfwidths[i] > 0.0) or (-e + self._halfwidths[i] < 0.0)) then begin result := false; exit; end; end; end; // we have an intersection result := true; end; end.
unit RegisterWebinarRequestUnit; interface uses REST.Json.Types, SysUtils, GenericParametersUnit, CommonTypesUnit, EnumsUnit; type TRegisterWebinarRequest = class(TGenericParameters) private [JSONName('email_address')] FEMail: String; [JSONName('first_name')] FFirstName: String; [JSONName('last_name')] FLastName: String; [JSONName('phone_number')] FPhone: String; [JSONName('company_name')] FCompany: String; [JSONName('member_id')] FMemberId: integer; [JSONName('webiinar_date')] FDate: String; public constructor Create(EMail, FirstName, LastName, Phone, Company: String; MemberId: integer; Date: TDateTime); reintroduce; end; implementation constructor TRegisterWebinarRequest.Create( EMail, FirstName, LastName, Phone, Company: String; MemberId: integer; Date: TDateTime); begin Inherited Create; FEMail := EMail; FFirstName := FirstName; FLastName := LastName; FPhone := Phone; FCompany := Company; FMemberId := MemberId; DateTimeToString(FDate, 'yyyy-mm-dd hh:mm:ss', Date); end; end.
unit uQuickViewPanel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls, fViewer, uFileViewNotebook, uFile, uFileSource, uFileView; type { TQuickViewPanel } TQuickViewPanel = class(TPanel) private FFirstFile: Boolean; FFileViewPage: TFileViewPage; FFileView: TFileView; FFileSource: IFileSource; FViewer: TfrmViewer; FFileName: String; public constructor Create(TheOwner: TComponent; aParent: TFileViewPage); reintroduce; destructor Destroy; override; procedure CreateViewer(aFileView: TFileView); procedure LoadFile(const aFileName: String); procedure FileViewChangeActiveFile(Sender: TFileView; const aFile : TFile); end; procedure QuickViewShow(aFileViewPage: TFileViewPage; aFileView: TFileView); procedure QuickViewClose; var QuickViewPanel: TQuickViewPanel; implementation uses LCLProc, Forms, Controls, uTempFileSystemFileSource, uFileSourceProperty, uFileSourceOperation, uFileSourceOperationTypes; procedure QuickViewShow(aFileViewPage: TFileViewPage; aFileView: TFileView); var aFile: TFile = nil; begin QuickViewPanel:= TQuickViewPanel.Create(Application, aFileViewPage); QuickViewPanel.CreateViewer(aFileView); aFile := aFileView.CloneActiveFile; try QuickViewPanel.FileViewChangeActiveFile(aFileView, aFile); finally FreeAndNil(aFile); end; aFileView.OnChangeActiveFile:= @QuickViewPanel.FileViewChangeActiveFile; end; procedure QuickViewClose; begin FreeThenNil(QuickViewPanel); end; { TQuickViewPanel } constructor TQuickViewPanel.Create(TheOwner: TComponent; aParent: TFileViewPage); begin inherited Create(TheOwner); Parent:= aParent; Align:= alClient; FFileViewPage:= aParent; FFileSource:= nil; FViewer:= nil; end; destructor TQuickViewPanel.Destroy; begin FFileView.OnChangeActiveFile:= nil; FViewer.ExitPluginMode; FFileViewPage.FileView.Visible:= True; FreeThenNil(FViewer); FFileSource:= nil; FFileView.SetFocus; inherited Destroy; end; procedure TQuickViewPanel.CreateViewer(aFileView: TFileView); begin FViewer:= TfrmViewer.Create(Self, nil, True); FViewer.Parent:= Self; FViewer.BorderStyle:= bsNone; FViewer.Align:= alClient; FFirstFile:= True; FFileView:= aFileView; FFileSource:= aFileView.FileSource; FFileViewPage.FileView.Visible:= False; end; procedure TQuickViewPanel.LoadFile(const aFileName: String); begin if FFirstFile then begin FFirstFile:= False; FViewer.LoadFile(aFileName); FViewer.Show; end else begin FViewer.LoadNextFile(aFileName); end; // Viewer can steal focus, so restore it if not FFileView.Focused then FFileView.SetFocus; end; procedure TQuickViewPanel.FileViewChangeActiveFile(Sender: TFileView; const aFile: TFile); var ActiveFile: TFile = nil; TempFiles: TFiles = nil; TempFileSource: ITempFileSystemFileSource = nil; Operation: TFileSourceOperation = nil; begin if not (Assigned(aFile) and (aFile.Name <> '..')) then Exit; try // If files are links to local files if (fspLinksToLocalFiles in Sender.FileSource.Properties) then begin if aFile.IsDirectory or aFile.IsLinkToDirectory then Exit; FFileSource := Sender.FileSource; ActiveFile:= aFile.Clone; if not FFileSource.GetLocalName(ActiveFile) then Exit; end // If files not directly accessible copy them to temp file source. else if not (fspDirectAccess in Sender.FileSource.Properties) then begin if aFile.IsDirectory or SameText(FFileName, aFile.Name) then Exit; if not (fsoCopyOut in Sender.FileSource.GetOperationsTypes) then Exit; ActiveFile:= aFile.Clone; TempFiles:= TFiles.Create(Sender.CurrentPath); TempFiles.Add(aFile.Clone); if FFileSource.IsClass(TTempFileSystemFileSource) then TempFileSource := (FFileSource as ITempFileSystemFileSource) else TempFileSource := TTempFileSystemFileSource.GetFileSource; Operation := Sender.FileSource.CreateCopyOutOperation( TempFileSource, TempFiles, TempFileSource.FileSystemRoot); if not Assigned(Operation) then Exit; Operation.Execute; FreeAndNil(Operation); FFileName:= ActiveFile.Name; FFileSource := TempFileSource; ActiveFile.Path:= TempFileSource.FileSystemRoot; end else begin // We can use the file source directly. FFileSource := Sender.FileSource; ActiveFile:= aFile.Clone; end; LoadFile(ActiveFile.FullPath); finally FreeThenNil(TempFiles); FreeThenNil(ActiveFile); end; end; end.
(* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Initial Developer of this code is John Hansen. * Portions created by John Hansen are Copyright (C) 2009 John Hansen. * All Rights Reserved. * *) unit uPreprocess; interface uses Classes, Contnrs, SysUtils, mwGenericLex, uGenLexer, uNBCCommon; type EPreprocessorException = class(Exception) private fLineNo : integer; public constructor Create(const msg : string; const lineno : integer); property LineNo : integer read fLineNo; end; { TMapList } TMapList = class(TStringList) private fConsiderCase: boolean; function GetMapValue(index: integer): string; procedure SetConsiderCase(const AValue: boolean); procedure SetMapValue(index: integer; const Value: string); protected {$IFDEF FPC} function DoCompareText(const s1,s2 : string) : PtrInt; override; {$ENDIF} public constructor Create; function AddEntry(const aName, aValue : string) : integer; procedure AddDefines(aValue : TStrings); procedure Define(const aName : string); procedure Clear; override; procedure Delete(Index: Integer); override; property MapValue[index : integer] : string read GetMapValue write SetMapValue; property ConsiderCase : boolean read fConsiderCase write SetConsiderCase; end; TPreprocessorStatusChangeEvent = procedure(Sender : TObject; const StatusMsg : string) of object; TLangPreprocessor = class private fLangName : TLangName; fWarnings : TStrings; fCalc : TNBCExpParser; fIncludeFilesToSkip : TStrings; IncludeDirs : TStringList; MacroDefs : TMapList; MacroFuncArgs : TMapList; fLevel : integer; fLevelIgnore : TObjectList; fGLC : TGenLexerClass; fLexers : TObjectList; fRecursionDepth : integer; fAddPoundLine: boolean; fOnPreprocessorStatusChange: TPreprocessorStatusChangeEvent; { fVarI : integer; fVarJ : integer; procedure SetThreadName(const name : string); procedure SetCurrentFile(const name : string); procedure SetVarJ(val : integer); procedure SetVarI(val : integer); procedure LoadStandardMacros; } function DoProcessStream(name: string; lineNo: integer; Stream: TMemoryStream; OutStrings: TStrings) : string; function GetLevelIgnoreValue(const lineno : integer): boolean; procedure SwitchLevelIgnoreValue(const lineno : integer); function ProcessIdentifier(const ident : string; Lex: TGenLexer; var lineNo: integer): string; function EvaluateIdentifier(const ident : string) : string; function ReplaceTokens(const tokenstring: string; lineNo : integer; bArgs : boolean): string; function ProcessMacroDefinition(const fname : string; bUndefine : boolean; Lex: TGenLexer; var lineNo: integer): integer; function GenLexerType : TGenLexerClass; function GetDefines: TMapList; function ProcessDefinedFunction(expr : string) : string; function EvaluateExpression(expr : string; lineno : integer) : boolean; function AcquireLexer(const lineNo : integer) : TGenLexer; procedure ReleaseLexer; procedure InitializeLexers(const num: integer); procedure AddOneOrMoreLines(OutStrings: TStrings; const S, name: string; var lineNo: integer); function IgnoringAtLowerLevel(const lineno: integer): boolean; function ImportRIC(const fname, varname : string) : string; function ImportFile(const fname : string; varname : string) : string; function GetPreprocPath(const fname : string; const path : string) : string; procedure DoPreprocessorStatusChange(const Status: string); public class function PreprocessStrings(GLType : TGenLexerClass; const fname : string; aStrings : TStrings; aLN : TLangName; MaxDepth : word) : string; class function PreprocessFile(GLType : TGenLexerClass; const fin, fout : string; aLN : TLangName; MaxDepth : word) : string; constructor Create(GLType : TGenLexerClass; const defIncDir : string; aLN : TLangName; MaxDepth : word); destructor Destroy; override; procedure SkipIncludeFile(const fname : string); function Preprocess(const fname: string; aStrings: TStrings) : string; overload; function Preprocess(const fname: string; aStream: TMemoryStream) : string; overload; procedure AddIncludeDirs(aStrings : TStrings); property Defines : TMapList read GetDefines; property AddPoundLineToMultiLineMacros : boolean read fAddPoundLine write fAddPoundLine; property Warnings : TStrings read fWarnings; property OnPreprocessorStatusChange : TPreprocessorStatusChangeEvent read fOnPreprocessorStatusChange write fOnPreprocessorStatusChange; end; implementation uses Math, uVersionInfo, uLocalizedStrings, uRICComp; type TPreprocLevel = class public Taken : boolean; Ignore : boolean; constructor Create; virtual; end; TIgnoreLevel = class(TPreprocLevel) public constructor Create; override; end; TProcessLevel = class(TPreprocLevel) public constructor Create; override; end; function CountLineEndings(ablock : string) : integer; var tmpSL : TStringList; begin tmpSL := TStringList.Create; try tmpSL.Text := ablock+'_'; Result := tmpSL.Count - 1; finally tmpSL.Free; end; end; { TLangPreprocessor } class function TLangPreprocessor.PreprocessStrings(GLType : TGenLexerClass; const fname : string; aStrings : TStrings; aLN : TLangName; MaxDepth : word) : string; var P : TLangPreprocessor; begin P := TLangPreprocessor.Create(GLType, ExtractFilePath(fname), aLN, MaxDepth); try Result := P.Preprocess(fname, aStrings); finally P.Free; end; end; class function TLangPreprocessor.PreprocessFile(GLType : TGenLexerClass; const fin, fout : string; aLN : TLangName; MaxDepth : word) : string; var SL : TStringList; begin SL := TStringList.Create; try SL.LoadFromFile(fin); Result := TLangPreprocessor.PreprocessStrings(GLType, fin, SL, aLN, MaxDepth); SL.SaveToFile(fout); finally SL.Free; end; end; function TLangPreprocessor.Preprocess(const fname: string; aStream: TMemoryStream) : string; var Strings : TStringList; begin // MacroDefs.Clear; fWarnings.Clear; fLevelIgnore.Clear; IncludeDirs.Add(IncludeTrailingPathDelimiter(ExtractFilePath(fname))); fLevelIgnore.Add(TProcessLevel.Create); // level zero is NOT ignored fLevel := 0; // starting level is zero fRecursionDepth := 0; Strings := TStringList.Create; try Result := DoProcessStream(fname, 0, aStream, Strings); aStream.Size := 0; // empty the stream Strings.SaveToStream(aStream); aStream.Position := 0; finally Strings.Free; end; end; function TLangPreprocessor.Preprocess(const fname : string; aStrings : TStrings) : string; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try aStrings.SaveToStream(Stream); aStrings.Clear; Result := Preprocess(fname, Stream); aStrings.LoadFromStream(Stream); finally Stream.Free; end; end; function TLangPreprocessor.IgnoringAtLowerLevel(const lineno : integer) : boolean; var PL : TPreprocLevel; i : integer; begin Result := False; if (fLevel < 0) or (fLevel >= fLevelIgnore.Count) then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineno); for i := fLevel-1 downto 0 do begin PL := TPreprocLevel(fLevelIgnore[i]); if PL.Ignore then begin Result := True; Break; end; end; end; function TLangPreprocessor.GetLevelIgnoreValue(const lineno : integer) : boolean; var PL : TPreprocLevel; begin if (fLevel < 0) or (fLevel >= fLevelIgnore.Count) then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineno); PL := TPreprocLevel(fLevelIgnore[fLevel]); Result := PL.Ignore; end; procedure TLangPreprocessor.SwitchLevelIgnoreValue(const lineno : integer); var PL : TPreprocLevel; begin if (fLevel < 0) or (fLevel >= fLevelIgnore.Count) then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineno); PL := TPreprocLevel(fLevelIgnore[fLevel]); if PL.Taken then PL.Ignore := True else PL.Ignore := not PL.Ignore; if not PL.Ignore then PL.Taken := True; end; procedure TLangPreprocessor.AddOneOrMoreLines(OutStrings : TStrings; const S, name : string; var lineNo : integer); var SL : TStringList; lineCount : integer; begin if Pos(#10, S) > 0 then begin SL := TStringList.Create; try SL.Text := S; lineCount := SL.Count; if AddPoundLineToMultiLineMacros then begin dec(lineCount); if Copy(S, Length(S), 1) <> #10 then dec(lineCount); end; OutStrings.Add(Format('#pragma macro %d', [lineCount])); OutStrings.AddStrings(SL); // at the end of each multi-line macro expansion output a #line directive OutStrings.Add(Format('#line %d "%s"', [lineNo, name])); finally SL.Free; end; end else OutStrings.Add(S); end; function TLangPreprocessor.ReplaceTokens(const tokenstring: string; lineNo : integer; bArgs : boolean): string; var Lex : TGenLexer; map : TMapList; procedure AddToResult; var i{, len} : integer; charTok, ident : string; begin if Lex.Id = piIdent then begin if bArgs then begin i := map.IndexOf(Lex.Token); if i <> -1 then begin Result := Result + map.MapValue[i]; end else Result := Result + Lex.Token; end else begin // pass lex to ProcessIdentifier ident := Lex.Token; Result := Result + ProcessIdentifier(ident, Lex, lineNo); end; end { else if (Lex.Id = piSymbol) and (Lex.Token = '#') then begin len := Length(Result); if Pos('#', Result) = len then begin // the previous token was '#' and current token is '#' System.Delete(Result, len, 1); end else Result := Result + Lex.Token; end } else if Lex.Id = piChar then begin charTok := Lex.Token; charTok := Replace(charTok, '''', ''); if Length(charTok) > 1 then raise EPreprocessorException.Create(sInvalidCharConstant, lineNo); if Length(charTok) = 1 then Result := Result + IntToStr(Ord(charTok[1])); // if the length is not > 1 or = 1 then it must be = 0, // in which case there is no need to add anything to the result end else Result := Result + Lex.Token; end; begin Result := ''; if bArgs then map := MacroFuncArgs else map := MacroDefs; Lex := AcquireLexer(lineNo); try Lex.SetStartData(@tokenstring[1], Length(tokenstring)); while not Lex.AtEnd do begin AddToResult; Lex.Next; end; if Lex.Id <> piUnknown then AddToResult; finally ReleaseLexer; end; end; const WhiteSpaceIds = [piSpace, piComment, piInnerLineEnd, piLineEnd]; procedure SkipWhitespace(Lex : TGenLexer; var linesSkipped : integer); begin while (Lex.Id in WhiteSpaceIds) and not Lex.AtEnd do begin if Lex.Id = piLineEnd then inc(linesSkipped); Lex.Next; end; end; function TLangPreprocessor.ProcessIdentifier(const ident : string; Lex : TGenLexer; var lineNo : integer) : string; var i, linesSkipped : integer; macroVal, dirText, prevToken, tmp, tok : string; nestLevel : integer; bDone : boolean; begin Result := ''; // is token in defmap? if so replace it (smartly) // token may be a function which takes parameters // so if it is then we need to grab more tokens from ( to ) tok := ident; i := MacroDefs.IndexOf(tok); if i <> -1 then begin macroVal := MacroDefs.MapValue[i]; if Pos('#', macroVal) = 1 then begin linesSkipped := 0; // function macro - complicated // format of macroVal == #arg1,arg2,...,argn#formula // is next non-whitespace token '('? Lex.Next; // skip whitespace prior to '(' if any exists SkipWhitespace(Lex, linesSkipped); if (Lex.Id = piSymbol) and (Lex.Token = '(') then begin // move past the '(' Lex.Next; MacroFuncArgs.Clear; // start with an empty arg map Delete(macroVal, 1, 1); // remove starting '#' i := Pos('#', macroVal); dirText := Copy(macroVal, 1, i-1)+ ','; // arg1,arg2,...,argn, macroVal := Copy(macroVal, i+1, MaxInt); if (dirText = ',') and Lex.AtEnd then begin i := 1; dirText := ''; end; while not Lex.AtEnd do begin // skip whitespace prior to each arg instance SkipWhitespace(Lex, linesSkipped); prevToken := ''; // now collect tokens until either ',' or ')' or whitespace nestLevel := 0; while not ({((nestLevel <= 0) and (Lex.Id in WhiteSpaceIds)) or} ((Lex.Id = piSymbol) and (((nestLevel <= 0) and (Lex.Token = ',')) or ((nestLevel <= 0) and (Lex.Token = ')'))))) do begin prevToken := prevToken + Lex.Token; if Lex.Token = '(' then inc(nestLevel) else if Lex.Token = ')' then dec(nestLevel); Lex.Next; if Lex.AtEnd then break; end; prevToken := TrimRight(prevToken); // trim any whitespace // now match instance to arg // each identifier in the instance maps to // an argument in the defined macro function i := Pos(',', dirText); if i = 0 then Break; if ((i > 1) and (prevToken = '')) or ((i = 1) and (prevToken <> '')) then Break; if i > 1 then begin tmp := Copy(dirText, 1, i-1); if tmp = '...' then begin tmp := '__VA_ARGS__'; // now collect the rest of the tokens all the way up to the ')' while not (((Lex.Id = piSymbol) and (((nestLevel <= 0) and (Lex.Token = ')'))))) do begin // 2010-01-03 JCH - changed code to replace line endings with space. if (Lex.Token = #13#10) or (Lex.Token = #10#13) or (Lex.Token = #10) or (Lex.Token = #13) then prevToken := prevToken + ' ' else prevToken := prevToken + Lex.Token; if Lex.Token = '(' then inc(nestLevel) else if Lex.Token = ')' then dec(nestLevel); Lex.Next; if Lex.AtEnd then break; end; prevToken := TrimRight(prevToken); // trim any whitespace end; MacroFuncArgs.AddEntry(tmp, prevToken); end; Delete(dirText, 1, i); // skip whitespace following each arg instance SkipWhitespace(Lex, linesSkipped); if (Lex.Id = piSymbol) and (Lex.Token = ')') then Break; // stop looping Lex.Next; end; if (i = 0) or (dirText <> '') then raise EPreprocessorException.Create(Format(sMacroMismatch, [macroVal]), lineNo); // we have eaten '(' through ')' (possibly to end of line) bDone := False; Result := macroVal; while not bDone do begin tmp := Result; Result := ReplaceTokens(tmp, lineNo, True); Result := ReplaceTokens(Result, lineNo, False); Result := Replace(Result, '##', ''); bDone := tmp = Result; end; end else raise EPreprocessorException.Create(Format(sMacroMismatch, [macroVal]), lineNo); inc(lineNo, linesSkipped); end else begin // simple macro substitution // Result := ReplaceTokens(macroVal, lineNo, False); bDone := False; Result := macroVal; while not bDone do begin tmp := Result; Result := ReplaceTokens(Result, lineNo, False); Result := Replace(Result, '##', ''); bDone := tmp = Result; end; end; Result := EvaluateIdentifier(Result); end else Result := tok; end; function TrimTrailingSpaces(const S: string) : string; var I: Integer; begin I := Length(S); while (I > 0) and (S[I] = ' ') do Dec(I); Result := Copy(S, 1, I); end; function TLangPreprocessor.ProcessMacroDefinition(const fname : string; bUndefine : boolean; Lex : TGenLexer; var lineNo : integer) : integer; var macro, dirText, oldDef, macroVal, prevToken : string; bEndOfDefine, bArgMode : boolean; i, prevId : integer; procedure HandleDefinition; begin macroVal := ''; bEndOfDefine := (Lex.Id = piLineEnd) or Lex.AtEnd; while not bEndOfDefine do begin prevId := Lex.Id; prevToken := Lex.Token; Lex.Next; if bArgMode then begin if prevId = piIdent then begin dirText := dirText + prevToken + ','; // add argument end else if (prevId = piSymbol) and (prevToken = '...') then begin dirText := dirText + prevToken + ','; // add argument end else if (prevId = piSymbol) and (prevToken = ')') then begin Delete(dirText, Length(dirText), 1); // remove last character dirText := dirText + '#'; // end arguments bArgMode := False; end; end else begin if prevId <> piComment then begin if (prevId = piSymbol) and (prevToken = '\') and (Lex.Id = piLineEnd) then begin inc(lineNo); inc(Result); continue; end else macroVal := macroVal + prevToken; end; end; bEndOfDefine := (Lex.Id = piLineEnd) or Lex.AtEnd; end; end; begin Result := 0; // add/remove definition to/from defmap // line should have a space token (1) and then an identifier // token followed by an optional parameter list ( ... ) // followed by an optional value (everything left on the line // to EOL -- or multiple lines if line ends with '\') Lex.Next; // token ID should be piSpace if Lex.Id <> piSpace then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineNo); Lex.Next; // token ID should be piIdent if Lex.Id <> piIdent then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineNo); macro := Lex.Token; // the macro name if bUndefine then begin // no more info needed. Remove macro i := MacroDefs.IndexOf(macro); if i <> -1 then MacroDefs.Delete(i); end else begin // is the next token whitespace? Lex.Next; if Lex.Id in [piSpace, piLineEnd] then begin // collect to end of #define (skipping comments) bArgMode := False; dirText := ''; HandleDefinition; end else if (Lex.Id = piSymbol) and (Lex.Token = '(') then begin bArgMode := True; Lex.Next; dirText := '#'; // flag that this is a function macro HandleDefinition; end; dirText := Trim(dirText) + TrimTrailingSpaces(TrimLeft(macroVal)); // check for macro definition i := MacroDefs.IndexOf(macro); if i <> -1 then begin oldDef := MacroDefs.MapValue[i]; if dirText <> oldDef then fWarnings.Add(IntToStr(lineNo) + '=' + fname + '|Redefinition of ''' + macro + ''' is not identical'); // now remove the previous declaration MacroDefs.Delete(i); end; MacroDefs.AddEntry(macro, dirText); end; end; function TLangPreprocessor.DoProcessStream(name : string; lineNo : integer; Stream : TMemoryStream; OutStrings : TStrings) : string; var Lex: TGenLexer; S, dir, dirText, tmpname, usePath, macro, tmp : string; X : TMemoryStream; i, j, cnt, origLevel, qPos, oldLineNo : integer; bFileFound, bDefined, bProcess : boolean; origName, ident : string; begin DoPreprocessorStatusChange(sIncludePath + ' = ' + IncludeDirs.DelimitedText); Result := ''; origName := name; S := ''; origLevel := fLevel; // at the start of each call to this function output a #line directive bProcess := not GetLevelIgnoreValue(lineNo); if bProcess and (lineNo > 0) then OutStrings.Add('#line 0 "' + name + '"'); // OutStrings.Add('#line ' + IntToStr(lineNo) + ' "' + name + '"'); if lineNo <= 0 then lineNo := 1; Lex := GenLexerType.CreateLexer; try Lex.SetStartData(Stream.Memory, Integer(Stream.Size)); while not Lex.AtEnd do begin case Lex.Id of piSpace : begin S := S + ' '; // all space == single space end; piLineEnd, piInnerLineEnd : begin // output S and clear it if bProcess then AddOneOrMoreLines(OutStrings, S, name, lineNo) else OutStrings.Add(''); S := ''; inc(lineNo); end; piComment : begin // strip all comments end; piDirective : begin // if we have some non-blank text collected then output it before // we process the directive if Trim(S) <> '' then begin // output S and clear it if bProcess then AddOneOrMoreLines(OutStrings, S, name, lineNo) else OutStrings.Add(''); S := ''; end; // some sort of preprocessor directive. dir := AnsiLowerCase(Lex.Token); dirText := ''; if dir = '#download' then begin // collect to end of line Lex.Next; while (Lex.Id <> piLineEnd) and not Lex.AtEnd do begin dirText := dirText + Lex.Token; Lex.Next; end; if bProcess then begin S := dir + dirText; dirText := Trim(dirText); // get filename qPos := Pos('"', dirText); if qPos > 0 then begin System.Delete(dirText, 1, qPos); qPos := Pos('"', dirText); if qPos > 0 then begin tmpName := Copy(dirText, 1, qPos-1); DoPreprocessorStatusChange(sProcessingDownload + ': ' + tmpName); usePath := ''; // first try to find the file without any include path DoPreprocessorStatusChange(sSearchingForFile + ': ' + usePath+tmpName); bFileFound := FileExists(tmpName); if not bFileFound then begin for i := 0 to IncludeDirs.Count - 1 do begin usePath := GetPreprocPath(origName, IncludeDirs[i]); DoPreprocessorStatusChange(sSearchingForFile + ': ' + usePath+tmpName); bFileFound := FileExists(usePath+tmpName); if bFileFound then Break; end; end; if bFileFound then begin DoPreprocessorStatusChange(sFoundFile + ': ' + usePath+tmpName); // add this filename to the result Result := Result + usePath+tmpName + #13#10; end else raise EPreprocessorException.Create(Format(sDownloadNotFound, [tmpName]), lineNo); // // output a blank line to replace directive // OutStrings.Add(''); OutStrings.Add(S); // leave the #download in for the next stage to process S := ''; end else raise EPreprocessorException.Create(sDownloadMissingQuotes, lineNo); end else raise EPreprocessorException.Create(sDownloadMissingQuotes, lineNo); end; end else if dir = '#import' then begin // collect to end of line Lex.Next; while (Lex.Id <> piLineEnd) and not Lex.AtEnd do begin dirText := dirText + Lex.Token; Lex.Next; end; if bProcess then begin dirText := Trim(dirText); // get filename qPos := Pos('"', dirText); if qPos > 0 then begin System.Delete(dirText, 1, qPos); qPos := Pos('"', dirText); if qPos > 0 then begin tmpName := Copy(dirText, 1, qPos-1); DoPreprocessorStatusChange(sProcessingImport + ': ' + tmpName); System.Delete(dirText, 1, qPos); usePath := ''; // first try to find the file without any include path DoPreprocessorStatusChange(sSearchingForFile + ': ' + usePath+tmpName); bFileFound := FileExists(tmpName); if not bFileFound then begin for i := 0 to IncludeDirs.Count - 1 do begin usePath := GetPreprocPath(origName, IncludeDirs[i]); DoPreprocessorStatusChange(sSearchingForFile + ': ' + usePath+tmpName); bFileFound := FileExists(usePath+tmpName); if bFileFound then Break; end; end; if bFileFound then begin DoPreprocessorStatusChange(sFoundFile + ': ' + usePath+tmpName); dirtext := Trim(dirText); // the optional parameter is only up to the first space or '/' i := Pos(' ', dirText); j := Pos('/', dirText); i := Min(i, j); if i > 0 then System.Delete(dirText, i, MaxInt); // delete the rest of the line // import the file if LowerCase(ExtractFileExt(usepath+tmpName)) = '.ric' then begin S := ImportRIC(usePath+tmpName, dirText); // AddOneOrMoreLines(OutStrings, S, name, lineNo); // S := ''; end else S := ImportFile(usePath+tmpName, dirText); // raise EPreprocessorException.Create(sImportRICInvalid, lineNo); end else raise EPreprocessorException.Create(Format(sImportRICNotFound, [tmpName]), lineNo); end else raise EPreprocessorException.Create(sImportRICMissingQuotes, lineNo); end else raise EPreprocessorException.Create(sImportRICMissingQuotes, lineNo); end else OutStrings.Add(''); end else if dir = '#include' then begin // collect to end of line Lex.Next; while (Lex.Id <> piLineEnd) and not Lex.AtEnd do begin dirText := dirText + Lex.Token; Lex.Next; end; if bProcess then begin dirText := Trim(dirText); // get filename qPos := Pos('"', dirText); if qPos > 0 then begin System.Delete(dirText, 1, qPos); qPos := Pos('"', dirText); if qPos > 0 then begin tmpName := Copy(dirText, 1, qPos-1); DoPreprocessorStatusChange(sProcessingInclude + ': ' + tmpName); if fIncludeFilesToSkip.IndexOf(tmpName) = -1 then begin X := TMemoryStream.Create; try usePath := ''; // first try to find the file without any include path DoPreprocessorStatusChange(sSearchingForFile + ': ' + usePath+tmpName); bFileFound := FileExists(tmpName); if not bFileFound then begin for i := 0 to IncludeDirs.Count - 1 do begin usePath := GetPreprocPath(origName, IncludeDirs[i]); DoPreprocessorStatusChange(sSearchingForFile + ': ' + usePath+tmpName); bFileFound := FileExists(usePath+tmpName); if bFileFound then Break; end; end; if bFileFound then begin DoPreprocessorStatusChange(sFoundFile + ': ' + usePath+tmpName); // load into stream X.LoadFromFile(usePath+tmpName); // call function recursively DoProcessStream(usePath+tmpName, 1, X, OutStrings); end else raise EPreprocessorException.Create(Format(sIncludeNotFound, [tmpName]), lineNo); finally X.Free; end; // at the end of each #include output a #line directive OutStrings.Add('#line ' + IntToStr(lineNo) + ' "' + name + '"'); end else // output a blank line to replace directive OutStrings.Add(''); end else raise EPreprocessorException.Create(sIncludeMissingQuotes, lineNo); end else raise EPreprocessorException.Create(sIncludeMissingQuotes, lineNo); end; end else if dir = '#reset' then begin lineNo := 0; name := origName; OutStrings.Add('#line ' + IntToStr(lineNo) + ' "' + name + '"'); end else if dir = '#error' then begin // collect to end of line Lex.Next; while (Lex.Id <> piLineEnd) and not Lex.AtEnd do begin dirText := dirText + Lex.Token; Lex.Next; end; if bProcess then begin dirText := Replace(Trim(dirText), '"', ''); raise EPreprocessorException.Create(dirText, lineNo); end; // output a blank line to replace directive OutStrings.Add(''); end else if (dir = '#define') or (dir = '#undef') then begin cnt := 1; // number of lines in #define if bProcess then begin cnt := cnt + ProcessMacroDefinition(name, dir = '#undef', Lex, lineNo); end; // output blank line(s) to replace #define for i := 0 to cnt - 1 do OutStrings.Add(''); end else if (dir = '#if') or (dir = '#elif') then begin // increment level Lex.Next; // token ID should be piSpace if Lex.Id <> piSpace then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineNo); dirText := ''; while (Lex.Id <> piLineEnd) and not Lex.AtEnd do begin dirText := dirText + Lex.Token; Lex.Next; end; // replace defined(xxx) or defined IDENT with a 0 or 1 dirText := ProcessDefinedFunction(dirText); // replace defined macros in expression dirText := ReplaceTokens(dirText, lineNo, False); if dir = '#if' then begin // reset bProcess to reflect the containing level's value bProcess := not GetLevelIgnoreValue(lineNo); // evaluate expression // if we are already ignoring code because of a containing // if/elif/ifdef/ifndef then it doesn't matter what the // expression evaluates to bDefined := EvaluateExpression(dirText, lineNo) and bProcess; if bDefined then fLevelIgnore.Add(TProcessLevel.Create) else fLevelIgnore.Add(TIgnoreLevel.Create); // continue to ignore inc(fLevel); bProcess := not GetLevelIgnoreValue(lineNo); end else begin dec(fLevel); // reset bProcess to reflect the containing level's value bProcess := not GetLevelIgnoreValue(lineNo); // evaluate expression // if we are already ignoring code because of a containing // if/elif/ifdef/ifndef then it doesn't matter what the // expression evaluates to bDefined := EvaluateExpression(dirText, lineNo) and bProcess; // restore current nesting level inc(fLevel); // #elif does not increase the level // have we already been processing code at this level? bProcess := not GetLevelIgnoreValue(lineNo); if bProcess or (not bProcess and bDefined) then begin // if we are already processing then always // turn off processing // if we are not already processing then turn ON // processing if bDefined is true SwitchLevelIgnoreValue(lineNo); bProcess := not GetLevelIgnoreValue(lineNo); end; end; // output a blank line to replace directive OutStrings.Add(''); end else if (dir = '#ifndef') or (dir = '#ifdef') then begin // increment level Lex.Next; // token ID should be piSpace if Lex.Id <> piSpace then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineNo); Lex.Next; // token ID should be piIdent or piNumber if not Lex.Id in [piIdent, piNumber] then raise EPreprocessorException.Create(sInvalidPreprocDirective, lineNo); if Lex.Id = piIdent then begin macro := Lex.Token; // the macro name bDefined := MacroDefs.IndexOf(macro) <> -1; end else begin // Lex.Token == number i := StrToIntDef(Lex.Token, 0); bDefined := i <> 0; end; if not bProcess then begin // if we are already ignoring code because of a containing // ifdef/ifndef then always ignore anything below this level fLevelIgnore.Add(TIgnoreLevel.Create); end else begin if (bDefined and (dir = '#ifdef')) or not (bDefined or (dir = '#ifdef')) then fLevelIgnore.Add(TProcessLevel.Create) else fLevelIgnore.Add(TIgnoreLevel.Create); end; inc(fLevel); bProcess := not GetLevelIgnoreValue(lineNo); // output a blank line to replace directive OutStrings.Add(''); end else if dir = '#endif' then begin // decrement level fLevelIgnore.Delete(fLevel); dec(fLevel); bProcess := not GetLevelIgnoreValue(lineNo); // output a blank line to replace directive OutStrings.Add(''); end else if dir = '#else' then begin // if we are already ignoring code because of a containing // if/elif/ifdef/ifndef then we just ignore the #else if not IgnoringAtLowerLevel(lineNo) then begin // switch mode at current level (must be > 0) SwitchLevelIgnoreValue(lineNo); bProcess := not GetLevelIgnoreValue(lineNo); end; // output a blank line to replace directive OutStrings.Add(''); end else if (dir = '#pragma') or (dir = '#line') then begin // collect to end of line Lex.Next; while (Lex.Id <> piLineEnd) and not Lex.AtEnd do begin dirText := dirText + Lex.Token; Lex.Next; end; if bProcess then begin dirText := dir + ' ' + Trim(dirText); OutStrings.Add(dirText); if dir = '#line' then begin // get filename qPos := Pos('"', dirText); if qPos > 0 then begin System.Delete(dirText, 1, qPos); qPos := Pos('"', dirText); if qPos > 0 then begin tmpName := Copy(dirText, 1, qPos-1); name := tmpName; end; end; end; end; end; // eat to end of line while (Lex.Id <> piLineEnd) and not Lex.AtEnd do Lex.Next; inc(lineNo); end; piZero, piUnknown : {do nothing}; piIdent : begin if bProcess then begin oldLineNo := lineNo; ident := Lex.Token; // we need to fix a problem here where our tokenizer is including // a leading "." as part of the identifier if Pos('.', ident) = 1 then begin System.Delete(ident, 1, 1); // remove the "." tmp := '.' + ProcessIdentifier(ident, Lex, lineNo); end else begin tmp := ProcessIdentifier(ident, Lex, lineNo); end; if Pos(#10, tmp) > 0 then begin if AddPoundLineToMultiLineMacros then begin // add #line to multi-line macros tmp := tmp + Format(#13#10'#line %d "%s"'#13#10, [oldLineNo-1, name]); end; // if we just processed a multi-line macro then we need to first // output S (if not empty) and then set S equal to our multi-line macro if Trim(S) <> '' then begin // output S and then set it to tmp AddOneOrMoreLines(OutStrings, S, name, lineNo); end; S := tmp; end else S := S + tmp; end; end; else if bProcess then S := S + Lex.Token; end; Lex.Next; end; // 2006-12-11 JCH - need to add the very last token if bProcess and not (Lex.Id in [piLineEnd, piInnerLineEnd]) then S := S + Lex.Token; if fLevel <> origLevel then raise EPreprocessorException.Create(sUnmatchedDirective, lineNo); if (S <> '') and bProcess then AddOneOrMoreLines(OutStrings, S, name, lineNo); finally Lex.Free; end; end; constructor TLangPreprocessor.Create(GLType : TGenLexerClass; const defIncDir : string; aLN : TLangName; MaxDepth : word); begin inherited Create; fLangName := aLN; fAddPoundLine := False; fGLC := GLType; fWarnings := TStringList.Create; IncludeDirs := TStringList.Create; IncludeDirs.Duplicates := dupIgnore; IncludeDirs.Sorted := True; IncludeDirs.Delimiter := ';'; IncludeDirs.Add(IncludeTrailingPathDelimiter(defIncDir)); MacroDefs := TMapList.Create; MacroFuncArgs := TMapList.Create; fLevelIgnore := TObjectList.Create; fIncludeFilesToSkip := TStringList.Create; with TStringList(fIncludeFilesToSkip) do begin Sorted := True; Duplicates := dupIgnore; end; fCalc := TNBCExpParser.Create(nil); fCalc.CaseSensitive := True; fCalc.StandardDefines := True; fCalc.ExtraDefines := True; fLexers := TObjectList.Create; InitializeLexers(MaxDepth); // fCalc.OnParserError := HandleCalcParserError; // fVarI := 0; // fVarJ := 0; // LoadStandardMacros; end; destructor TLangPreprocessor.Destroy; begin IncludeDirs.Clear; MacroDefs.Clear; MacroFuncArgs.Clear; FreeAndNil(IncludeDirs); FreeAndNil(MacroDefs); FreeAndNil(MacroFuncArgs); FreeAndNil(fLevelIgnore); FreeAndNil(fIncludeFilesToSkip); FreeAndNil(fCalc); FreeAndNil(fLexers); FreeAndNil(fWarnings); inherited; end; procedure TLangPreprocessor.AddIncludeDirs(aStrings: TStrings); var i : integer; begin for i := 0 to aStrings.Count - 1 do IncludeDirs.Add(IncludeTrailingPathDelimiter(aStrings[i])); end; function TLangPreprocessor.GenLexerType: TGenLexerClass; begin Result := fGLC; end; function TLangPreprocessor.EvaluateIdentifier(const ident: string): string; begin Result := ident; // try to evaluate Result fCalc.SilentExpression := Result; if not fCalc.ParserError then begin Result := NBCFloatToStr(fCalc.Value); end; end; function TLangPreprocessor.GetDefines: TMapList; begin Result := MacroDefs; end; function TLangPreprocessor.EvaluateExpression(expr: string; lineno : integer): boolean; begin // try to evaluate Result while Pos(' ', expr) > 0 do expr := Replace(expr, ' ', ''); fCalc.SilentExpression := expr; if not fCalc.ParserError then begin Result := fCalc.Value <> 0; end else raise EPreprocessorException.Create(Format(sInvalidPreprocExpression, [fCalc.ErrorMessage]), lineno); end; function TLangPreprocessor.ProcessDefinedFunction(expr: string): string; var p : integer; first, ident, last, delim : string; begin Result := Trim(expr); p := Pos('defined', Result); while p <> 0 do begin // replace defined(xxx) or defined xxx with 0 or 1 first := Copy(Result, 1, p-1); System.Delete(Result, 1, p+6); Result := Trim(Result); // remove any initial or trailing whitespace delim := ' '; if Pos('(', Result) = 1 then begin System.Delete(Result, 1, 1); delim := ')'; end; // grab the identifier p := Pos(delim, Result); if p = 0 then p := Length(Result)+1; ident := Trim(Copy(Result, 1, p-1)); System.Delete(Result, 1, p); last := Result; // is ident defined? Result := Format('%s %d %s', [first, Ord(MacroDefs.IndexOf(ident) <> -1), last]); p := Pos('defined', Result); end; end; procedure TLangPreprocessor.SkipIncludeFile(const fname: string); begin fIncludeFilesToSkip.Add(fname); end; function TLangPreprocessor.AcquireLexer(const lineNo : integer): TGenLexer; begin if fRecursionDepth < fLexers.Count then begin Result := TGenLexer(fLexers[fRecursionDepth]); inc(fRecursionDepth); end else raise EPreprocessorException.Create(Format(sMaxRecursionDepthError, [fLexers.Count]), lineNo); end; procedure TLangPreprocessor.ReleaseLexer; begin dec(fRecursionDepth); end; procedure TLangPreprocessor.InitializeLexers(const num: integer); var i : integer; begin for i := 0 to num - 1 do fLexers.Add(fGLC.CreateLexer); end; function TLangPreprocessor.ImportRIC(const fname, varname: string): string; var RC : TRICComp; begin RC := TRICComp.Create; try RC.LoadFromFile(fname); Result := RC.SaveAsDataArray(fLangName, varname); finally RC.Free; end; end; function TLangPreprocessor.ImportFile(const fname : string; varname: string): string; var tmp : string; i, cnt : integer; Data : TMemoryStream; P : PChar; begin if fLangName in [lnNBC, lnNXC] then begin if varname = '' then varname := ChangeFileExt(ExtractFileName(fname),'') else varname := Format(varname, [ChangeFileExt(ExtractFileName(fname),'')]); Data := TMemoryStream.Create; try Data.LoadFromFile(fname); Data.Position := 0; tmp := ''; P := Data.Memory; cnt := Integer(Data.Size) - 1; for i := 0 to cnt do begin tmp := tmp + Format('0x%2.2x', [Byte(P^)]); if i < cnt then tmp := tmp + ', '; inc(P); end; if fLangName = lnNXC then begin Result := 'byte ' + varname + '[] = {' + tmp + '};'; end else if fLangName = lnNBC then begin Result := 'dseg segment'#13#10 + ' ' + varname + ' byte[] ' + tmp + #13#10 + 'dseg ends'; end; finally Data.Free; end; end else Result := '// unable to import "' + ExtractFileName(fname) + '"'; end; function TLangPreprocessor.GetPreprocPath(const fname, path: string): string; begin Result := IncludeTrailingPathDelimiter(path); // if the path is relative then prepend it with the path from the file if Pos('.', Result) = 1 then Result := ExtractFilePath(fname) + Result else if Pos(PathDelim, Result) = 1 then Result := ExtractFileDrive(fname) + Result; end; procedure TLangPreprocessor.DoPreprocessorStatusChange(const Status: string); begin if Assigned(fOnPreprocessorStatusChange) then fOnPreprocessorStatusChange(Self, Status); end; { EPreprocessorException } constructor EPreprocessorException.Create(const msg: string; const lineno: integer); begin inherited Create(msg); fLineNo := lineno; end; { TMapList } type TStrObj = class(TObject) public Value : string; end; function TMapList.AddEntry(const aName, aValue: string): integer; var obj : TStrObj; begin Result := IndexOf(aName); if Result = -1 then begin obj := TStrObj.Create; Result := AddObject(aName, obj); obj.Value := aValue; end; end; procedure TMapList.Clear; var i : integer; begin for i := 0 to Count - 1 do Objects[i].Free; inherited; end; constructor TMapList.Create; begin inherited; CaseSensitive := True; ConsiderCase := True; Sorted := True; Duplicates := dupIgnore; end; procedure TMapList.Delete(Index: Integer); begin Objects[Index].Free; Objects[Index] := nil; inherited; end; function TMapList.GetMapValue(index: integer): string; begin Result := TStrObj(Objects[index]).Value; end; procedure TMapList.SetMapValue(index: integer; const Value: string); begin TStrObj(Objects[index]).Value := Value; end; procedure TMapList.SetConsiderCase(const AValue: boolean); begin if fConsiderCase=AValue then exit; fConsiderCase:=AValue; if Sorted then Sort; end; {$IFDEF FPC} function TMapList.DoCompareText(const s1, s2: string): PtrInt; begin if CaseSensitive or ConsiderCase then result := AnsiCompareStr(s1,s2) else result := AnsiCompareText(s1,s2); end; {$ENDIF} procedure TMapList.AddDefines(aValue: TStrings); var i : integer; begin for i := 0 to aValue.Count - 1 do AddEntry(aValue.Names[i], aValue.ValueFromIndex[i]); end; procedure TMapList.Define(const aName: string); begin AddEntry(aName, '1'); end; { TPreprocLevel } constructor TPreprocLevel.Create; begin Taken := False; Ignore := False; end; { TProcessLevel } constructor TProcessLevel.Create; begin inherited; Ignore := False; Taken := True; end; { TIgnoreLevel } constructor TIgnoreLevel.Create; begin inherited; Ignore := True; end; end.
unit ModCalcSyn2; interface var success : boolean; procedure S; implementation uses ModCalcLex, sysutils; type nodePtr = ^Node; node = record firstChild, sibling : nodePtr; val : string; (* nonterminal, operator or operand as text *) end; treePtr = nodePtr; procedure expr(var ePtr : treePtr); forward; procedure term(var tPtr : treePtr); forward; procedure fact(var fPtr : treePtr); forward; procedure S; var exprPtr : treePtr; begin new(exprPtr); (* S = expr EOF. *) success := TRUE; expr(exprPtr); if not success then exit; if curSy <> eofSy then begin success := FALSE; exit; end; newSy; (* sem *) write(exprPtr^.val); (* endsem *) end; procedure expr(var ePtr : treePtr); var firstChildPtr : treePtr; siblingPtr : treePtr; begin new(firstChildPtr); new(siblingPtr); (* Expr = Term { '+' Term | '-' Term } *) term(firstChildPtr); if not success then exit; while (curSy = plusSy) or (curSy = minusSy) do begin case curSy of plusSy: begin newSy; term(siblingPtr); if not success then exit; (* sem *) ePtr^.val := '+'; ePtr^.firstChild := firstChildPtr; ePtr^.sibling := siblingPtr; (* endsem *) end; minusSy: begin newSy; term(siblingPtr); if not success then exit; (* sem *) ePtr^.val := '-'; ePtr^.firstChild := firstChildPtr; ePtr^.sibling := siblingPtr; (* endsem *) end; end; (* case *) end; (* while *) end; procedure term(var tPtr : treePtr); var firstChildPtr : treePtr; siblingPtr : treePtr; begin new(firstChildPtr); new(siblingPtr); (* Term = Fact { '*' Fact | '/' Fact }. *) fact(firstChildPtr); if not success then exit; while (curSy = mulSy) or (curSy = divSy) do begin case curSy of mulSy: begin newSy; fact(siblingPtr); if not success then exit; (* sem *) tPtr^.val := '*'; tPtr^.firstChild := firstChildPtr; tPtr^.sibling := siblingPtr; (* endsem *) end; divSy: begin newSy; fact(siblingPtr); if not success then exit; (* sem *) tPtr^.val := '*'; tPtr^.firstChild := firstChildPtr; tPtr^.sibling := siblingPtr; (* endsem *) end; end; (* case *) end; (* while *) end; procedure fact(var fPtr : treePtr); begin (* Fact = number | '(' Expr ')' . *) case curSy of numberSy : begin newSy; (* sem *) fPtr^.val := intToStr(numVal); (* endsem *) end; leftParSy : begin newSy; (* skip (*) expr(fPtr); if not success then exit; if curSy <> rightParSy then begin success := FALSE; exit; end; newSy; end; else begin success := FALSE; exit; end; (* else *) end;(* case *) end; begin end.
(*------------------------------------------------------------------ BinominalCoefficientNice || Neuhold Michael 24.10.2018 Calculate the binomial coefficient (k choose n). introducing a Factorial procedure bc = n! DIV (k! *(n-k)!) ------------------------------------------------------------------*) PROGRAM BinominalCoefficient; USES Crt; PROCEDURE Factorial (n: INTEGER; VAR nf: LONGINT) // n ist call by value; nf ist call by reference VAR i : INTEGER; BEGIN nf := 1; FOR i := 2 TO n DO BEGIN nf := nf * i; END; (* FOR *) END; (* Factorial *) VAR k,n: INTEGER; kf, nf, nkf: INTEGER; (* kf .. k!, nf .. n!, nkf .. (n-k)! *) bc: INTEGER; (* binomial coefficient *) BEGIN WriteLn('Berechnung des Binominalkoeffizienten'); WriteLn('<#---------------------------------#>'); Write('n > '); ReadLn(n); Write('k > '); ReadLn(k); Factorial(n, nf); (* Procedure aufrufen Berechne: n! *) Factorial(k, kf); (* Procedure aufrufen Berechne: k! *) Factorial(n-k, nkf); (* Procedure aufrufen Berechne: (n-k)! *) bc := nf DIV (kf * nkf); (* DIV oder / *) WriteLN('BinominalCoefficient ', n, ' über ', k, ' = ', bc); END. (* BinominalCoefficient *)
unit kwPopEditorResizeTableColumnEX; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorResizeTableColumnEX.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_ResizeTableColumnEX // // Изменить размер колонки таблицы. Пример: // {code} aDelta aKeys aCol aRow editor:ResizeTableColumnEX{code} // {panel} // * aCol - номер ячейки, которую тянем // * aRow - номер строки // * aKeys - клавиша, нажатая при изменении размеров. // * aDelta - смещение колонки (положительное - вправо, отрицательное - влево). // {panel} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses nevTools, evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes, l3Units, nevGUIInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackTableColumnResize.imp.pas} TkwPopEditorResizeTableColumnEX = class(_kwEditorFromStackTableColumnResize_) {* Изменить размер колонки таблицы. Пример: [code] aDelta aKeys aCol aRow editor:ResizeTableColumnEX[code] [panel] * aCol - номер ячейки, которую тянем * aRow - номер строки * aKeys - клавиша, нажатая при изменении размеров. * aDelta - смещение колонки (положительное - вправо, отрицательное - влево). [panel] } protected // overridden protected methods function GetKeys: TShiftState; override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorResizeTableColumnEX {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses Table_Const, evConst, TextPara_Const, CommentPara_Const, Windows, evParaTools, evOp, tfwAutoregisteredDiction, tfwScriptEngine, afwFacade, Forms, l3Base ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorResizeTableColumnEX; {$Include ..\ScriptEngine\kwEditorFromStackTableColumnResize.imp.pas} // start class TkwPopEditorResizeTableColumnEX class function TkwPopEditorResizeTableColumnEX.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:ResizeTableColumnEX'; end;//TkwPopEditorResizeTableColumnEX.GetWordNameForRegister function TkwPopEditorResizeTableColumnEX.GetKeys: TShiftState; //#UC START# *4E32CA120170_4E37BEF102EE_var* var l_Value: Integer; //#UC END# *4E32CA120170_4E37BEF102EE_var* begin //#UC START# *4E32CA120170_4E37BEF102EE_impl* l_Value := ItfwScriptEngine(f_Engine).PopInt; case l_Value of 0: Result := []; 1: Result := [ssShift]; 2: Result := [ssAlt]; 3: Result := [ssCtrl]; else Assert(False, 'Другие значения не поддерживаются.') end; //#UC END# *4E32CA120170_4E37BEF102EE_impl* end;//TkwPopEditorResizeTableColumnEX.GetKeys {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackTableColumnResize.imp.pas} {$IfEnd} //not NoScripts end.
unit fb2rtf_dispatch; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, FB2_to_RTF_TLB, fb2rtf_engine,StdVcl; type TFB2RTFExport = class(TAutoObject, IFB2RTFExport) protected procedure AfterConstruction; Override; function Get_SkipDescr: WordBool; safecall; function Get_SkipImages: WordBool; safecall; procedure Set_SkipDescr(Value: WordBool); safecall; procedure Set_SkipImages(Value: WordBool); safecall; function Get_ImagesToBMP: WordBool; safecall; function Get_EncOptimise: WordBool; safecall; procedure Set_ImagesToBMP(Value: WordBool); safecall; procedure Set_EncOptimise(Value: WordBool); safecall; procedure AddXSLParameter(baseName, parameter, namespaceURI: OleVariant); safecall; procedure Convert(const Document: IDispatch; FileName: OleVariant); safecall; procedure ConvertInteractive(hWnd: Integer; filename: OleVariant; const Document: IDispatch); safecall; function Get_SkipCover: WordBool; safecall; procedure Set_SkipCover(Value: WordBool); safecall; { Protected declarations } private Converter:TRTFConverter; end; implementation uses ComServ,save_rtf_dialog,SysUtils,MSXML2_TLB,Dialogs; procedure TFB2RTFExport.AfterConstruction; Begin Converter:=TRTFConverter.Create; end; function TFB2RTFExport.Get_SkipDescr: WordBool; begin Result:=Converter.SkipDescr; end; function TFB2RTFExport.Get_SkipImages: WordBool; begin Result:=Converter.SkipImages; end; procedure TFB2RTFExport.Set_SkipDescr(Value: WordBool); begin Converter.SkipDescr:=Value; end; procedure TFB2RTFExport.Set_SkipImages(Value: WordBool); begin Converter.SkipImages:=Value; end; function TFB2RTFExport.Get_ImagesToBMP: WordBool; begin Result:=Converter.ImgCompat; end; function TFB2RTFExport.Get_EncOptimise: WordBool; begin Result:=Converter.EncCompat; end; procedure TFB2RTFExport.Set_ImagesToBMP(Value: WordBool); begin Converter.ImgCompat:=Value; end; procedure TFB2RTFExport.Set_EncOptimise(Value: WordBool); begin Converter.EncCompat:=Value; end; procedure TFB2RTFExport.AddXSLParameter(baseName, parameter, namespaceURI: OleVariant); begin Converter.Processor.addParameter(baseName, parameter, namespaceURI); end; procedure TFB2RTFExport.Convert(const Document: IDispatch; FileName: OleVariant); begin Converter.Convert(Document,FileName); end; procedure TFB2RTFExport.ConvertInteractive(hWnd: Integer; filename: OleVariant; const Document: IDispatch); Var DLG:TOpenPictureDialog; XDoc:IXMLDOMDocument2; FN:String; begin FN:=filename; if Document=Nil then Begin With TOpenDialog.Create(Nil) do try Filter:='FictionBook 2.0 documents (*.fb2)|*.fb2|All files (*.*)|*.*'; If not Execute then Exit; XDoc:=CoFreeThreadedDOMDocument40.Create; if not XDoc.load(FileName) then Raise Exception.Create('Opening fb2 file:'#10+XDoc.parseError.reason); FN:=FileName; Finally Free; end; end else XDoc:=IXMLDOMDocument2(Document); DLG:=TOpenPictureDialog.Create(Nil); Try if FN<>'' then DLG.FileName:=copy(FN,1,Length(FN)-Length(ExtractFileExt(FN)))+'.rtf'; if DLG.Execute then ExportDOM(hWnd,XDoc,DLG.FileName, DLG.DoSkipImages, DLG.DoSkipCover, DLG.DoSkipDescr, DLG.DoEncCompat, DLG.DoImgCompat); Finally DLG.Free; end; end; function TFB2RTFExport.Get_SkipCover: WordBool; begin result:=Converter.SkipCover; end; procedure TFB2RTFExport.Set_SkipCover(Value: WordBool); begin Converter.SkipCover:=Value; end; initialization TAutoObjectFactory.Create(ComServer, TFB2RTFExport, Class_FB2RTFExport, ciMultiInstance, tmApartment); end.
{ ******************************************************* } { This is the main jabber client unit } { } { } { Copyright (C) 2014 } { } { ******************************************************* } unit fmxJabberClient; interface uses Sysutils, fmx.dialogs, System.Classes, fmx.Types, FmxJabberTools, fmxJabberXml, fmxSocket, fmxSASLCrypt; type TfmxJabberClient = class(TFmxObject) // The jabber component private fSocket: TJabberSocket; // The socket core fXml: TfmxJabberXml; // the xml core fConnected: Boolean; fLogin: string; fPassword: string; fJabberServer: string; fJabberPort: Integer; FUserStatus: TUserStatus; // userstatus (online, oflfine, ...) FUserDisplayMsg: string; // user display message fJResource: String; fLogged: Boolean; fOnLogged: TOnResponseWithNoData; fOnGettingContacts: TOnResponseWithNoData; fOnUpdateContact: TOnResponseWithStrData; fOnNewContact: TOnResponseWithStrData; fOnMessageReceived: TOnMessageReceived; fOnAskToAddRosterStatus: TOnAddRequestStatus; fOnAskedToAddContact: TOnContactAskToAdd; fContactsList: TList; procedure OnReceivedDataProc(AServerResponse: string); procedure OnInitConnectionProc(AId: String; ACompression: String; AUseSASL: Boolean; AMechanism: TMechanism); procedure OnCryptedSASLProc(ACryptedSignature: String); procedure OnSuccessSASL(ASASLResponse: String); procedure OnBindInitProc; procedure OnSessionInitProc; procedure OnIQRequest(AId: string); procedure OnGettingContactsProc(AContactsList: String); procedure OnFailureProc(AError: String); procedure OnUpdateRosterProc(AName, AJID, ASubscription, AGroup: string); procedure OnAskToAddRosterStatusProc(AFrom: string; AAccepted: Boolean); procedure OnAskedForSubscriptionProc(AJID: string); procedure OnMessageReceivedProc(AFrom, AMessage: string); procedure OnPresenceCallBackProc(AFrom, ATo, ADisplayMessage: String; APresence: TUserStatus); procedure AddNewContact(AJID: string); procedure ClearContactsList; function Getcontact(AIdx: Integer): PContact; function GetContactsCount: Integer; protected public constructor Create(AOwner : TComponent);override; Destructor Destroy; override; procedure InitializeSocket; procedure DoLogon; procedure Disconnect; procedure SetPresence(Astatus: TUserStatus; AMessage: String); procedure GetcontactsList; procedure AddContact(AUsername, AJID, AGroup: string); procedure SendMessage(ATo, AMessage: string); procedure RemoveContact(AContactIdx: Integer); property Connected: Boolean read fConnected; property UserDisplayMsg: string read FUserDisplayMsg write FUserDisplayMsg; property UserStatus: TUserStatus read FUserStatus write FUserStatus; property Contacts[AIdx: Integer]: PContact read Getcontact; property ContactsCount: Integer read GetContactsCount; property Logged: Boolean read fLogged write fLogged; Published property Login: String read fLogin write fLogin; property Password: String read fPassword write fPassword; property JabberServer: String read fJabberServer write fJabberServer; property JabberPort: Integer read fJabberPort write fJabberPort; property JResource: string read fJResource write fJResource; property OnLogged: TOnResponseWithNoData read fOnLogged write fOnLogged; property OnGettingContacts: TOnResponseWithNoData read fOnGettingContacts write fOnGettingContacts; property OnNewContact: TOnResponseWithStrData read fOnNewContact write fOnNewContact; property OnContactAskToAdd: TOnContactAskToAdd read fOnAskedToAddContact write fOnAskedToAddContact; property OnAddContactStatus: TOnAddRequestStatus read fOnAskToAddRosterStatus write fOnAskToAddRosterStatus; property OnMessageReceived: TOnMessageReceived read fOnMessageReceived write fOnMessageReceived; property OnUpdatePresence: TOnResponseWithStrData read fOnUpdateContact write fOnUpdateContact; end; procedure Register; implementation { TJabberClient } { ------------------------------------------------------------------------------- Procedure: Register Arguments: None Result: None ------------------------------------------------------------------------------- } procedure Register; begin RegisterComponents('FmxJabberClient', [TfmxJabberClient]); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.Disconnect : Send disconnect request to server Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.Disconnect; begin try fSocket.SendRequest('<presence type="unavailable"/>'); fSocket.UnInitialize; except On E: Exception do Raise Exception.Create('[TfmxJabberClient.Disconnect] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.DoLogon : Send authentification request Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.DoLogon; var wLoginRequest: String; begin try wLoginRequest := fXml.CreateInitRequest(fJabberServer); fSocket.SendRequest(wLoginRequest); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.DoLogon] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.Getcontact : Get a contact data from contacts list Arguments: AIdx: integer Result: PContact ------------------------------------------------------------------------------- } function TfmxJabberClient.Getcontact(AIdx: Integer): PContact; begin Result := fContactsList[AIdx]; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.GetContactsCount : Get contacts count Arguments: None Result: integer ------------------------------------------------------------------------------- } function TfmxJabberClient.GetContactsCount: Integer; begin Result := fContactsList.count; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.GetcontactsList : Send "Get contacts " request to server Author: kelhedadi DateTime: 2014.04.22 Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.GetcontactsList; var wRequest: String; begin try wRequest := fXml.CreateGetcontactsRequest; // create xml request fSocket.SendRequest(wRequest); // send request except On E: Exception do Raise Exception.Create('[TfmxJabberClient.GetcontactsList] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.AddContact : Add a contact to list Arguments: AUsername, AJID, AGroup: string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.AddContact(AUsername, AJID, AGroup: string); var wRequest: string; wFrom: string; begin wFrom := fLogin + '@' + fJabberServer; wRequest := fXml.CreateAddContactRequest(wFrom, AUsername, AJID, AGroup); // Create add request fSocket.SendRequest(wRequest); // send request to server end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.ClearContactsList Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.ClearContactsList; var wcontact: PContact; i: Integer; begin for i := 0 to fContactsList.count - 1 do begin wcontact := fContactsList[i]; Dispose(wcontact); end; fContactsList.Clear; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.Create Arguments: None Result: None ------------------------------------------------------------------------------- } constructor TfmxJabberClient.Create(AOwner : TComponent); begin try inherited; if not(csDesigning in ComponentState) then begin fLogged := False; // initialize variables and events fContactsList := TList.Create; fSocket := TJabberSocket.Create; fSocket.OnDataReceived := OnReceivedDataProc; fXml := TfmxJabberXml.Create; fXml.OnInitConnection := OnInitConnectionProc; fXml.OnCryptedSASL := OnCryptedSASLProc; fXml.OnSuccessSASL := OnSuccessSASL; fXml.OnBindInit := OnBindInitProc; fXml.OnSessionInit := OnSessionInitProc; fXml.OnIQRequest := OnIQRequest; fXml.OnGettingContacts := OnGettingContactsProc; fXml.OnFaillure := OnFailureProc; fXml.OnUpdateRoster := OnUpdateRosterProc; fXml.OnAskToAddRosterStatus := OnAskToAddRosterStatusProc; fXml.OnAskedForSubscription := OnAskedForSubscriptionProc; fXml.OnMessageReceived := OnMessageReceivedProc; fXml.OnPresenceCallback := OnPresenceCallBackProc; fConnected := False; end; except On E: Exception do Raise Exception.Create('[TfmxJabberClient.Create] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.destroy Arguments: None Result: None ------------------------------------------------------------------------------- } destructor TfmxJabberClient.Destroy; begin try if not(csDesigning in ComponentState) then begin ClearContactsList; fContactsList.free; if assigned(fXml) then fXml.free; if assigned(fSocket) then fSocket.free; end; inherited; except On E: Exception do Raise Exception.Create('[TfmxJabberClient.destroy] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.InitializeSocket Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.InitializeSocket; begin try fSocket.Initialize(fJabberServer, fJabberPort); // initialize tcp connection with server fConnected := fSocket.Connected; except On E: Exception do Raise Exception.Create('[TJabberClient.Initialize] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnAskToAddRosterStatusProc : received when you ask to add a contact and he accepted your request Arguments: AFrom : string; AAccepted : Boolean Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnAskToAddRosterStatusProc(AFrom: string; AAccepted: Boolean); begin if AAccepted then // contact accept your request AddNewContact(AFrom); if assigned(fOnAskToAddRosterStatus) then fOnAskToAddRosterStatus(AFrom, AAccepted); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnAskedForSubscriptionProc : when a contact want to add you to his list Arguments: AJid : string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnAskedForSubscriptionProc(AJID: string); var wAccept: Boolean; begin wAccept := False; if assigned(fOnAskedToAddContact) then fOnAskedToAddContact(AJID, wAccept); // ask user for accept request if wAccept then // if user accept adding request fSocket.SendRequest (Format('<presence from="%s" to="%s" type="subscribed"/>', [fLogin + '@' + fJabberServer, AJID]) + fXml.CreateAddContactRequest (fLogin + '@' + fJabberServer, '', AJID, '')) else fSocket.SendRequest (Format('<presence from="%s" to="%s" type="unsubscribed"/>', [fLogin + '@' + fJabberServer, AJID])); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.AddNewContact Arguments: AJID : string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.AddNewContact(AJID: string); var wcontact: PContact; begin New(wcontact); // create contact record and add it to contacts list wcontact.Name := AJID; wcontact.Jid := AJID; wcontact.Astatus := usInVisible; wcontact.ADisplayMessage := ''; fContactsList.Add(wcontact); if assigned(fOnNewContact) then fOnNewContact(AJID); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnBindInitProc Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnBindInitProc; var wRequest: string; begin wRequest := fXml.CreateInitBindRequest(fJResource); fSocket.SendRequest(wRequest); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnCryptedSASLProc Arguments: ACryptedSignature: String Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnCryptedSASLProc(ACryptedSignature: String); var wDecencoded: String; wRequest: String; begin try wDecencoded := GetSASLResponse(ACryptedSignature, fLogin, fPassword, fJabberServer); // Get SASL response from server request wRequest := fXml.CreateSASLRequest(wDecencoded); // Create response XML fSocket.SendRequest(wRequest); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.OnCryptedSASLProc] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnFailureProc Arguments: AError: String Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnFailureProc(AError: String); begin Raise Exception.Create(AError); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnGettingContactsProc : Getting contacts from server Arguments: AContactsList: String Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnGettingContactsProc(AContactsList: String); var wStrlist, wItems: Tstringlist; i: Integer; wcontact: PContact; begin try ClearContactsList; wStrlist := Tstringlist.Create; try wStrlist.CommaText := AContactsList; wItems := Tstringlist.Create; try for i := 0 to wStrlist.count - 1 do begin wItems.CommaText := wStrlist[i]; New(wcontact); wcontact.Name := wItems[0]; wcontact.Jid := wItems[1]; wcontact.Subscription := CompareText(wItems[2], 'none') <> 0; wcontact.Group := wItems[3]; fContactsList.Add(wcontact); end; finally wItems.free; end; finally wStrlist.free; end; if assigned(fOnGettingContacts) then fOnGettingContacts(); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.OnGettingContactsProc] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnInitConnectionProc Arguments: AId, ACompression: String; AUseSASL : Boolean; AMechanism : TMechanism Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnInitConnectionProc(AId, ACompression: String; AUseSASL: Boolean; AMechanism: TMechanism); var wRequest: String; begin if AUseSASL then begin if AMechanism <> mecNONE then begin wRequest := fXml.CreateAuthRequest(AMechanism); fSocket.SendRequest(wRequest); end; end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnIQRequest Arguments: AId: string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnIQRequest(AId: string); var wResponse: String; begin try wResponse := fXml.CreateIQResponse(AId, fJabberServer); fSocket.SendRequest(wResponse); fLogged := True; if assigned(fOnLogged) then fOnLogged(); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.OnIQRequest] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnMessageReceivedProc Arguments: AFrom, AMessage: string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnMessageReceivedProc(AFrom, AMessage: string); begin if assigned(fOnMessageReceived) then fOnMessageReceived(AFrom, AMessage); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnPresenceCallBackProc Arguments: AFrom, ATo, ADisplayMessage: String; APresence: TUserStatus Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnPresenceCallBackProc(AFrom, ATo, ADisplayMessage : String; APresence: TUserStatus); var i: Integer; wcontact: PContact; begin // On receive a status change event if AFrom = ATo then // if the event concern the current user begin FUserStatus := APresence; FUserDisplayMsg := ADisplayMessage; // update status if assigned(fOnUpdateContact) then fOnUpdateContact('-2'); end else begin for i := 0 to fContactsList.count - 1 do // if the event is for a ocntact from the list begin wcontact := fContactsList[i]; if pos(uppercase(wcontact.Jid), uppercase(AFrom)) > 0 then begin wcontact.ADisplayMessage := ADisplayMessage; // update contacts status in the list wcontact.Astatus := APresence; if assigned(fOnUpdateContact) then fOnUpdateContact(wcontact.Jid); Break; end; end; end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnReceivedDataProc Arguments: AServerResponse: string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnReceivedDataProc(AServerResponse: string); begin try fXml.ParseServerResponse(AServerResponse); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.OnReceivedDataProc] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnSessionInitProc Arguments: None Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnSessionInitProc; var wRequest: String; begin wRequest := fXml.CreateInitSessionRequest(GetUniqueID); fSocket.SendRequest(wRequest); end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnSuccessSASL Arguments: ASASLResponse: String Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnSuccessSASL(ASASLResponse: String); var wResponse: String; begin try wResponse := Format(ASASLResponse, [fJabberServer]); fSocket.SendRequest(wResponse); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.OnSuccessSASL] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.OnUpdateRosterProc Arguments: AName, AJID, ASubscription, AGroup: string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.OnUpdateRosterProc(AName, AJID, ASubscription, AGroup: string); var i: Integer; wcontact: PContact; begin for i := 0 to fContactsList.count - 1 do begin wcontact := Getcontact(i); if CompareText(wcontact.Jid, AJID) = 0 then begin wcontact.Jid := AJID; wcontact.Name := AName; wcontact.Group := AGroup; wcontact.Subscription := CompareText(ASubscription, 'none') <> 0; Break end; end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.RemoveContact : Remove a contact Arguments: AContactIdx: integer Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.RemoveContact(AContactIdx: Integer); var wReq: string; wcontact: PContact; begin wcontact := fContactsList[AContactIdx]; wReq := fXml.CreateDeleteRosterRequest(fLogin + '@' + fJabberServer, wcontact.Jid); fSocket.SendRequest(wReq); // send request to server Dispose(wcontact); fContactsList.Delete(AContactIdx); // delete him from list end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.SendMessage Arguments: ATo, AMessage: string Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.SendMessage(ATo, AMessage: string); var wRequest: string; wFrom: string; begin try wFrom := fLogin + '@' + fJabberServer; wRequest := fXml.CreateSendMessageRequest(wFrom, ATo, 'chat', AMessage); fSocket.SendRequest(wRequest); except On E: Exception do Raise Exception.Create('[TfmxJabberClient.SendMessage] : ' + E.message); end; end; { ------------------------------------------------------------------------------- Procedure: TfmxJabberClient.SetPresence Arguments: Astatus : TUserStatus; AMessage : String Result: None ------------------------------------------------------------------------------- } procedure TfmxJabberClient.SetPresence(Astatus: TUserStatus; AMessage: String); var wRequest: string; begin try wRequest := fXml.CreatePresenceRequest(Astatus, AMessage); fSocket.SendRequest(wRequest); FUserStatus := Astatus; except On E: Exception do Raise Exception.Create('[TfmxJabberClient.SetPresence] : ' + E.message); end; end; initialization RegisterFMXClasses([TfmxJabberClient]); end.
unit MDIChilds.Reg; interface uses SysUtils, Classes, Contnrs, Forms, Generics.Collections, IniFiles, {Processors Forms} MDIChilds.CustomDialog; type TFormsRegistrator = class private type TFormInfo = record FormClass: TFormClass; Caption: string; ImageIndex: Integer; GroupName: string; ToolBarButton: Boolean; DPK: TDataProcessorKind; CMD: string; end; private FForms: TList<TFormInfo>; FSettings: TIniFile; function GetCount: Integer; function GetForm(Index: Integer): TFormInfo; protected function IndexOf(AFormClass: TFormClass): Integer; public procedure RegisterForm(AFormClass: TFormClass; ACaption: string; AGroup: string; ToolBarButton: Boolean; DPK: TDataProcessorKind; CMD: string; AGroupIndex: Integer = 0); procedure UnRegisterForm(AFormClass: TFormClass); constructor Create; destructor Destroy; override; property Count: Integer read GetCount; property Forms[Index: Integer]: TFormInfo read GetForm; default; end; function FormsRegistrator: TFormsRegistrator; implementation { TFormsResgistrator } var aFormsRegistrator: TFormsRegistrator; constructor TFormsRegistrator.Create; begin inherited Create; FForms := TList<TFormInfo>.Create; FSettings := TIniFile.Create(ExtractFilePath(Application.ExeName)+'config_view.ini'); end; destructor TFormsRegistrator.Destroy; begin FSettings.Free; FForms.Free; inherited; end; function TFormsRegistrator.GetCount: Integer; begin Result := FForms.Count; end; function TFormsRegistrator.GetForm(Index: Integer): TFormInfo; begin Result := FForms[Index]; end; function TFormsRegistrator.IndexOf(AFormClass: TFormClass): Integer; var I: Integer; begin Result := -1; for I := 0 to FForms.Count - 1 do if FForms[I].FormClass = AFormClass then begin Result := I; Break; end; end; procedure TFormsRegistrator.RegisterForm(AFormClass: TFormClass; ACaption: string; AGroup: string; ToolBarButton: Boolean; DPK: TDataProcessorKind; CMD: string; AGroupIndex: Integer); var Info: TFormInfo; begin if FSettings.ReadBool('register',ACaption,true) then if Self.IndexOf(AFormClass) = -1 then begin Info.FormClass := AFormClass; Info.Caption := ACaption; Info.ImageIndex := AGroupIndex; Info.GroupName := AGroup; Info.ToolBarButton := ToolBarButton; Info.DPK := DPK; Info.CMD := CMD; FForms.Add(Info); FSettings.WriteBool('register',ACaption,true); end; end; procedure TFormsRegistrator.UnRegisterForm(AFormClass: TFormClass); var I: Integer; begin I := IndexOf(AFormClass); if I <> -1 then FForms.Delete(I); end; function FormsRegistrator: TFormsRegistrator; begin Result := aFormsRegistrator; end; initialization aFormsRegistrator := TFormsRegistrator.Create; finalization FreeAndNil(aFormsRegistrator); end.
program TESTNF ( OUTPUT ) ; var S1 , S2 , S3 : STRING ( 100 ) ; begin (* HAUPTPROGRAMM *) S1 := 'Bernd Oppolzer' ; S2 := LEFT ( S1 , 5 ) ; S3 := RIGHT ( S1 , 8 ) ; WRITELN ( '<' , S1 , '>' ) ; WRITELN ( '<' , S2 , '>' ) ; WRITELN ( '<' , S3 , '>' ) ; S1 := RIGHT ( S1 , 50 ) ; S2 := LEFT ( S2 , 20 ) ; S3 := LEFT ( S3 , 4 ) ; WRITELN ( '<' , S1 , '>' ) ; WRITELN ( '<' , S2 , '>' ) ; WRITELN ( '<' , S3 , '>' ) ; WRITELN ( 'index = ' , INDEX ( S1 , 'e' ) ) ; WRITELN ( 'lastindex = ' , LASTINDEX ( S1 , 'e' ) ) ; WRITELN ( 'index = ' , INDEX ( S1 , 'er' ) ) ; WRITELN ( 'lastindex = ' , LASTINDEX ( S1 , 'er' ) ) ; WRITELN ( 'index = ' , INDEX ( S1 , 'Oppo' ) ) ; WRITELN ( 'lastindex = ' , LASTINDEX ( S1 , 'Oppo' ) ) ; WRITELN ( 'index = ' , INDEX ( S1 , ' Bernd' ) ) ; WRITELN ( 'lastindex = ' , LASTINDEX ( S1 , ' Bernd' ) ) ; WRITELN ( 'index = ' , INDEX ( S2 , 'Bernd' ) ) ; WRITELN ( 'lastindex = ' , LASTINDEX ( S2 , 'Bernd' ) ) ; WRITELN ( 'index = ' , INDEX ( S1 , ' ' ) ) ; WRITELN ( 'lastindex = ' , LASTINDEX ( S1 , ' ' ) ) ; end (* HAUPTPROGRAMM *) .
unit constants; interface const nHELLO_CODE:integer=100; sHELLO_MSG:string='Welcome to victims kingdom!'; nNO_COMMAND_CODE:integer=105; sNO_COMMAND_MSG:string='Type a command followed by space or type help.'; nINVALID_COMMAND_CODE:integer=110; sINVALID_COMMAND_MSG:string='Command not recognized. Type voculbary to know valid commands.'; nNO_PARAM_CODE:integer=115; sNO_PARAM_MSG='Command requires parameters.'; nREQ_TWO_PARAM_CODE:integer=120; sREQ_TWO_PARAM_MSG='Command requires two parameters: CMD "param1" "param2".'; nCOMMAND_ENDED_CODE:integer=125; nWAIT_CODE:integer=130; sWAIT_MSG:string='wait while command completes'; nINVALID_PARAM_CODE:integer=135; sINVALID_PARAM_MSG:string='Passed parameter is invalid'; nINTERNAL_ERROR_CODE:integer=140; implementation end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIProxiedInterface; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpCryptoLibTypes; type IAsn1Object = interface; IAsn1Convertible = interface(IInterface) ['{13104D9E-9DF1-4CCE-B48C-1ACC2AC362B1}'] function ToAsn1Object(): IAsn1Object; end; IAsn1Encodable = interface(IAsn1Convertible) ['{1B2D1F84-4E8F-442E-86F8-B75C9942F1AB}'] function GetEncoded(): TCryptoLibByteArray; overload; function GetEncoded(const encoding: String): TCryptoLibByteArray; overload; function GetDerEncoded(): TCryptoLibByteArray; function Equals(const obj: IAsn1Convertible): Boolean; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} end; IAsn1Object = interface(IAsn1Encodable) ['{83A52A0F-570B-43BB-9B98-8E5351FDA996}'] function Asn1Equals(const asn1Object: IAsn1Object): Boolean; function Asn1GetHashCode(): Int32; procedure Encode(const derOut: TStream); function CallAsn1Equals(const obj: IAsn1Object): Boolean; function CallAsn1GetHashCode(): Int32; end; implementation end.
unit AddOrderToRouteUnit; interface uses SysUtils, BaseExampleUnit, RouteParametersUnit, AddressUnit; type TAddOrderToRoute = class(TBaseExample) public procedure Execute(RouteId: String; RouteParameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray); end; implementation uses AddOrderToRouteRequestUnit; procedure TAddOrderToRoute.Execute(RouteId: String; RouteParameters: TRouteParameters; OrderedAddresses: TOrderedAddressArray); var ErrorString: String; begin Route4MeManager.Route.AddOrder(RouteId, RouteParameters, OrderedAddresses, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then WriteLn('AddOrderToRoute executed successfully') else WriteLn(Format('AddOrderToRoute error: "%s"', [ErrorString])); end; end.
unit Model.CadastroAnexos; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema; type TCadastroAnexos = class private FDataAnexo: TDateTime; FID: Integer; FNomeArquivo: String; FDescricaoAnexo: String; FIdAnexo: Integer; FAcao: TAcao; FConexao: TConexao; FQuery: TFDQuery; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public property Id: Integer read FID write FID; property IdAnexo: Integer read FIdAnexo write FIdAnexo; property DescricaoAnexo: String read FDescricaoAnexo write FDescricaoAnexo; property NomeArquivo: String read FNomeArquivo write FNomeArquivo; property DataAnexo: TDateTime read FDataAnexo write FDataAnexo; property Query: TFDQuery read FQuery write FQuery; constructor Create(); function GetID(iID: Integer): Integer; function Localizar(aParam: array of variant): Boolean; function Gravar(): Boolean; procedure SetupClass(FDQuery: TFDquery); procedure ClearSetup; end; const TABLENAME = 'cadastro_anexos'; implementation { TCadastroAnexos } procedure TCadastroAnexos.ClearSetup; begin FDataAnexo := StrToDate('31/12/1899'); FID := 0; FNomeArquivo := ''; FDescricaoAnexo := ''; FIdAnexo := 0; end; constructor TCadastroAnexos.Create; begin FConexao := TConexao.Create; end; function TCadastroAnexos.Delete: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; if Self.IdAnexo = -1 then begin sSQL := 'delete drom ' + TABLENAME + ' ' + 'where id_cadastro = :pid_cadastro;'; FDQuery.ExecSQL(sSQL,[Self.ID]); end else begin sSQL := 'delete from ' + TABLENAME + ' ' + 'where id_cadastro = :pid_cadastro and id_anexo = :id_anexo;'; FDQuery.ExecSQL(sSQL,[Self.ID, Self.IdAnexo]); end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroAnexos.GetID(iID: Integer): Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(id_anexo),0) + 1 from ' + TABLENAME + ' where id_cadastro = ' + iID.toString + ';'); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroAnexos.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Self.Insert(); tacAlterar: Result := Self.Update(); tacExcluir: Result := Self.Delete(); end; end; function TCadastroAnexos.Insert: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); Self.IDAnexo := GetID(Self.ID); sSQL := 'insert into ' + TABLENAME + '(' + 'id_cadastro, id_anexo, des_anexo, nom_arquivo, dat_anexo) ' + 'values (' + ':id_cadastro, :id_anexo, :des_anexo, :nom_arquivo, :dat_anexo);'; FDQuery.ExecSQL(sSQL, [Self.ID ,Self.IdAnexo, Self.DescricaoAnexo, Self.NomeArquivo, Self.DataAnexo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroAnexos.Localizar(aParam: array of variant): Boolean; begin Result := False; FQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FQuery.SQL.Clear; FQuery.SQL.Add('select id_cadastro, id_anexo, des_anexo, nom_arquivo, dat_anexo from ' + TABLENAME); if aParam[0] = 'ID' then begin FQuery.SQL.Add('whew id_cadastro = :id_cadastro'); FQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FQuery.SQL.Add('where id_cadastro = :id_cadastro and id_anexo = :id_anexo'); FQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; FQuery.ParamByName('id_anexo').AsInteger := aParam[2]; end; if aParam[0] = 'DATA' then begin FQuery.SQL.Add('where dat_anexo = :dat_anexo'); FQuery.ParamByName('dat_anexo').AsDateTime := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FQuery.SQL.Add('where des_anexo LIKE :des_anexo'); FQuery.ParamByName('des_anexo').asString := aParam[1]; end; if aParam[0] = 'ARQUIVO' then begin FQuery.SQL.Add('where nom_arquivo LIKE :nom_arquivo'); FQuery.ParamByName('nom_arquivo').asString := aParam[1]; FQuery.SQL.Add('select id_cadastro, cod_tipo_cadastro, id_anexo, des_anexo, nom_arquivo, dat_anexo from ' + TABLENAME); end; if aParam[0] = 'ID' then begin FQuery.SQL.Add('whew id_cadastro = :id_cadastro and cod_tipo_cadastro = :cod_tipo_cadastro'); FQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; FQuery.ParamByName('cod_tipo_cadastro').AsInteger := aParam[2]; end; if aParam[0] = 'SEQUENCIA' then begin FQuery.SQL.Add('where id_cadastro = :id_cadastro and cod_tipo_cadastro = :cod_tipo_cadastro and id_anexo = :id_anexo'); FQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; FQuery.ParamByName('cod_tipo_cadastro').AsInteger := aParam[2]; FQuery.ParamByName('id_anexo').AsInteger := aParam[3]; end; if aParam[0] = 'NUMERO' then begin FQuery.SQL.Add('where num_consulta like :num_consulta'); FQuery.ParamByName('num_consulta').AsString := aParam[1]; end; if aParam[0] = 'DATA' then begin FQuery.SQL.Add('where dat_consulta = :dat_consulta'); FQuery.ParamByName('dat_consulta').AsDateTime := aParam[1]; end; if aParam[0] = 'VALIDADE' then begin FQuery.SQL.Add('where dat_validade = :dat_validade'); FQuery.ParamByName('dat_validade').AsDateTime := 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; FQuery.Open(); if FQuery.IsEmpty then begin Exit; end; Result := True; end; procedure TCadastroAnexos.SetupClass(FDQuery: TFDQuery); begin FDataAnexo := FDQuery.FieldByName('dat_anexo').asDateTime; FID := FDQuery.FieldByName('id_cadastro').AsInteger; FNomeArquivo := FDQuery.FieldByName('nom_arquivo').AsString; FDescricaoAnexo := FDQuery.FieldByName('des_anexo').asString; FIdAnexo := FDQuery.FieldByName('id_anexo').asInteger; end; function TCadastroAnexos.Update: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); Self.IdAnexo := GetID(Self.ID); sSQL := 'update ' + TABLENAME + ' set ' + 'des_anexo = :des_anexo, nom_arquivo = :nom_arquivo, dat_anexo = :dat_anexo' + 'where ' + 'id_cadastro = :id_cadastro and id_anexo = :id_anexo;'; FDQuery.ExecSQL(sSQL,[Self.DescricaoAnexo, Self.NomeArquivo, Self.DataAnexo, Self.ID, Self.IdAnexo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit ImageLoader; interface uses GameTypes; function LoadGameImage(const FileName : string) : TGameImage; procedure ImageReleased(const FileName : string); implementation uses SysUtils, Classes, SpeedBmp, Dib2Frames, SpriteLoaders, ImageLoaders, GifLoader, SyncObjs; var vLoadedImages : TStringList; vLoaderLock : TCriticalSection; function LoadGameImage(const FileName : string) : TGameImage; function HasGifExtension(const FileName : string) : boolean; const GifExt = '.GIF'; var i, j : integer; begin i := Length(FileName); j := Length(GifExt); while (j > 0) and (i > 0) and (UpCase( FileName[i] ) = GifExt[j]) do begin dec(i); dec(j); end; Result := j = 0; end; var aux : TSpeedBitmap; ImgStream : TMemoryStream; index : integer; begin vLoaderLock.Enter; try index := vLoadedImages.IndexOf(FileName); if index = -1 then begin if HasGifExtension(FileName) then try ImgStream := TMemoryStream.Create; try ImgStream.LoadFromFile(FileName); LoadFrameImage(Result, ImgStream); finally ImgStream.Free; end; except Result := nil; end else try aux := TSpeedBitmap.Create; try aux.LoadFromFile(FileName); Result := FrameFromDib(aux.DibHeader, aux.ScanLines); finally aux.Free; end; except Result := nil; end; if Result <> nil then vLoadedImages.AddObject(FileName, Result); end else begin Result := TGameImage(vLoadedImages.Objects[index]); Result.AddRef; end; finally vLoaderLock.Leave; end; { if Result <> nil then begin getmem(tmp, Result.Width*Result.Height); try try BltCopyOpaque(Result.PixelAddr[0, 0, 0], tmp, Result.Width, Result.Height, Result.StorageWidth, Result.Width); except raise Exception.Create('Hehe. I got you!'); end; finally freemem(tmp); end; end; } end; procedure ImageReleased(const FileName : string); var i : integer; begin vLoaderLock.Enter; try i := vLoadedImages.IndexOf(FileName); if i <> -1 then vLoadedImages.Delete(i); finally vLoaderLock.Leave; end; end; initialization RegisterLoader( GetGifLoader, 0 ); vLoadedImages := TStringList.Create; vLoaderLock := TCriticalSection.Create; finalization vLoaderLock.Free; vLoadedImages.Free; end.
unit AutoDocObjects; interface uses dSpecIntf; type TBaseAutoDoc = class(TInterfacedObject, IAutoDoc) private FContext: IContext; FEnabled: Boolean; function GetEnabled : Boolean; procedure SetEnabled(Value : Boolean); protected function SplitCamelCaseString(const s : string) : string; function DoOutput(const s : string) : string; public constructor Create(const AContext: IContext); destructor Destroy; override; function BeginSpec(const ContextName, SpecName : string) : string; function DocSpec(const Spec : string) : string; end; implementation uses SysUtils; { TBaseAutoDoc } function TBaseAutoDoc.BeginSpec(const ContextName, SpecName: string): string; begin Result := DoOutput(ContextName + ' - ' + SplitCamelCaseString(SpecName)); end; constructor TBaseAutoDoc.Create(const AContext: IContext); begin FContext := AContext; end; destructor TBaseAutoDoc.Destroy; begin FContext := nil; inherited; end; function TBaseAutoDoc.DocSpec(const Spec: string): string; var ContextDescription: string; begin if FContext.ContextDescription <> '' then ContextDescription := FContext.ContextDescription + ', ' else ContextDescription := ''; Result := DoOutput(' ' + ContextDescription + Spec); end; function TBaseAutoDoc.DoOutput(const s: string): string; begin if FEnabled then Result := s else Result := ''; end; function TBaseAutoDoc.GetEnabled: Boolean; begin Result := FEnabled; end; procedure TBaseAutoDoc.SetEnabled(Value: Boolean); begin FEnabled := Value; end; function TBaseAutoDoc.SplitCamelCaseString(const s: string): string; var i: Integer; begin i := 2; Result := s[1]; while i <= Length(s) do begin if s[i] = UpperCase(s[i]) then Result := Result + ' '; Result := Result + LowerCase(s[i]); Inc(i); end; end; end.
unit uProduto; interface type TProduto = class private Fpro_CodProduto: Integer; Fpro_CodIntProduto: Integer; Fpro_DescricaoProduto: String; Fpro_Estoque: Double; Fpro_Empresa: Integer; procedure Setpro_CodIntProduto(const Value: Integer); procedure Setpro_CodProduto(const Value: Integer); procedure Setpro_DescricaoProduto(const Value: String); procedure Setpro_Empresa(const Value: Integer); procedure Setpro_Estoque(const Value: Double); public Constructor Create; Destructor Destroy; override; protected published property pro_Empresa : Integer read Fpro_Empresa write Setpro_Empresa; property pro_CodProduto : Integer read Fpro_CodProduto write Setpro_CodProduto; property pro_CodIntProduto : Integer read Fpro_CodIntProduto write Setpro_CodIntProduto; property pro_DescricaoProduto: String read Fpro_DescricaoProduto write Setpro_DescricaoProduto; property pro_Estoque : Double read Fpro_Estoque write Setpro_Estoque; end; implementation { TProduto } constructor TProduto.Create; begin Fpro_CodProduto := 0; Fpro_CodIntProduto := 0; Fpro_DescricaoProduto := ''; Fpro_Estoque := 0; Fpro_Empresa := 0; end; destructor TProduto.Destroy; begin inherited; end; procedure TProduto.Setpro_CodIntProduto(const Value: Integer); begin Fpro_CodIntProduto := Value; end; procedure TProduto.Setpro_CodProduto(const Value: Integer); begin Fpro_CodProduto := Value; end; procedure TProduto.Setpro_DescricaoProduto(const Value: String); begin Fpro_DescricaoProduto := Value; end; procedure TProduto.Setpro_Empresa(const Value: Integer); begin Fpro_Empresa := Value; end; procedure TProduto.Setpro_Estoque(const Value: Double); begin Fpro_Estoque := Value; end; end.
{ Subroutine SST_R_PAS_EXP_TERM (TERM_STR_H,NVAL_ERR,TERM) * * The tag for a nested EXPRESSION2 - EXPRESSION4 or ITEM syntax has just been * read. Fill in TERM to reflect this nested expression. A nested expression * will only be created if necessary, otherwise the term will be an item. * STR_H is the string handle to the nested term. If NVAL_ERR is TRUE, then * it will be an error if the term does not have a resolable constant value. } module sst_r_pas_EXP_TERM; define sst_r_pas_exp_term; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_exp_term ( {read and process next term in expression} in term_str_h: syo_string_t; {SYN string handle for whole term} in nval_err: boolean; {unknown value at compile time is err if TRUE} out term: sst_exp_term_t); {term descriptor to fill in} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} tag2: sys_int_machine_t; {to avoid corrupting TAG} str2_h: syo_string_t; {handle to string associated with TAG2} levels_down: sys_int_machine_t; {number of syntax levels currently down} label exp_loop, leave; begin levels_down := 0; {init number of syntax levels below caller} exp_loop: {back here if just contains one expression} syo_push_pos; {save syn position at old level} syo_level_down; {down into this EXPRESSIONn syntax level} levels_down := levels_down + 1; {one more syntax level down from caller} syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'exp_bad', nil, 0); {item or nested exp} syo_push_pos; {save position at nested expression} syo_get_tag_msg (tag2, str2_h, 'sst_pas_read', 'exp_bad', nil, 0); {operator tag, if any} syo_pop_pos; {restore current pos to nested expression} if tag2 <> syo_tag_end_k then begin {term is more than just one ITEM ?} syo_pop_pos; {back to start of this expression level} levels_down := levels_down - 1; {one less syntax level below caller} term.next_p := nil; {init to this is last term in expression} term.op1 := sst_op1_none_k; {init to no preceeding unadic operator} term.ttype := sst_term_exp_k; {term is a nested expression} term.str_h := str_h; {save term source stream handle} term.val_eval := false; {inidicate not tried to resolve constant value} sst_r_pas_exp (term_str_h, nval_err, term.exp_exp_p); {process nested expression} sst_term_eval (term, nval_err); {fully evaluate this term} goto leave; {TERM all filled in} end; { * There is only one tagged syntax in the current syntax level. Its tag is * in TAG. } case tag of { * The tagged syntax is another nested expression. } 1: begin goto exp_loop; {back for another level down} end; { * The tagged syntax is an ITEM. } 2: begin term.str_h := str_h; {save source stream handle to this item} sst_r_pas_item (term); {read and process ITEM syntax} end; { * Unexpected TAG value. } otherwise syo_error_tag_unexp (tag, str_h); end; {end of cases for first tag in EXPRESSION} leave: {common exit point} while levels_down > 0 do begin {once for each nested syntax level} syo_pop_pos; {back up one level} levels_down := levels_down - 1; {keep track of current nesting level} end; {back to pop another level up} end;
unit MFichas.Model.Usuario.Funcoes.Editar; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Usuario.Interfaces, MFichas.Model.Entidade.USUARIO, MFichas.Controller.Types; type TModelUsuarioFuncoesEditar = class(TInterfacedObject, iModelUsuarioFuncoesEditar) private [weak] FParent : iModelUsuario; FEntidade : TUSUARIO; FGUUID : String; FLogin : String; FNome : String; FSenha : String; FTipoUsuario : Integer; FAtivoInativo: Integer; FListaUsuario: TObjectList<TUSUARIO>; constructor Create(AParent: iModelUsuario); procedure RecuperarObjetoDoBancoDeDados; procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelUsuario): iModelUsuarioFuncoesEditar; function GUUID(AGUUID: String) : iModelUsuarioFuncoesEditar; function Login(ALogin: String) : iModelUsuarioFuncoesEditar; function Nome(ANomeUsuario: String) : iModelUsuarioFuncoesEditar; function Senha(ASenha: String) : iModelUsuarioFuncoesEditar; function TipoUsuario(ABoolean: Integer) : iModelUsuarioFuncoesEditar; function AtivoInativo(ABoolean: Integer): iModelUsuarioFuncoesEditar; function &End : iModelUsuarioFuncoes; end; implementation { TModelUsuarioFuncoesEditar } function TModelUsuarioFuncoesEditar.&End: iModelUsuarioFuncoes; begin Result := FParent.Funcoes; RecuperarObjetoDoBancoDeDados; Gravar; end; function TModelUsuarioFuncoesEditar.AtivoInativo( ABoolean: Integer): iModelUsuarioFuncoesEditar; begin Result := Self; FAtivoInativo := ABoolean; end; constructor TModelUsuarioFuncoesEditar.Create(AParent: iModelUsuario); begin FParent := AParent; FEntidade := TUSUARIO.Create; end; destructor TModelUsuarioFuncoesEditar.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FEntidade); if Assigned(FListaUsuario) then FreeAndNil(FListaUsuario); {$ELSE} FEntidade.Free; FEntidade.DisposeOf; if Assigned(FListaUsuario) then begin FListaUsuario.Free; FListaUsuario.DisposeOf; end; {$ENDIF} inherited; end; function TModelUsuarioFuncoesEditar.TipoUsuario(ABoolean: Integer) : iModelUsuarioFuncoesEditar; begin Result := Self; FTipoUsuario := ABoolean; end; procedure TModelUsuarioFuncoesEditar.Gravar; begin FParent.DAO.Modify(FEntidade); FEntidade.GUUID := FGUUID; FEntidade.LOGIN := FLogin; FEntidade.NOME := FNome; FEntidade.SENHA := FSenha; FEntidade.TIPO := FTipoUsuario; FEntidade.STATUS := FAtivoInativo; FParent.DAO.Update(FEntidade); end; function TModelUsuarioFuncoesEditar.GUUID( AGUUID: String): iModelUsuarioFuncoesEditar; begin Result := Self; FGUUID := AGUUID; end; function TModelUsuarioFuncoesEditar.Login( ALogin: String): iModelUsuarioFuncoesEditar; begin Result := Self; FLogin := ALogin.ToUpper; end; class function TModelUsuarioFuncoesEditar.New(AParent: iModelUsuario): iModelUsuarioFuncoesEditar; begin Result := Self.Create(AParent); end; function TModelUsuarioFuncoesEditar.Nome( ANomeUsuario: String): iModelUsuarioFuncoesEditar; begin Result := Self; FNome := ANomeUsuario.ToUpper; end; procedure TModelUsuarioFuncoesEditar.RecuperarObjetoDoBancoDeDados; begin FListaUsuario := FParent.DAO.FindWhere('GUUID = ' + QuotedStr(FGUUID)); FEntidade.GUUID := FListaUsuario[0].GUUID; FEntidade.LOGIN := FListaUsuario[0].LOGIN; FEntidade.NOME := FListaUsuario[0].NOME; FEntidade.SENHA := FListaUsuario[0].SENHA; FEntidade.TIPO := FListaUsuario[0].TIPO; FEntidade.STATUS := FListaUsuario[0].STATUS; FEntidade.DATACADASTRO := FListaUsuario[0].DATACADASTRO; FEntidade.DATAALTERACAO := FListaUsuario[0].DATAALTERACAO; end; function TModelUsuarioFuncoesEditar.Senha( ASenha: String): iModelUsuarioFuncoesEditar; begin Result := Self; FSenha := ASenha; end; end.
{.GXFormatter.config=twm} unit GX_dzVersionInfo; interface uses SysUtils; type EApplicationInfo = class(Exception); EAIChecksumError = class(EApplicationInfo); EAIUnknownProperty = class(EApplicationInfo); EAIInvalidVersionInfo = class(EApplicationInfo); type TFileProperty = (FpProductName, FpProductVersion, FpFileDescription, FpFileVersion, FpCopyright, FpCompanyName, FpTrademarks, fpInternalName, fpOriginalFilename); TFilePropertySet = set of TFileProperty; type TVersionParts = (vpMajor, vpMajorMinor, vpMajorMinorRevision, vpFull); type TFileVersionRec = record Major: Integer; Minor: Integer; Revision: Integer; Build: Integer; IsValid: Boolean; end; type IFileInfo = interface ['{BF3A3600-1E39-4618-BD7A-FBBD6C148C2E}'] function HasVersionInfo: Boolean; procedure SetAllowExceptions(_Value: Boolean); ///<summary> If set to false, any exceptions will be ignored and an empty string will /// be returned. </summary> property AllowExceptions: Boolean write SetAllowExceptions; ///<summary> The file name.</summary> function Filename: string; ///<summary> The file directory whithout the filename with a terminating backslash </summary> function FileDir: string; ///<summary> The file description from the version resource </summary> function FileDescription: string; ///<summary> The file version from the file version resource </summary> function FileVersion: string; function FileVersionRec: TFileVersionRec; function FileVersionStr(_Parts: TVersionParts = vpMajorMinorRevision): string; ///<summary> The file's product name from the version resource </summary> function ProductName: string; ///<summary> The the product version from the version resource </summary> function ProductVersion: string; ///<summary> The company name from the version resource </summary> function Company: string; deprecated; // use CompanyName ///<summary> The company name from the version resource </summary> function CompanyName: string; ///<summary> The LegalCopyRight string from the file version resources </summary> function LegalCopyRight: string; ///<summary> The LegalTrademark string from the file version resources </summary> function LegalTradeMarks: string; function InternalName: string; function OriginalFilename: string; end; type TEXEVersionData = record CompanyName, FileDescription, FileVersion, InternalName, LegalCopyRight, LegalTradeMarks, OriginalFilename, ProductName, ProductVersion, Comments, PrivateBuild, SpecialBuild: string; end; ///<summary> abstract ancestor, do not instantiate this class, instantiate one of /// the derived classes below </summary> TCustomFileInfo = class(TInterfacedObject) private FAllowExceptions: Boolean; FFilename: string; FFilePropertiesRead: Boolean; FFileProperties: array[TFileProperty] of string; function GetFileProperty(_Property: TFileProperty): string; virtual; function ReadVersionData: TEXEVersionData; protected // implements IFileInfo procedure SetAllowExceptions(_Value: Boolean); function HasVersionInfo: Boolean; function Filename: string; function FileDir: string; function FileDescription: string; function FileVersion: string; function FileVersionRec: TFileVersionRec; virtual; function FileVersionStr(_Parts: TVersionParts = vpMajorMinorRevision): string; function ProductName: string; function ProductVersion: string; ///<summary> The company name from the version resource </summary> function Company: string; ///<summary> The company name from the version resource </summary> function CompanyName: string; ///<summary> The LegalCopyRight string from the file version resources </summary> function LegalCopyRight: string; ///<summary> The LegalTrademark string from the file version resources </summary> function LegalTradeMarks: string; function InternalName: string; function OriginalFilename: string; public constructor Create; destructor Destroy; override; property AllowExceptions: Boolean read FAllowExceptions write SetAllowExceptions; end; type ///<summary> Get informations about the given file.</summary> TFileInfo = class(TCustomFileInfo, IFileInfo) public constructor Create(const _Filename: string); end; type ///<summary> Get informations about the current executable /// If called from a dll it will return the info about the /// calling executable, if called from an executable, it will return /// info about itself. </summary> TApplicationInfo = class(TCustomFileInfo, IFileInfo) public constructor Create; end; type ///<summary> Get informations about the current DLL. /// It will always return info about itself regardless of whether it is /// called from a dll or an executable </summary> TDllInfo = class(TCustomFileInfo, IFileInfo) public constructor Create; end; type TDummyFileInfo = class(TCustomFileInfo, IFileInfo) protected function GetFileProperty(_Property: TFileProperty): string; override; function FileVersionRec: TFileVersionRec; override; public constructor Create; end; implementation uses Windows, Forms, GX_dzOsUtils; { TCustomFileInfo } constructor TCustomFileInfo.Create; begin inherited; FAllowExceptions := True; FFilePropertiesRead := False; end; function TCustomFileInfo.Filename: string; begin Result := FFilename; end; destructor TCustomFileInfo.Destroy; begin inherited; end; function TCustomFileInfo.FileDescription: string; begin Result := GetFileProperty(FpFileDescription); end; function TCustomFileInfo.FileDir: string; begin Result := ExtractFileDir(Filename); if Result <> '' then Result := IncludeTrailingPathDelimiter(Result); end; procedure TCustomFileInfo.SetAllowExceptions(_Value: Boolean); begin FAllowExceptions := _Value; end; function TCustomFileInfo.ReadVersionData: TEXEVersionData; // code taken from http://stackoverflow.com/a/5539411/49925 type PLandCodepage = ^TLandCodepage; TLandCodepage = record wLanguage, wCodePage: Word; end; var Dummy, Len: Cardinal; Buf, pntr: Pointer; lang: string; begin Len := GetFileVersionInfoSize(PChar(Filename), Dummy); if Len = 0 then RaiseLastOSError; GetMem(Buf, Len); try if not GetFileVersionInfo(PChar(Filename), 0, Len, Buf) then RaiseLastOSError; if not VerQueryValue(Buf, '\VarFileInfo\Translation\', pntr, Len) then RaiseLastOSError; lang := Format('%.4x%.4x', [PLandCodepage(pntr)^.wLanguage, PLandCodepage(pntr)^.wCodePage]); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\CompanyName'), pntr, Len) { and (@len <> nil)} then Result.CompanyName := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\FileDescription'), pntr, Len) { and (@len <> nil)} then Result.FileDescription := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\FileVersion'), pntr, Len) { and (@len <> nil)} then Result.FileVersion := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\InternalName'), pntr, Len) { and (@len <> nil)} then Result.InternalName := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\LegalCopyright'), pntr, Len) { and (@len <> nil)} then Result.LegalCopyRight := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\LegalTrademarks'), pntr, Len) { and (@len <> nil)} then Result.LegalTradeMarks := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\OriginalFileName'), pntr, Len) { and (@len <> nil)} then Result.OriginalFilename := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\ProductName'), pntr, Len) { and (@len <> nil)} then Result.ProductName := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\ProductVersion'), pntr, Len) { and (@len <> nil)} then Result.ProductVersion := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\Comments'), pntr, Len) { and (@len <> nil)} then Result.Comments := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\PrivateBuild'), pntr, Len) { and (@len <> nil)} then Result.PrivateBuild := PChar(pntr); if VerQueryValue(Buf, PChar('\StringFileInfo\' + lang + '\SpecialBuild'), pntr, Len) { and (@len <> nil)} then Result.SpecialBuild := PChar(pntr); finally FreeMem(Buf); end; end; function TCustomFileInfo.HasVersionInfo: Boolean; var Handle: DWORD; Size: DWORD; begin Size := GetFileVersionInfoSize(PChar(Filename), Handle); Result := Size <> 0; end; function TCustomFileInfo.GetFileProperty(_Property: TFileProperty): string; resourcestring SFileHasNoVersionInfo = 'File "%s" has no version information.'; var fi: TEXEVersionData; begin Result := ''; if not FFilePropertiesRead then begin try case _Property of FpProductName, FpProductVersion, FpCompanyName, FpFileDescription, FpFileVersion, FpCopyright, fpInternalName, fpOriginalFilename: begin if not HasVersionInfo then begin if FAllowExceptions then raise Exception.CreateFmt(SFileHasNoVersionInfo, [Filename]); Exit; end; fi := Self.ReadVersionData; FFileProperties[FpFileVersion] := fi.FileVersion; FFileProperties[FpFileDescription] := fi.FileDescription; FFileProperties[FpProductName] := fi.ProductName; FFileProperties[FpProductVersion] := fi.ProductVersion; FFileProperties[FpCopyright] := fi.LegalCopyRight; FFileProperties[FpTrademarks] := fi.LegalTradeMarks; FFileProperties[FpCompanyName] := fi.CompanyName; FFileProperties[fpOriginalFilename] := fi.OriginalFilename; FFileProperties[fpInternalName] := fi.InternalName; FFilePropertiesRead := True; end; end; except if FAllowExceptions then raise; Exit; end; end; Result := FFileProperties[_Property]; end; function TCustomFileInfo.InternalName: string; begin Result := GetFileProperty(fpInternalName); end; function TCustomFileInfo.Company: string; begin Result := CompanyName; end; function TCustomFileInfo.CompanyName: string; begin Result := GetFileProperty(FpCompanyName); end; function TCustomFileInfo.LegalCopyRight: string; begin Result := GetFileProperty(FpCopyright); end; function TCustomFileInfo.LegalTradeMarks: string; begin Result := GetFileProperty(FpTrademarks); end; function TCustomFileInfo.OriginalFilename: string; begin Result := GetFileProperty(fpOriginalFilename); end; function TCustomFileInfo.FileVersion: string; begin Result := GetFileProperty(FpFileVersion); end; function TCustomFileInfo.FileVersionRec: TFileVersionRec; begin ZeroMemory(@Result, SizeOf(Result)); Result.IsValid := GetFileBuildInfo(FFilename, Result.Major, Result.Minor, Result.Revision, Result.Build); end; function TCustomFileInfo.FileVersionStr(_Parts: TVersionParts = vpMajorMinorRevision): string; resourcestring SInvalidVersionPart = 'Invalid version part (%d)'; SNoVersionInfo = '<no version information>'; var Rec: TFileVersionRec; begin Rec := FileVersionRec; if Rec.IsValid then begin case _Parts of vpMajor: Result := IntToStr(Rec.Major); vpMajorMinor: Result := IntToStr(Rec.Major) + '.' + IntToStr(Rec.Minor); vpMajorMinorRevision: Result := IntToStr(Rec.Major) + '.' + IntToStr(Rec.Minor) + '.' + IntToStr(Rec.Revision); vpFull: Result := IntToStr(Rec.Major) + '.' + IntToStr(Rec.Minor) + '.' + IntToStr(Rec.Revision) + '.' + IntToStr(Rec.Build) else raise EApplicationInfo.CreateFmt(SInvalidVersionPart, [Ord(_Parts)]); end; end else Result := SNoVersionInfo; end; function TCustomFileInfo.ProductName: string; begin Result := GetFileProperty(FpProductName); end; function TCustomFileInfo.ProductVersion: string; begin Result := GetFileProperty(FpProductVersion); end; { TFileInfo } constructor TFileInfo.Create(const _Filename: string); begin inherited Create; FFilename := ExpandFileName(_Filename); end; { TApplicationInfo } constructor TApplicationInfo.Create; begin inherited Create; FFilename := GetModuleFilename(0); end; { TDllInfo } constructor TDllInfo.Create; begin inherited Create; FFilename := GetModuleFilename; end; { TDummyFileInfo } constructor TDummyFileInfo.Create; begin inherited Create; AllowExceptions := False; end; function TDummyFileInfo.FileVersionRec: TFileVersionRec; begin ZeroMemory(@Result, SizeOf(Result)); Result.IsValid := False; end; function TDummyFileInfo.GetFileProperty(_Property: TFileProperty): string; begin Result := ''; end; end.
unit FFSLmdLabel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDBaseLabel, LMDCustomLabel, LmdSimpleLabel, LMDLabel, LMDCustomSimpleLabel, FFSTypes; type TFFSLmdLabel = class(TLMDSimpleLabel) private FEnterChangeColor: boolean; { Private declarations } procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; procedure SetEnterChangeColor(const Value: boolean); protected { Protected declarations } procedure MouseEnter;override; procedure MouseExit;override; public { Public declarations } constructor create(AOwner:TCOmponent);override; published { Published declarations } property EnterChangeColor:boolean read FEnterChangeColor write SetEnterChangeColor default true; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Common', [TFFSLmdLabel]); end; { TFFSLmdLabel } constructor TFFSLmdLabel.create(AOwner: TCOmponent); begin inherited; font.Color := FFSColor[fcsActionText]; InActiveColor := FFSColor[fcsActionText]; ActiveColor := FFSColor[fcsActionRollover]; EnterChangeColor := true; JumpMode := jmCustom; end; procedure TFFSLmdLabel.MouseEnter; begin inherited; if EnterChangeColor then font.color := ActiveColor; end; procedure TFFSLmdLabel.MouseExit; begin inherited; if EnterChangeColor then font.color := InactiveColor; end; procedure TFFSLmdLabel.MsgFFSColorChange(var Msg: TMessage); begin font.Color := FFSColor[fcsActionText]; InActiveColor := FFSColor[fcsActionText]; ActiveColor := FFSColor[fcsActionRollover]; end; procedure TFFSLmdLabel.SetEnterChangeColor(const Value: boolean); begin FEnterChangeColor := Value; end; end.
unit BlkLvForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Create: TButton; Target: TEdit; procedure CreateClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses BlockLevels; {$R *.DFM} procedure TForm1.CreateClick(Sender: TObject); var BlkLv : TLevelManager; Stream : TStream; begin BlkLv := TLevelManager.Create; Stream := TFileStream.Create(Target.Text, fmOpenRead); try if BlkLv.CreateLevels(Stream, ExtractFilePath(Target.Text)) then ShowMessage('Pincha!!') else ShowMessage('NIET!!') finally Stream.Free; BlkLv.Free; end; end; end.
unit uTanggal; interface type Tanggal = record Hari : string; Tanggal, Bulan, Tahun : integer; end; procedure load (var f:text;p:string); {* procedure yang digunakan untuk me-load data dari file eksternal pemesanan.txt ke dalam variabel internal I.S : file eksternal pemesanan.txt telah terdefinisi F.S : data di pemesanan.txt telah ditampung ke dalam dP *} procedure loadTanggal(var tgl: Tanggal); {* procedure yang digunakan untuk me-load data dari file eksternal tanggal.txt ke dalam variabel internal I.S : file eksternal tanggal.txt telah terdefinisi F.S : data di tanggal.txt telah ditampung ke dalam tgl *} procedure makeTanggal(Tanggal,Bulan,Tahun :integer; var tgl : Tanggal); {* procedure yang digunakan untuk memunculkan type tanggal dari Tanggal, Bulan, dan Tahun I.S : Tanggal, Bulan, Tahun telah terdefinisi F.S : type tanggal terdefinisi *} function isKabisat(Tahun: integer) : boolean; {* function digunakan untuk mengecek apakah Tahun merupakan tahun kabisat atau bukan *} function nameBulan(Bulan: integer): string; {* function digunakan untuk memunculkan nama bulan dari input Bulan yang bertipe integer *} function getDay(Tanggal, Bulan, Tahun : integer) : string ; {* functon digunakan untuk memunculkan nama hari dari Tanggal, Bulan, dan Tahun *} function tanggalMax(Bulan,Tahun : integer) : integer; {* function digunakan untuk mengecek tanggal maksimum dari suatu Bulan dan Tahun *} function afterXDay(tgl : Tanggal; x : integer ) : Tanggal ; {* function yang digunakan untuk memunculkan tanggal setelah beberapa hari sesudahnya *} procedure writeTanggal(tgl :Tanggal); {* procedure yang digunakan untuk menuliskan tgl I.S : tgl terdefinisi F.S : tgl dimunculkan ke layar *} function isTanggalValid(Tanggal, Bulan, Tahun : integer) : boolean; {* function digunakan untuk mengecek masukkan Tanggal, Bulan, dan Tahun apakah valid atau tidak *} implementation // --- Load File untuk tanggal.txt --- // procedure load (var f:text;p:string); begin assign(f,p); reset(f); end; procedure loadTanggal(var tgl: Tanggal); var dTanggal: text; f:ansistring; pos1,l,i,j:integer; begin j:=1; load(dTanggal,'database\tanggal.txt'); while not Eof(dTanggal) do begin readln(dTanggal,f); for i:=1 to 4 do begin pos1:=pos('|',f); l:=length(copy(f,1,pos1+1)); case i of 1:val(copy(f,1,pos1-2),tgl.Tanggal); 2:val(copy(f,1,pos1-2),tgl.Bulan); 3:val(copy(f,1,pos1-2),tgl.Tahun); 4:tgl.Hari:=copy(f,1,pos1-2); end; delete(f,1,l); end; j:=j+1; end; close(dTanggal); end; // --- Selesai Load --- // function getDay(Tanggal, Bulan, Tahun : integer) : string ; var i : integer; jml : longint; begin // Senin => 1 Januari 1990 || deafult jml:=0; for i:=1990 to ((Tahun)-1) do begin if ((i mod 4) = 0) then jml:=jml+366 else jml:=jml+365; end; for i:=1 to ((Bulan)-1) do begin if ( (i=1)or(i=3)or(i=5)or(i=7)or(i=8)or(i=10)or(i=12) ) then jml:=jml+31 else if ( (i = 2) and ((Tahun mod 4) = 0) ) then jml:=jml+29 else if ( (i = 2) and ((Tahun mod 4) <> 0) ) then jml:=jml+28 else jml:=jml+30; end; jml:=jml+ ( (Tanggal) - 1 ); case (jml mod 7) of 0 : getDay:=('Senin'); 1 : getDay:=('Selasa'); 2 : getDay:=('Rabu'); 3 : getDay:=('Kamis'); 4 : getDay:=('Jumat'); 5 : getDay:=('Sabtu'); 6 : getDay:=('Minggu'); end; end; procedure makeTanggal(Tanggal, Bulan, Tahun :integer; var tgl : Tanggal); begin tgl.Hari:=getDay(Tanggal, Bulan, Tahun); tgl.Tanggal:=Tanggal; tgl.Bulan:=Bulan; tgl.Tahun:=Tahun; end; function isKabisat(tahun: integer) : boolean; begin if tahun mod 4 = 0 then isKabisat:=true else isKabisat:=false; end; function nameBulan(bulan: integer): string; begin case (bulan) of 1: nameBulan:='Januari'; 2: nameBulan:='Februari'; 3: nameBulan:='Maret'; 4: nameBulan:='April'; 5: nameBulan:='Mei'; 6: nameBulan:='Juni'; 7: nameBulan:='Juli'; 8: nameBulan:='Agustus'; 9: nameBulan:='September'; 10: nameBulan:='Oktober'; 11: nameBulan:='November'; 12: nameBulan:='Desember'; end; end; function tanggalMax(bulan,tahun : integer) : integer; begin case (bulan) of 1: tanggalMax:=31; 2: if ( (tahun mod 4) = 0) then tanggalMax:=29 else tanggalMax:=28; 3: tanggalMax:=31; 4: tanggalMax:=30; 5: tanggalMax:=31; 6: tanggalMax:=30; 7: tanggalMax:=31; 8: tanggalMax:=31; 9: tanggalMax:=30; 10: tanggalMax:=31; 11: tanggalMax:=30; 12: tanggalMax:=31; end; end; function afterXDay(tgl : Tanggal; x : integer ) : Tanggal ; var Tanggal, Bulan, Tahun : integer; hari: integer; begin Tanggal:=tgl.Tanggal; Bulan:=tgl.Bulan; Tahun:=tgl.Tahun; hari:=Tanggal+x; if (x<0) then begin while ( hari<0 ) do begin hari:=hari+tanggalMax(Bulan, Tahun); Bulan:=Bulan-1; if Bulan=0 then begin Bulan:=12; Tahun:=Tahun-1; end; end; makeTanggal(Tanggal,Bulan,Tahun, tgl); afterXDay:=tgl; end else begin while ( (hari>366) or (hari>365) ) do begin if ( (Tahun mod 4) = 0) then begin Tahun:=Tahun+1; hari:=hari-366; end else begin Tahun:=Tahun+1; hari:=hari-365; end; end; while hari>tanggalMax(Bulan,Tahun) do begin hari:=hari-tanggalMax(Bulan,Tahun); Bulan:=Bulan+1; end; makeTanggal(hari,Bulan,Tahun, tgl); afterXDay:=tgl; end; end; procedure writeTanggal(tgl :Tanggal); begin writeln(getDay(tgl.Tanggal, tgl.Bulan, tgl.Tahun),', ', tgl.Tanggal , ' ' , nameBulan(tgl.bulan) ,' ', tgl.tahun); end; function isTanggalValid(Tanggal, Bulan, Tahun :integer) : boolean; begin if Tahun>0 then if ( (Bulan>0) and (Bulan<=12) ) then if ( (Tanggal>0) and (Tanggal<=tanggalMax(Bulan,Tahun)) ) then isTanggalValid:=True else isTanggalValid:=false else isTanggalValid:=false else isTanggalValid:=false; end; end.