text
stringlengths
14
6.51M
unit Acme.Robot.GUI.Console.Controller; interface uses System.Generics.Collections, System.SysUtils, Acme.Robot.Core.Bot; type TConsoleBotController = class private FBot: IBot; FMacros: TDictionary<string, TProc<IBot>>; public constructor Create(ABot: IBot); function HandleNextCommand: Boolean; end; implementation resourcestring StrCommandNotFound = 'Command not found'; { TConsoleBotController } constructor TConsoleBotController.Create(ABot: IBot); begin inherited Create; FBot := ABot; FMacros := TDictionary < string, TProc < IBot >>.Create; FMacros.Add('T1', procedure(ABot: IBot) begin ABot.TurnOn; end); FMacros.Add('T0', procedure(ABot: IBot) begin ABot.TurnOff; end); FMacros.Add('NAME', procedure(ABot: IBot) begin Writeln(Format('[Name] %s', [ABot.Name])) end); FMacros.Add('ON', procedure(ABot: IBot) begin ABot.Rotate(TBotOrientation.North); end); FMacros.Add('OS', procedure(ABot: IBot) begin ABot.Rotate(TBotOrientation.South); end); FMacros.Add('OE', procedure(ABot: IBot) begin ABot.Rotate(TBotOrientation.East); end); FMacros.Add('OW', procedure(ABot: IBot) begin ABot.Rotate(TBotOrientation.West); end); FMacros.Add('M1', procedure(ABot: IBot) begin ABot.Move(1); end); FMacros.Add('M5', procedure(ABot: IBot) begin ABot.Move(5); end); FMacros.Add('HELLO', procedure(ABot: IBot) var LTalkingBot: ITalkingBot; begin if Supports(ABot, ITalkingBot, LTalkingBot) then LTalkingBot.Say('Hello to you!'); end); end; function TConsoleBotController.HandleNextCommand: Boolean; var LCommand: string; LMacro: TProc<IBot>; begin Readln(LCommand); LCommand := UpperCase(Trim(LCommand)); if Length(LCommand) <= 0 then begin Result := False; Exit; end; Result := True; if not FMacros.TryGetValue(LCommand, LMacro) or not Assigned(LMacro) then begin Writeln(StrCommandNotFound); Writeln; Exit; end; LMacro(FBot); Writeln(Format('[Status] %s', [FBot.ToString])); Writeln; end; end.
unit ADC.Elevation; interface uses System.SysUtils, Winapi.Windows, Winapi.ActiveX, System.Win.ComObj, ADCommander_TLB; type // Vista SDK - extended BIND_OPTS2 struct BIND_OPTS3 = record cbStruct: DWORD; grfFlags: DWORD; grfMode: DWORD; dwTickCountDeadline: DWORD; dwTrackFlags: DWORD; dwClassContext: DWORD; locale: LCID; pServerInfo: PCOSERVERINFO; hwnd: HWND; end; PBIND_OPTS3 = ^BIND_OPTS3; type // Vista SDK - extended TOKEN_INFORMATION_CLASS enum TOKEN_INFORMATION_CLASS = ( TokenICPad, // dummy padding element TokenUser, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum ); type TOKEN_ELEVATION = packed record TokenIsElevated: DWORD; end; PTOKEN_ELEVATION = ^TOKEN_ELEVATION; function IsElevated: Boolean; procedure CoCreateInstanceAsAdmin( AHWnd: HWND; // parent for elevation prompt window const AClassID: TGUID; // COM class guid const AIID: TGUID; // interface id implemented by class out AObj // interface pointer ); function IsProcessElevated: Boolean; function RegisterUCMAComponents(AHandle: HWND; AClassID: PWideChar; AElevate: Boolean): HRESULT; function UnregisterUCMAComponents(AHandle: HWND; AClassID: PWideChar; AElevate: Boolean): HRESULT; function SaveControlEventsList(AHandle: HWND; AFileName: PWideChar; const AXMLStream: IUnknown; AElevate: Boolean): HRESULT; function DeleteControlEventsList(AHandle: HWND; AFileName: PWideChar; AElevate: Boolean): HRESULT; function CreateAccessDatabase(AHandle: HWND; AConnectionString: PWideChar; const AFieldCatalog: IUnknown; AElevate: Boolean): IUnknown; function CreateExcelBook(AHandle: HWND; const AFieldCatalog: IUnknown; AElevate: Boolean): IDispatch; procedure SaveExcelBook(AHandle: HWND; const ABook: IDispatch; AFileName: PWideChar; AFormat: Shortint; AElevate: Boolean); implementation function CoGetObject(pszName: PWideChar; pBindOptions: PBIND_OPTS3; const iid: TIID; out ppv ): HResult; stdcall; external 'ole32.dll' name 'CoGetObject'; function GetTokenInformation(TokenHandle: THandle; TokenInformationClass: TOKEN_INFORMATION_CLASS; TokenInformation: Pointer; TokenInformationLength: DWORD; var ReturnLength: DWORD ): BOOL; stdcall; external advapi32 name 'GetTokenInformation'; function IsElevated: Boolean; var Token: THandle; Elevation: TOKEN_ELEVATION; Dummy: DWORD; begin Result := False; if OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, Token) then begin Dummy := 0; if GetTokenInformation(Token, TokenElevation, @Elevation, SizeOf(TOKEN_ELEVATION), Dummy) then Result := (Elevation.TokenIsElevated <> 0); CloseHandle(Token); end; end; procedure CoCreateInstanceAsAdmin(aHWnd: HWND; const aClassID, aIID: TGUID; out aObj); var BO: BIND_OPTS3; MonikerName: String; begin if (not IsElevated) then begin { Request elevated out-of-process instance. } MonikerName := 'Elevation:Administrator!new:' + GUIDToString(aClassID); FillChar(BO, SizeOf(BIND_OPTS3), 0); BO.cbStruct := SizeOf(BIND_OPTS3); BO.dwClassContext := CLSCTX_LOCAL_SERVER; BO.hwnd := aHWnd; OleCheck(CoGetObject(PWideChar(MonikerName), @BO, aIID, aObj)); end else { Request normal in-process instance. } OleCheck(CoCreateInstance(aClassID, nil, CLSCTX_ALL, aIID, aObj)); end; function IsProcessElevated: Boolean; begin Result := IsElevated; end; function RegisterUCMAComponents(AHandle: HWND; AClassID: PWideChar; AElevate: Boolean): HRESULT; var Moniker: IElevationMoniker; begin Result := E_FAIL; try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Result := S_OK; { Attempt to register components } Moniker.RegisterUCMAComponents(AClassID); end; function UnregisterUCMAComponents(AHandle: HWND; AClassID: PWideChar; AElevate: Boolean): HRESULT; var Moniker: IElevationMoniker; begin Result := E_FAIL; try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Result := S_OK; { Attempt to unregister components } Moniker.UnregisterUCMAComponents(AClassID); end; function SaveControlEventsList(AHandle: HWND; AFileName: PWideChar; const AXMLStream: IUnknown; AElevate: Boolean): HRESULT; var Moniker: IElevationMoniker; begin Result := E_FAIL; try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Result := S_OK; Moniker.SaveControlEventsList(AFileName, AXMLStream); end; function DeleteControlEventsList(AHandle: HWND; AFileName: PWideChar; AElevate: Boolean): HRESULT; var Moniker: IElevationMoniker; begin Result := E_FAIL; try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Result := S_OK; Moniker.DeleteControlEventsList(AFileName); end; function CreateAccessDatabase(AHandle: HWND; AConnectionString: PWideChar; const AFieldCatalog: IUnknown; AElevate: Boolean): IUnknown; var Moniker: IElevationMoniker; begin Result := nil; try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Result := Moniker.CreateAccessDatabase(AConnectionString, AFieldCatalog); end; function CreateExcelBook(AHandle: HWND; const AFieldCatalog: IUnknown; AElevate: Boolean): IDispatch; var Moniker: IElevationMoniker; begin Result := nil; try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Result := Moniker.CreateExcelBook(AFieldCatalog); end; procedure SaveExcelBook(AHandle: HWND; const ABook: IDispatch; AFileName: PWideChar; AFormat: Shortint; AElevate: Boolean); var Moniker: IElevationMoniker; begin try if AElevate then { Create elevated COM object instance. } CoCreateInstanceAsAdmin( AHandle, CLASS_ElevationMoniker, IID_IElevationMoniker, Moniker ) else { Create non-elevated COM object instance. } Moniker := CoElevationMoniker.Create; except on E: Exception do begin // MessageBox( // AHandle, // PWideChar(E.Message), // PWideChar('COM object instantiation failed: ' + E.ClassName), // MB_OK or MB_ICONERROR // ); Exit; end; end; Moniker.SaveExcelBook(ABook, AFileName, AFormat); end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clSshUserKey; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, {$ELSE} System.Classes, System.SysUtils, {$ENDIF} clUtils; type TclSshUserKey = class(TPersistent) private FPrivateKey: TclByteArray; FPrivateKeyFile: string; FOnChanged: TNotifyEvent; FPassPhrase: string; procedure SetPrivateKeyFile(const Value: string); procedure SetPassPhrase(const Value: string); procedure InternalLoad; function DecodePrivateKey(const AValue: TclByteArray): TclByteArray; protected procedure Init; virtual; procedure Changed; virtual; public constructor Create; procedure Assign(Source: TPersistent); override; procedure Clear; virtual; function GetPrivateKey: TclByteArray; virtual; procedure Load(APrivateKey: TStrings); overload; procedure Load(APrivateKey: TStream); overload; procedure Load(const APrivateKey: TclByteArray); overload; virtual; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; published property PrivateKeyFile: string read FPrivateKeyFile write SetPrivateKeyFile; property PassPhrase: string read FPassPhrase write SetPassPhrase; end; implementation uses clCryptEncoder, clCryptUtils, clStreams; { TclSshUserKey } procedure TclSshUserKey.Assign(Source: TPersistent); var src: TclSshUserKey; begin if (Source is TclSshUserKey) then begin src := TclSshUserKey(Source); FPrivateKeyFile := src.PrivateKeyFile; FPassPhrase := src.PassPhrase; Changed(); end else begin inherited Assign(Source); end; end; procedure TclSshUserKey.Changed; begin Init(); if Assigned(OnChanged) then begin OnChanged(Self); end; end; procedure TclSshUserKey.InternalLoad; var priv: TStream; begin if (FPrivateKey = nil) and (PrivateKeyFile <> '') then begin priv := TFileStream.Create(PrivateKeyFile, fmOpenRead or fmShareDenyWrite); try Load(priv); finally priv.Free(); end; end; end; procedure TclSshUserKey.Clear; begin FPrivateKeyFile := ''; FPassPhrase := ''; Changed(); end; constructor TclSshUserKey.Create; begin inherited Create(); Init(); end; function TclSshUserKey.GetPrivateKey: TclByteArray; begin InternalLoad(); Result := FPrivateKey; end; procedure TclSshUserKey.Init; begin FPrivateKey := nil; end; procedure TclSshUserKey.Load(APrivateKey: TStrings); var priv: TStream; begin priv := nil; try priv := TMemoryStream.Create(); APrivateKey.SaveToStream(priv); priv.Position := 0; Load(priv); finally priv.Free(); end; end; procedure TclSshUserKey.Load(const APrivateKey: TclByteArray); begin Init(); FPrivateKey := APrivateKey; end; procedure TclSshUserKey.SetPassPhrase(const Value: string); begin if (FPassPhrase <> Value) then begin FPassPhrase := Value; Changed(); end; end; procedure TclSshUserKey.SetPrivateKeyFile(const Value: string); begin if (FPrivateKeyFile <> Value) then begin FPrivateKeyFile := Value; Changed(); end; end; function TclSshUserKey.DecodePrivateKey(const AValue: TclByteArray): TclByteArray; var encoder: TclCryptEncoder; begin encoder := TclCryptEncoder.Create(nil); try encoder.PassPhrase := PassPhrase; Result := encoder.Decode(AValue); if not (encoder.DataType in [dtRsaPrivateKey]) then begin RaiseCryptError(UnknownKeyFormat, UnknownKeyFormatCode); end; finally encoder.Free(); end; end; procedure TclSshUserKey.Load(APrivateKey: TStream); var priv: TclByteArray; len: Integer; begin len := Integer(APrivateKey.Size - APrivateKey.Position); if (len > 0) then begin SetLength(priv, len); APrivateKey.Read(priv[0], Length(priv)); priv := DecodePrivateKey(priv); end else begin priv := nil; end; Load(priv); end; end.
unit vcmOperationsCollection; {* Коллекция операций. } { Библиотека "vcm" } { Автор: Люлин А.В. © } { Модуль: vcmOperationsCollection - } { Начат: 11.03.2003 12:19 } { $Id: vcmOperationsCollection.pas,v 1.16 2011/07/29 15:08:37 lulin Exp $ } // $Log: vcmOperationsCollection.pas,v $ // Revision 1.16 2011/07/29 15:08:37 lulin // {RequestLink:209585097}. // // Revision 1.15 2009/10/12 11:27:15 lulin // - коммитим после падения CVS. // // Revision 1.15 2009/10/08 12:46:44 lulin // - чистка кода. // // Revision 1.14 2009/02/20 17:29:20 lulin // - чистка комментариев. // // Revision 1.13 2009/02/20 15:19:00 lulin // - <K>: 136941122. // // Revision 1.12 2004/09/21 16:22:18 mmorozov // change: вместо IvcmUserFriendlyControl подаём IvcmIdentifiedUserFriendlyControl; // // Revision 1.11 2004/09/13 07:10:32 mmorozov // new: используем TvcmOperationsCollectionItem.UnRegister; // // Revision 1.10 2004/09/10 16:52:08 mmorozov // new behaviour: в ReRegisterItem не вызываем UnRegisterItem если имя устанавливается впервые; // // Revision 1.9 2003/12/30 10:03:55 law // - optimization: при создании второго Main-окна не создаем по новой все формы сущностей (CQ OIT5-5628). // // Revision 1.8 2003/11/24 17:35:21 law // - new method: TvcmCustomEntities._RegisterInRep. // // Revision 1.7 2003/11/19 11:38:25 law // - new behavior: регистрируем все сущности и операции в MenuManager'е для дальнейшей централизации редактирования. Само редактирование пока не доделано. // // Revision 1.6 2003/11/18 19:35:54 law // - new: начал делать общий репозиторий модулей, сущностей и операций в MenuManager'е. Чтобы все можно было править из одного места. // // Revision 1.5 2003/07/25 10:45:43 law // - new unit: vcmBaseCollection. // // Revision 1.4 2003/04/22 14:03:00 law // - new behavior: сделана обработка операций, описанных на основной форме. // // Revision 1.3 2003/04/08 10:40:46 law // - bug fix: разрешались отсутствующие операции. // // Revision 1.2 2003/04/04 10:58:58 law // - bug fix: была ошибка в имени типа TvcmControlID. // // Revision 1.1 2003/04/01 12:54:44 law // - переименовываем MVC в VCM. // // Revision 1.8 2003/03/27 14:36:53 law // - new prop: операция теперь имеет картинку. // // Revision 1.7 2003/03/26 12:13:41 law // - cleanup. // // Revision 1.6 2003/03/24 14:04:06 law // - change: продолжаем заковыривать все относящееся к операции в _IvcmParams. // // Revision 1.5 2003/03/24 13:25:47 law // - change: продолжаем заковыривать все относящееся к операции в _IvcmParams. // // Revision 1.4 2003/03/21 12:34:43 law // - new behavior: операциям добавлен список параметров. // // Revision 1.3 2003/03/20 12:30:01 law // - new behavior: сделана обработка контекстных операций. // // Revision 1.2 2003/03/13 09:52:02 law // - new component: TvcmModuleDef. // // Revision 1.1 2003/03/11 09:31:23 law // - new prop: TvcmEntitiesCollectionItem.Operations. // {$I vcmDefine.inc } interface {$IfNDef NoVCM} uses Classes, vcmInterfaces, vcmBase, vcmBaseOperationsCollection ; type TvcmOperationsCollection = class(TvcmBaseOperationsCollection) {* Коллекция операций. } protected // internal methods procedure Notify(Item: TCollectionItem; Action: TCollectionNotification); override; {-} public // public methods class function GetItemClass: TCollectionItemClass; override; {-} procedure RegisterItem(anItem: TCollectionItem); {-} procedure ReRegisterItem(anItem: TCollectionItem); {-} procedure UnRegisterItem(anItem: TCollectionItem); {-} end;//TvcmOperationsCollection {$EndIf NoVCM} implementation {$IfNDef NoVCM} uses SysUtils, vcmUserControls, vcmOperationsCollectionItem, vcmBaseMenuManager ; // start class TvcmOperationsCollection class function TvcmOperationsCollection.GetItemClass: TCollectionItemClass; //override; {-} begin Result := TvcmOperationsCollectionItem; end; procedure TvcmOperationsCollection.RegisterItem(anItem: TCollectionItem); {-} var l_UF : IvcmIdentifiedUserFriendlyControl; l_Op : IvcmOperationDef; begin if (g_MenuManager <> nil) then begin if Supports(anItem, IvcmOperationDef, l_Op) then try if (l_Op.Name <> '') AND Supports(Owner, IvcmIdentifiedUserFriendlyControl, l_UF) then try g_MenuManager.RegisterOperation(l_UF, l_Op, Owner, anItem); finally l_UF := nil; end;//try..finally finally l_Op := nil; end;//try..finally end;//g_MenuManager <> nil end; procedure TvcmOperationsCollection.Notify(Item: TCollectionItem; Action: TCollectionNotification); //override; {-} begin inherited; case Action of cnAdded : RegisterItem(Item); cnDeleting: UnRegisterItem(Item); end;//case Action end; procedure TvcmOperationsCollection.UnRegisterItem(anItem: TCollectionItem); {-} begin TvcmOperationsCollectionItem(anItem).UnRegister; end; procedure TvcmOperationsCollection.ReRegisterItem(anItem: TCollectionItem); {-} begin with TvcmOperationsCollectionItem(anItem) do begin if IsRegistred then UnRegisterItem(anItem); RegisterItem(anItem); IsRegistred := True; end; end; {$EndIf NoVCM} end.
unit TasksAllFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, ToolWin, TasksUnit; type TFrameTasksAll = class(TFrame) toolbarMain: TToolBar; tbRefresh: TToolButton; tbLoadTasks: TToolButton; tbSaveTasks: TToolButton; ToolButton4: TToolButton; panelLeft: TPanel; panelRight: TPanel; Splitter1: TSplitter; lvAllTasks: TListView; gbTaskDetails: TGroupBox; toolbarTaskEdit: TToolBar; tbAddTask: TToolButton; tbDeleteTask: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; Label1: TLabel; Label2: TLabel; trackbarPriority: TTrackBar; lbPriorityValue: TLabel; Label3: TLabel; Label4: TLabel; trackbarStatus: TTrackBar; reTaskText: TRichEdit; lbAuthor: TLabel; dtpBegin: TDateTimePicker; dtpEnd: TDateTimePicker; procedure trackbarPriorityChange(Sender: TObject); procedure tbClick(Sender: TObject); procedure lvAllTasksChange(Sender: TObject; Item: TListItem; Change: TItemChange); private { Private declarations } TaskList: TTaskList; SelectedTask: TTaskItem; procedure LoadList(); procedure SaveList(); procedure NewItem(ASubItem: boolean = false); procedure DeleteItem(); procedure ReadSelectedTask(); procedure WriteSelectedTask(); procedure RefreshTasksList(SelectedOnly: boolean = false); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy(); override; end; implementation uses Main, MainFunc; {$R *.dfm} constructor TFrameTasksAll.Create(AOwner: TComponent); begin inherited Create(AOwner); if not Assigned(TaskList) then TaskList:=TTaskList.Create(); self.LoadList(); end; destructor TFrameTasksAll.Destroy(); begin TaskList.Free(); inherited Destroy(); end; procedure TFrameTasksAll.trackbarPriorityChange(Sender: TObject); begin lbPriorityValue.Caption := IntToStr((Sender as TTrackBar).Position); end; procedure TFrameTasksAll.RefreshTasksList(SelectedOnly: boolean = false); var Task: TTaskItem; li: TListItem; i: integer; begin if SelectedOnly then begin for i:=0 to TaskList.Count-1 do begin Task:=TTaskItem(TaskList[i]); if Task=SelectedTask then begin li:=lvAllTasks.Items[i]; li.Caption:=IntToStr(Task.Priority); li.SubItems[0]:=Task.Author; li.SubItems[1]:=Task.Name; li.SubItems[2]:=DateTimeToStr(Task.BeginDate); Exit; end; end; Exit; end; lvAllTasks.Clear(); TaskList.Sort(); for i:=0 to TaskList.Count-1 do begin Task:=TTaskItem(TaskList[i]); li:=lvAllTasks.Items.Add(); li.Data:=Task; li.Caption:=IntToStr(Task.Priority); li.SubItems.Add(Task.Author); li.SubItems.Add(Task.Name); li.SubItems.Add(DateTimeToStr(Task.BeginDate)); if Task=SelectedTask then begin li.Selected:=true; li.Focused:=true; end; end; end; procedure TFrameTasksAll.tbClick(Sender: TObject); begin if Sender=tbLoadTasks then begin LoadList(); end else if Sender=tbSaveTasks then begin SaveList(); end else if Sender=tbRefresh then begin RefreshTasksList(); end else if Sender=tbAddTask then begin NewItem(); end else if Sender=tbDeleteTask then begin DeleteItem(); end; end; procedure TFrameTasksAll.LoadList(); begin // SelectedTask:=nil; TaskList.Clear(); TaskList.LoadList(); RefreshTasksList(); end; procedure TFrameTasksAll.SaveList(); begin self.TaskList.SaveList(); end; procedure TFrameTasksAll.NewItem(ASubItem: boolean = false); var Task: TTaskItem; li: TListItem; i: integer; begin Task:=TTaskItem.Create(); Task.Name:='Новая задача'; Task.Priority:=1; Task.Status:=0; Task.Author:='Admin'; Task.BeginDate:=Now(); Task.EndDate:=Now(); self.TaskList.Add(Task); li:=lvAllTasks.Items.Add(); li.Data:=Task; li.Caption:=IntToStr(Task.Priority); li.SubItems.Add(Task.Author); li.SubItems.Add(Task.Name); li.SubItems.Add(DateTimeToStr(Task.BeginDate)); self.SelectedTask:=Task; ReadSelectedTask(); end; procedure TFrameTasksAll.ReadSelectedTask(); var Task: TTaskItem; begin if not Assigned(self.SelectedTask) then Exit; Task:=self.SelectedTask; trackbarPriority.Position:=Task.Priority; trackbarStatus.Position:=Task.Status; dtpBegin.DateTime:=Task.BeginDate; dtpEnd.DateTime:=Task.EndDate; lbAuthor.Caption:=Task.Author; //lbPeriod.Caption:=''+DateTimeToStr(Task.BeginDate)+' - '+DateTimeToStr(Task.EndDate); reTaskText.Text:=Task.Text; end; procedure TFrameTasksAll.WriteSelectedTask(); begin if not Assigned(self.SelectedTask) then Exit; self.SelectedTask.Priority:=trackbarPriority.Position; self.SelectedTask.Status:=trackbarStatus.Position; self.SelectedTask.BeginDate:=dtpBegin.DateTime; self.SelectedTask.EndDate:=dtpEnd.DateTime; //self.SelectedTask.Author:=lbAuthor.Caption; self.SelectedTask.Text:=reTaskText.Text; self.SelectedTask.Name:=''; if reTaskText.Lines.Count>0 then self.SelectedTask.Name:=reTaskText.Lines[0]; end; procedure TFrameTasksAll.DeleteItem(); var i: integer; begin if not Assigned(self.SelectedTask) then Exit; i:=lvAllTasks.ItemIndex; TaskList.Remove(SelectedTask); SelectedTask:=nil; RefreshTasksList(); while i >= lvAllTasks.Items.Count do Dec(i); if i < 0 then Exit; lvAllTasks.ItemIndex:=i; end; procedure TFrameTasksAll.lvAllTasksChange(Sender: TObject; Item: TListItem; Change: TItemChange); var li: TListItem; Task: TTaskItem; begin self.WriteSelectedTask(); self.RefreshTasksList(true); li:=TListView(Sender).Selected; if not Assigned(li) then Exit; Task:=li.Data; if not Assigned(Task) then Exit; self.SelectedTask:=Task; self.ReadSelectedTask(); end; end.
unit ufrmJurnal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDefault, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, Vcl.Menus, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, System.ImageList, Vcl.ImgList, Datasnap.DBClient, Datasnap.Provider, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, cxCheckBox, cxGridLevel, cxClasses, cxGridCustomView, Vcl.StdCtrls, cxButtons, Vcl.ComCtrls, Vcl.ExtCtrls, cxPC, dxStatusBar, cxDBExtLookupComboBox, cxCurrencyEdit, dxCore, cxDateUtils, cxDropDownEdit, cxMemo, cxLookupEdit, cxDBLookupEdit, cxMaskEdit, cxCalendar, cxTextEdit,uDBUtils,uAppUtils, uJurnal, ClientModule, uModel, uDMReport, Data.FireDACJSONReflect; type TfrmJurnal = class(TfrmDefault) pnlHeader: TPanel; lblNoBukti: TLabel; lblTglBukti: TLabel; lblKeterangan: TLabel; edNoBukti: TcxTextEdit; edTglBukti: TcxDateEdit; memKeterangan: TcxMemo; cxGridJurnal: TcxGrid; cxGridTableJurnal: TcxGridTableView; cxGridColKode: TcxGridColumn; cxGridColNama: TcxGridColumn; cxGridColDebet: TcxGridColumn; cxGridColKeterangan: TcxGridColumn; cxgrdlvlJurnal: TcxGridLevel; cxGridColKredit: TcxGridColumn; procedure ActionBaruExecute(Sender: TObject); procedure ActionHapusExecute(Sender: TObject); procedure ActionRefreshExecute(Sender: TObject); procedure ActionSimpanExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cxGridColKodePropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure cxGridColNamaPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); private FCDSAccount: tclientDataSet; FJurnal: TJurnal; function GetJurnal: TJurnal; procedure InisialisasiAccount; { Private declarations } protected function GetJenisJurnal: String; public procedure CetakSlip; override; procedure LoadData(AID : String); property Jurnal: TJurnal read GetJurnal write FJurnal; { Public declarations } end; var frmJurnal: TfrmJurnal; implementation {$R *.dfm} procedure TfrmJurnal.ActionBaruExecute(Sender: TObject); begin inherited; LoadData(''); end; procedure TfrmJurnal.ActionHapusExecute(Sender: TObject); begin inherited; if not TAppUtils.Confirm('Anda yakin akan menghapus data ?') then Exit; if ClientDataModule.ServerJurnalClient.Delete(Jurnal) then begin TAppUtils.InformationBerhasilHapus; ActionBaruExecute(Sender); end; end; procedure TfrmJurnal.ActionRefreshExecute(Sender: TObject); var lcds: TClientDataSet; begin inherited; if chkKonsolidasi1.Checked then lcds := TDBUtils.DSToCDS(ClientDataModule.ServerLaporanClient.RetriveJurnal(dtpAwal.DateTime, dtpAkhir.DateTime, nil, GetJenisJurnal), cxGridDBTableOverview) else lcds := TDBUtils.DSToCDS(ClientDataModule.ServerLaporanClient.RetriveJurnal(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang, GetJenisJurnal), cxGridDBTableOverview); cxGridDBTableOverview.SetDataset(lcds, True); cxGridDBTableOverview.SetVisibleColumns(['ID', 'CABANGID'], False); cxGridDBTableOverview.ApplyBestFit(); end; procedure TfrmJurnal.ActionSimpanExecute(Sender: TObject); var I: Integer; lJurnalItem: TJurnalItem; begin inherited; if Jurnal.ID = '' then edNoBukti.Text := ClientDataModule.ServerJurnalClient.GenerateNoBukti(edTglBukti.Date, ClientDataModule.Cabang.Kode); if not ValidateEmptyCtrl([1]) then Exit; Jurnal.NoBukti := edNoBukti.Text; Jurnal.TglBukti := edTglBukti.Date; Jurnal.Keterangan := memKeterangan.Lines.Text; Jurnal.Cabang := TCabang.CreateID(ClientDataModule.Cabang.ID); Jurnal.JurnalItems.Clear; for I := 0 to cxGridTableJurnal.DataController.RecordCount - 1 do begin lJurnalItem := TJurnalItem.Create(); cxGridTableJurnal.LoadObjectData(lJurnalItem, i); Jurnal.JurnalItems.Add(lJurnalItem); end; if Jurnal.Debet <> Jurnal.Kredit then begin TAppUtils.Warning('Nilai Debet Tidak Sama Dengan Kredit'); Exit; end; if ClientDataModule.ServerJurnalClient.Save(Jurnal) then begin TAppUtils.InformationBerhasilSimpan; ActionBaruExecute(Sender); end; end; procedure TfrmJurnal.CetakSlip; var lcds: TFDJSONDataSets; begin inherited; with dmReport do begin AddReportVariable('UserCetak', UserAplikasi.UserName); if cxPCData.ActivePageIndex = 0 then lcds := ClientDataModule.ServerJurnalClient.RetrieveDataSlip(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang.ID, 'XXX') else lcds := ClientDataModule.ServerJurnalClient.RetrieveDataSlip(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang.ID, Jurnal.ID); ExecuteReport( 'Reports/Slip_Jurnal' , lcds ); end; end; procedure TfrmJurnal.cxGridColKodePropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin inherited; cxGridTableJurnal.SetValue(cxGridTableJurnal.FocusedIndex,cxGridColNama.Index, FCDSAccount.FieldByName('ID').AsString); end; procedure TfrmJurnal.cxGridColNamaPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin inherited; cxGridTableJurnal.SetValue(cxGridTableJurnal.FocusedIndex,cxGridColKode.Index, FCDSAccount.FieldByName('ID').AsString); end; procedure TfrmJurnal.cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin inherited; LoadData(cxGridDBTableOverview.DS.FieldByName('ID').AsString); cxPCData.ActivePageIndex := 1; end; procedure TfrmJurnal.FormCreate(Sender: TObject); begin inherited; InisialisasiAccount; ActionBaruExecute(Sender); end; function TfrmJurnal.GetJenisJurnal: String; begin Result := TJurnal.ClassName; end; function TfrmJurnal.GetJurnal: TJurnal; begin if FJurnal = nil then FJurnal := TJurnal.Create; Result := FJurnal; end; procedure TfrmJurnal.InisialisasiAccount; begin FCDSAccount := TDBUtils.DSToCDS(ClientDataModule.DSDataCLient.LoadAccountPengeluaranKasLain(), Self); TcxExtLookupComboBoxProperties(cxGridColKode.Properties).LoadFromCDS(FCDSAccount, 'ID', 'Kode', ['id'], Self); TcxExtLookupComboBoxProperties(cxGridColNama.Properties).LoadFromCDS(FCDSAccount, 'ID', 'Nama', ['id'], Self); end; procedure TfrmJurnal.LoadData(AID : String); var I: Integer; begin ClearByTag([0,1]); FreeAndNil(FJurnal); cxGridTableJurnal.ClearRows; if AID = '' then Exit; FJurnal := ClientDataModule.ServerJurnalClient.Retrieve(AID); if FJurnal = nil then Exit; if FJurnal.ID = '' then Exit; edNoBukti.Text := FJurnal.NoBukti; edTglBukti.Date := FJurnal.TglBukti; memKeterangan.Lines.Text := FJurnal.Keterangan; for I := 0 to FJurnal.JurnalItems.Count - 1 do begin cxGridTableJurnal.DataController.AppendRecord; cxGridTableJurnal.SetObjectData(FJurnal.JurnalItems[i], i); cxGridTableJurnal.SetValue(i, cxGridColNama.Index, FJurnal.JurnalItems[i].Account.ID); end; end; end.
unit l3IniFile; {$I+} { $Id: l3IniFile.pas,v 1.30 2016/02/26 16:16:12 voba Exp $ } // $Log: l3IniFile.pas,v $ // Revision 1.30 2016/02/26 16:16:12 voba // - лингвомодули можно подключать в инишнике // // Revision 1.29 2014/10/29 15:37:58 voba // no message // // Revision 1.28 2014/10/16 13:44:04 lukyanets // Зануляем возвращаемые значения в случае провала. // // Revision 1.27 2014/10/16 10:41:59 lukyanets // Более контролируемо создаем конфиги // // Revision 1.26 2014/10/08 09:45:42 lukyanets // CLeanup // // Revision 1.25 2013/12/25 11:41:58 lulin // - чистим код. // // Revision 1.24 2013/06/17 15:36:37 voba // - Сделал дефолт. проперти, что бы имя секции задавать в той же строке, типа f_BaseLang.LanguageID:= BaseConfig['Settings'].ReadParamIntDef('Language', -1); // // Revision 1.23 2013/04/17 14:22:51 lulin // - портируем. // // Revision 1.22 2013/04/09 11:08:18 lulin // - пытаемся отладиться под XE. // // Revision 1.21 2013/04/05 12:03:00 lulin // - портируем. // // Revision 1.20 2012/11/01 09:42:57 lulin // - забыл точку с запятой. // // Revision 1.19 2012/11/01 07:45:08 lulin // - делаем возможность логирования процесса загрузки модулей. // // Revision 1.18 2012/04/03 05:37:33 narry // Обновление // // Revision 1.17 2011/05/18 12:09:16 lulin // {RequestLink:266409354}. // // Revision 1.16 2010/09/28 13:06:11 fireton // - Распределяем память для PAnsiChar своими средствами // // Revision 1.15 2010/04/12 13:10:42 voba // - [K:200085802] // // Revision 1.14 2010/02/02 14:09:31 voba // - K:178324176 // // Revision 1.13 2008/10/22 06:15:58 fireton // - bug fix: падение с Range Check Error при подаче пустой строки в NormalizePath // // Revision 1.12 2008/09/15 10:35:29 fireton // - инициализация SattionConfig и ServerConfig // // Revision 1.11 2008/03/03 20:06:08 lulin // - <K>: 85721135. // // Revision 1.10 2007/08/14 19:31:59 lulin // - оптимизируем очистку памяти. // // Revision 1.9 2007/08/14 14:30:13 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.8 2007/03/26 09:29:53 fireton // - bug fix // // Revision 1.7 2007/02/09 14:40:01 voba // - buf fix (Шура чото наменял) // // Revision 1.6 2007/02/08 15:01:38 lulin // - функции работы с форматкой выделены в модуль работы со строками. // // Revision 1.5 2007/02/08 14:37:46 lulin // - cleanup. // // Revision 1.4 2007/02/08 14:27:17 lulin // - cleanup. // // Revision 1.3 2005/03/23 15:26:15 step // new: function NormalizedPath // // Revision 1.2 2005/01/24 11:43:23 lulin // - new behavior: при освобождении заглушки очищаем указатель на нее. // // Revision 1.1 2004/12/23 11:42:16 lulin // - rename unit: User_Cfg -> l3IniFile. // // Revision 1.50 2004/12/23 11:28:36 lulin // - rename unit: vtDateSt -> l3DateSt. // // Revision 1.49 2004/10/06 17:15:13 lulin // - борьба за кошерность. // // Revision 1.48 2004/09/21 15:10:49 fireton // - bug fix: не освобождался fSubstList // // Revision 1.47 2004/09/21 12:56:01 lulin // - Release заменил на Cleanup. // // Revision 1.46 2004/09/14 16:22:26 voba // - убрал Антошины изменения потому что глючит сохранение // // Revision 1.45 2004/09/14 13:47:18 lulin // - г¤ «Ґ­ ¬®¤г«м Str_Man. // // Revision 1.40 2004/05/18 09:28:05 voba // -code clean // // Revision 1.39 2004/05/18 09:02:29 voba // -code clean // // Revision 1.38 2004/03/31 13:48:38 fireton // - добавлены процедуры удаления секции и ключа в ini-файле // // Revision 1.37 2004/03/31 11:48:08 fireton // - оптимизация по скорости ReadStringIni и WriteStringIni // // Revision 1.36 2004/03/30 15:33:23 step // bug fix // // Revision 1.35 2004/03/30 14:23:45 fireton // - процедуры для чтения/записи строк в ini-файл // (ReadStringIni и WriteStringIni) // // Revision 1.34 2004/03/18 14:27:15 fireton // - добавление ImplodeSubsts // // Revision 1.33 2004/02/26 14:55:12 step // изменена TCfgList.ExpandBySubst (условная компиляция) // // Revision 1.32 2004/02/20 09:31:48 step // изменена TCfgList.ExpandBySubst // // Revision 1.31 2004/02/19 15:41:42 step // add: TCfgList.ExpandBySubst // // Revision 1.30 2003/11/12 15:22:58 narry // - new: добавлена возможность записи-чтения TDateTime (форматка T) в составе записи // // Revision 1.29 2003/05/28 15:26:46 voba // -new behavior: при записи рекордов можно указывать в форматке размер целого от 1 до 8 и boolean // // Revision 1.28 2002/12/24 13:02:02 law // - change: объединил Int64_Seek c основной веткой. // // Revision 1.27 2002/12/23 13:02:13 voba // no message // // Revision 1.26.2.1 2002/12/23 13:05:04 law // - объединил с основной веткой (то что Вован забыл положить). // // Revision 1.27 2002/12/23 13:02:13 voba // no message // // Revision 1.26 2002/09/11 15:39:46 voba // no message // // Revision 1.25 2002/06/20 06:28:09 voba // no message // // Revision 1.24 2002/04/09 14:55:03 voba // -improvement : для функции чтения листов можно задать максимальное количество элементов // // Revision 1.23 2002/02/05 15:15:01 voba // -new behavior: use AnsiString in place of shortstring // // Revision 1.22 2002/02/04 10:13:22 narry // - bug fix: неверное восстановление ShortDateFormat после чтения времени // // Revision 1.21 2001/12/25 08:16:50 narry // - bug fix: процедура чтения времени читала дату // // Revision 1.20 2001/10/25 13:51:42 narry // - new behavior: чтение/запись времени // // Revision 1.19 2001/10/02 12:22:58 law // - cleanup. // // Revision 1.18 2001/09/21 09:58:55 law // - cleanup. // // Revision 1.17 2001/08/31 11:38:45 law // - cleanup & comments. // // Revision 1.16 2001/08/31 11:02:36 law // - rename unit: MyUtil -> l3FileUtils. // // Revision 1.15 2001/07/30 15:50:29 narry // -bug fix: процедура ReadSectionValues возвращала пару Key=Value // // Revision 1.14 2001/05/18 12:42:21 law // - change: изменен предок TObject -> _Tl3Base. // // Revision 1.13 2001/05/18 06:07:35 voba // -bug fix // // Revision 1.12 2001/02/20 13:23:14 voba // no message // // Revision 1.11 2000/12/15 15:36:28 law // - вставлены директивы Log. {$I l3Define.inc } interface uses SysUtils, Classes, Forms, l3Base, l3ProtoObject ; const CfgExt = '.INI'; StrSize = 1024; YesStr = 'YES'; NoStr = 'NO'; OnStr = 'ON'; OffStr = 'OFF'; TrueStr = 'TRUE'; FalseStr = 'FALSE'; OneStr = '1'; ZeroStr = '0'; type {$IfNDef Win32} ShortString = AnsiString; PShortString = PAnsiString; {$EndIf} PBoolean = ^Boolean; TCfgString = AnsiString; type TOnGetListItem = function(var ItStr: ShortString): Boolean; {* - Подитеративная функция для WriteParamExtList} function MakeWGLStub(Action: Pointer): TOnGetListItem; procedure FreeWGLStub(var Action: TOnGetListItem); type TOnSetListItem = procedure(const ItStr: ShortString); {* - Подитеративная функция для ReadParamExtList} function MakeRGLStub(Action: Pointer): TOnSetListItem; procedure FreeRGLStub(var Action: TOnSetListItem); type TOnWriteArrayItem = function(var aValue: Integer): Boolean; {* - Подитеративная функция для записи элементов массива. Если возвращает true - элемент последний. } function MakeWAIStub(Action: Pointer): TOnWriteArrayItem; procedure FreeWAIStub(var Action: TOnWriteArrayItem); type TOnReadArrayItem = procedure(aValue: Integer); {* - Подитеративная функция для записи элементов массива.} function MakeRAIStub(Action: Pointer): TOnReadArrayItem; procedure FreeRAIStub(var Action: TOnReadArrayItem); type TCfgList = class(Tl3ProtoObject) private FSection : AnsiString; FCfgFileName : PAnsiChar; {internal} tmpPChar: PAnsiChar; fSubstList: TStringList; protected procedure Cleanup; override; {-} procedure ExpandBySubst(var aStr: AnsiString); function GetSectionDefinition(const aSection : ShortString) : TCfgList; public constructor Create(CfgName: TFileName = ''); reintroduce; class function CorrectCfgFileName(const aName: TFileName): TFileName; procedure SetCfgFile(const Value: TFileName); function GetCfgFile: TFileName; function GetSubstList: TStringList; procedure AddSubst(const aID: AnsiString; const aValue: AnsiString); procedure InitSubsts(const aSubstsSection: AnsiString); function ReadParamString(const ID: ShortString; var aStr: AnsiString): Boolean; function ReadParamFileName(const ID: ShortString; var aStr: TFileName): Boolean; function ReadParamStr(const ID: ShortString; var aStr: ShortString): Boolean; deprecated; function ReadParamDate(const ID: ShortString; var aDate: TDateTime): Boolean; function ReadParamTime(const ID: ShortString; var aTime: TDateTime): Boolean; function ReadParamDateTime(const ID: ShortString; var aDateTime: TDateTime): Boolean; function ReadParamInt(const ID: ShortString; var aInt: Longint): Boolean; function ReadParamBool(const ID: ShortString; var aBool: Boolean): Boolean; function ReadParamStrDef(const ID: ShortString; const DefStr: AnsiString): AnsiString; function ReadParamFileNameDef(const ID: ShortString; const aDefStr: TFileName): TFileName; function ReadParamDateDef(const ID: ShortString; DefDate: TDateTime): TDateTime; function ReadParamTimeDef(const ID: ShortString; DefTime: TDateTime): TDateTime; function ReadParamDateTimeDef(const ID: ShortString; DefDateTime: TDateTime): TDateTime; function ReadParamIntDef(const ID: ShortString; DefInt: Longint): Longint; function ReadParamBoolDef(const ID: ShortString; DefBool: Boolean): Boolean; procedure ReadParamList(const ID: ShortString; StrList: TStrings; aMaxItems: Integer = High(Integer)); procedure ReadParamRec(const ID: ShortString; const FormStr: ShortString; var Rec); procedure ReadParamData(const ID: ShortString; Data: PAnsiChar; DataSize: Integer); procedure ReadParamExtList(const ID: ShortString; SetListFunc: TOnSetListItem); procedure ReadParamArrayF(const ID: ShortString; aSetItemFunc: TOnReadArrayItem); procedure ReadFormPlace(const ID: ShortString; aForm: TForm); function WriteParamStr(const ID: ShortString; const aStr: AnsiString): Boolean; function WriteParamDate(const ID: ShortString; aDate: TDateTime): Boolean; function WriteParamTime(const ID: ShortString; aTime: TDateTime): Boolean; function WriteParamDateTime(const ID: ShortString; aDateTime: TDateTime): Boolean; function WriteParamInt(const ID: ShortString; aInt: Longint): Boolean; function WriteParamBool(const ID: ShortString; aBool: Boolean): Boolean; function WriteParamList(const ID: ShortString; StrList: TStrings; aMaxItems: Integer = High(Integer)): Boolean; function WriteParamRec(const ID: ShortString; const FormStr: ShortString; var Rec): Boolean; function WriteParamData(const ID: ShortString; Data: PAnsiChar; DataSize: Integer): Boolean; function WriteParamExtList(const ID: ShortString; GetListFunc: TOnGetListItem): Boolean; procedure WriteParamArrayF(const ID: ShortString; aGetItemFunc: TOnWriteArrayItem); function WriteFormPlace(const ID: ShortString; aForm: TForm): Boolean; function WriteExpression(const aStr: ShortString): Boolean; procedure SetSection(const Value: ShortString); function GetSection: ShortString; procedure DeleteSection(const Value: ShortString); procedure GetSectionNameList(SectionList: TStrings); procedure ReadSection(Strings: TStrings); procedure ReadSectionValues(Strings: TStrings); procedure InflateSubst(var aStr: AnsiString); property SectionDefinition[const aSection : ShortString] : TCfgList read GetSectionDefinition; default; property Section: ShortString Read GetSection Write SetSection; property CfgFileName: TFileName Read GetCfgFile Write SetCfgFile; property SubstList: TStringList Read GetSubstList; end; Tl3IniFile = class(TCfgList) end; EcfgError = class(Exception); EcfgReadError = class(EcfgError); EcfgConvertError = class(EcfgError); function UserConfig: TCfgList; //inline; function StationConfig: TCfgList; //inline; function ServerConfig: TCfgList; //inline; procedure InitStationAndServerConfig(aIniPath: AnsiString = ''); procedure InitConfigs; procedure InitUserConfig(aIniPath: AnsiString = ''); procedure InitStationConfig(aIniPath: AnsiString = ''); procedure DoneConfigs; procedure DoneUserConfig; procedure WriteStringIni(const IniFN: AnsiString; const Section, Key, Value: AnsiString); function ReadStringIni(const IniFN: AnsiString; const Section, Key: AnsiString): AnsiString; procedure DeleteIniSection(const IniFN: AnsiString; const Section: AnsiString); procedure DeleteIniKey(const IniFN: AnsiString; const Section, Key: AnsiString); function NormalizedPath(const aPath: AnsiString): AnsiString; // удаляет лишние символы '\' implementation uses Windows, StrUtils, l3Stream, l3DateSt, l3MinMax, l3String, l3FileUtils, l3Types; resourcestring rsReadError = 'Ошибка чтения '; const RecSplitChar = '~'; c_SubstBracket = '%'; var g_UserConfig : TCfgList = Nil; g_StationConfig : TCfgList = Nil; g_ServerConfig : TCfgList = Nil; function MakeWAIStub(Action: Pointer): TOnWriteArrayItem; register; asm jmp l3LocalStub end;{asm} procedure FreeWAIStub(var Action: TOnWriteArrayItem); register; asm jmp l3FreeLocalStub end;{asm} function MakeRAIStub(Action: Pointer): TOnReadArrayItem; register; asm jmp l3LocalStub end;{asm} procedure FreeRAIStub(var Action: TOnReadArrayItem); register; asm jmp l3FreeLocalStub end;{asm} function MakeWGLStub(Action: Pointer): TOnGetListItem; register; asm jmp l3LocalStub end;{asm} procedure FreeWGLStub(var Action: TOnGetListItem); register; asm jmp l3FreeLocalStub end;{asm} function MakeRGLStub(Action: Pointer): TOnSetListItem; register; asm jmp l3LocalStub end;{asm} procedure FreeRGLStub(var Action: TOnSetListItem); register; asm jmp l3FreeLocalStub end;{asm} function DataToFormatString(Data: PAnsiChar; DataSize: Integer): AnsiString; var lDataLong : Longint; lDataOffset : Integer; begin {Попытаемся сократить DataSize, чтобы не писать лишних нулей в конце} lDataOffset := (Pred(DataSize) div 4) * 4; repeat lDataLong := 0; StrMove( @lDataLong, Data + lDataOffset, Min(4, DataSize - lDataOffset)); if (lDataLong <> 0) or (lDataOffset = 0) then Break; Dec(lDataOffset, 4); until False; DataSize := Min(DataSize, lDataOffset + 4); lDataOffset := 0; Result := ''; while lDataOffset < DataSize do begin lDataLong := 0; StrMove( @lDataLong, Data + lDataOffset, Min(4, DataSize - lDataOffset)); Result := Result + IntToStr(lDataLong) + RecSplitChar; Inc(lDataOffset, 4); end; end; procedure FormatStringToData(const FStr: AnsiString; aIterFunc: TOnReadArrayItem); var lDataLong : Longint; lStrOffset, lStrOffset2 : Integer; lStrSize : Integer; lStr : String[20]; begin lStrSize := Length(FStr); lStrOffset := 1; while (lStrOffset < lStrSize) do begin lStrOffset2 := l3StringPos(RecSplitChar, FStr, lStrOffset); if lStrOffset2 = 0 then lStrOffset2 := Succ(lStrSize); lStr[0] := AnsiChar(lStrOffset2 - lStrOffset); l3Move(FStr[lStrOffset], lStr[1], lStrOffset2 - lStrOffset); try lDataLong := StrToInt(lStr); except raise EcfgConvertError.Create('Невозможно преобразовать в число : ' + lStr); end; lStrOffset := Succ(lStrOffset2); aIterFunc(lDataLong); end; end; constructor TCfgList.Create(CfgName: TFileName); begin inherited Create; SetCfgFile(CfgName); tmpPChar := l3StrAlloc(StrSize); end; procedure TCfgList.Cleanup; begin WritePrivateProfileStringA(nil, nil, nil, fCfgFileName); FSection := ''; if Assigned(FCfgFileName) then l3StrDispose(fCfgFileName); if Assigned(tmpPChar) then l3StrDispose(tmpPChar); if Assigned(fSubstList) then FreeAndNil(fSubstList); inherited; end; procedure TCfgList.ExpandBySubst(var aStr: AnsiString); var l_StartBracket, l_EndBracket : Integer; l_SubstName : AnsiString; l_SubstIndex : Integer; begin if Assigned(fSubstList) and (fSubstList.Count > 0) then begin l_EndBracket := 0; repeat l_StartBracket := PosEx(c_SubstBracket, aStr, l_EndBracket + 1); if (l_StartBracket > 0) then // нашли первую "скобку" begin l_EndBracket := PosEx(c_SubstBracket, aStr, l_StartBracket + 1); if (l_EndBracket > 0) then // нашли вторую "скобку" begin if (l_EndBracket - l_StartBracket > 1) then // между первой и второй "скобками" что-то есть begin l_SubstName := Copy(aStr, l_StartBracket + 1, l_EndBracket - l_StartBracket - 1); l_SubstIndex := SubstList.IndexOfName(l_SubstName); if l_SubstIndex > -1 then // есть на что заменить begin Delete(aStr, l_StartBracket, l_EndBracket - l_StartBracket + 1); {$IFDEF Delphi7} Insert(SubstList.ValueFromIndex[l_SubstIndex], aStr, l_StartBracket); {$ELSE} Insert(SubstList.Values[l_SubstName], aStr, l_StartBracket); {$ENDIF} l_EndBracket := l_StartBracket; // позиция второй "скобки" после замены стала не актуальна end; end; end; end; until (l_StartBracket = 0) or (l_EndBracket = 0); end; end; procedure TCfgList.SetCfgFile(const Value: TFileName); var l_Name: TFileName; begin l_Name := CorrectCfgFileName(Value); // if not (FileExists(l_Name)) then // MakeFile(l_Name); if Assigned(FCfgFileName) then l3StrDispose(FCfgFileName); FCfgFileName := l3StrAlloc(Length(l_Name) + 1); StrPCopy(FCfgFileName, l_Name); FileClose(FileOpen(l3GetStrPas(FCfgFileName), fmShareExclusive and fmOpenReadWrite)); end; function TCfgList.GetCfgFile: TFileName; begin Result := l3GetStrPas(FCfgFileName); end; function TCfgList.GetSubstList: TStringList; begin if fSubstList = nil then fSubstList := TStringList.Create; Result := fSubstList; end; procedure TCfgList.AddSubst(const aID: AnsiString; const aValue: AnsiString); var I : Integer; begin with SubstList do begin I := IndexOfName(aID); if I = -1 then Add(aID + '=' + aValue) else Values[aID] := AValue; end; end; procedure TCfgList.InitSubsts(const aSubstsSection: AnsiString); const c_BufSize = 8192; var l_MemoryStream : TMemoryStream; l_MemSize : Cardinal; l_BufferIsSmall : Boolean; I : Integer; begin l_MemoryStream := TMemoryStream.Create; try l_MemSize := c_BufSize; repeat l_MemoryStream.SetSize(l_MemSize); l_BufferIsSmall := GetPrivateProfileSectionA(PAnsiChar(aSubstsSection), l_MemoryStream.Memory, l_MemSize, FCfgFileName) = l_MemSize - 2; l_MemSize := l_MemSize * 2; until not l_BufferIsSmall; // замена #0 на #13 for I := 0 to l_MemoryStream.Size - 2 do if (PAnsiChar(l_MemoryStream.Memory) + I)^ = #0 then begin (PAnsiChar(l_MemoryStream.Memory) + I)^ := #13; if (PAnsiChar(l_MemoryStream.Memory) + I + 1)^ = #0 then Break; end; SubstList.Clear; SubstList.LoadFromStream(l_MemoryStream); finally l_MemoryStream.Free; end; end; procedure TCfgList.SetSection(const Value: ShortString); begin FSection := AnsiUpperCase(Value); end; function TCfgList.GetSection: ShortString; begin Result := FSection; end; function TCfgList.GetSectionDefinition(const aSection : ShortString) : TCfgList; begin Section := aSection; Result := Self; end; procedure TCfgList.GetSectionNameList(SectionList: TStrings); var FF : Text; SS : ShortString; R : Byte; begin AssignFile(FF, FCfgFileName); try Reset(FF); except Exit; end; while not EOF(FF) do begin ReadLn(FF, SS); R := Pos(']', SS); if R > 0 then begin SS := TrimLeft(Copy(SS, 1, R - 1)); if (SS[0] = #0) or (SS[1] <> '[') then Continue; SectionList.Add(Copy(SS, 2, Byte(SS[0]) - 1)); end; end; Close(FF); end; procedure TCfgList.ReadSection(Strings: TStrings); const BufSize = 8192; var Buffer, P : PAnsiChar; Count : Integer; begin l3System.GetLocalMem(Buffer, BufSize); try Count := GetPrivateProfileStringA(PAnsiChar(FSection), nil, nil, Buffer, BufSize, FCfgFileName); P := Buffer; if Count > 0 then while P[0] <> #0 do begin Strings.Add(l3GetStrPas(P)); Inc(P, StrLen(P) + 1); end; finally l3System.FreeLocalMem(Buffer); end; end; procedure TCfgList.ReadSectionValues(Strings: TStrings); var KeyList : TStringList; I : Integer; begin KeyList := TStringList.Create; try ReadSection(KeyList); for I := 0 to Keylist.Count - 1 do //Strings.Values[KeyList[I]] := ReadParamStrDef(KeyList[I], ''); Strings.Add(ReadParamStrDef(KeyList[I], '')); finally KeyList.Free; end; end; procedure TCfgList.ReadParamList(const ID: ShortString; StrList: TStrings; aMaxItems: Integer = High(Integer)); var I : Integer; St : AnsiString; begin I := 1; repeat St := ID + IntToStr(I); if ReadParamString(St, St) then StrList.Add(St) else Break; Inc(I); until I > aMaxItems; end; function TCfgList.WriteParamList(const ID: ShortString; StrList: TStrings; aMaxItems: Integer = High(Integer)): Boolean; var I : Integer; St : ShortString; begin WritePrivateProfileStringA(PAnsiChar(FSection), nil, nil, FCfgFileName); {Delete Current Section} Result := False; aMaxItems := Min(aMaxItems, StrList.Count); for I := 1 to aMaxItems do begin St := ID + IntToStr(I); Result := WriteParamStr(St, StrList[Pred(I)]); end; end; procedure TCfgList.ReadParamExtList(const ID: ShortString; SetListFunc: TOnSetListItem); var I : Integer; St : ShortString; begin I := 1; repeat St := ID + IntToStr(I); if ReadParamStr(St, St) then SetListFunc(St) else Break; Inc(I); until False; end; function TCfgList.WriteParamExtList(const ID: ShortString; GetListFunc: TOnGetListItem): Boolean; var I : Integer; StID, St : ShortString; begin WritePrivateProfileStringA(PAnsiChar(FSection), nil, nil, FCfgFileName); {Delete Current Section} I := 1; Result := False; while GetListFunc(St) do begin StID := ID + IntToStr(I); Result := WriteParamStr(StID, St); Inc(I); end; end; procedure TCfgList.ReadParamArrayF(const ID: ShortString; aSetItemFunc: TOnReadArrayItem); var lStr : AnsiString; begin try try if ReadParamString(ID, lStr) then FormatStringToData(lStr, aSetItemFunc); except raise EcfgReadError.Create(rsReadError + ID); end; finally FreeRAIStub(aSetItemFunc); end; end; procedure TCfgList.WriteParamArrayF(const ID: ShortString; aGetItemFunc: TOnWriteArrayItem); var lValue : Integer; lStr : AnsiString; begin try lStr := ''; while not aGetItemFunc(lValue) do lStr := lStr + IntToStr(lValue) + RecSplitChar; WriteParamStr(ID, lStr); finally FreeWAIStub(aGetItemFunc); end; end; type TFormPlaceRec = record rLeft : Integer; rTop : Integer; rWidth : Integer; rHeight : Integer; rMaximize : Integer; end; procedure TCfgList.ReadFormPlace(const ID: ShortString; aForm: TForm); var lFormPlaceRec : TFormPlaceRec; begin try ReadParamRec(ID, 'DDDDD', lFormPlaceRec); with aForm, lFormPlaceRec do begin Position := poDesigned; SetBounds(rLeft, rTop, rWidth, rHeight); if rMaximize > 0 then WindowState := wsMaximized else WindowState := wsNormal; end; except end; end; function TCfgList.WriteFormPlace(const ID: ShortString; aForm : TForm): Boolean; var lFormPlaceRec : TFormPlaceRec; begin with aForm, lFormPlaceRec do begin rLeft := Left; rTop := Top; rWidth := Width; rHeight := Height; if WindowState = wsMaximized then rMaximize := 1 else rMaximize := 0; end; Result := WriteParamRec(ID, 'DDDDD', lFormPlaceRec); end; procedure TCfgList.DeleteSection(const Value: ShortString); begin if Section <> '' then Section := Value; WritePrivateProfileStringA(PAnsiChar(FSection), nil, nil, FCfgFileName) end; function TCfgList.ReadParamStr(const ID: ShortString; var aStr: ShortString): Boolean; var lStr : AnsiString; begin Result := ReadParamString(ID, lStr); aStr := lStr; end; function TCfgList.ReadParamString(const ID: ShortString; var aStr: AnsiString): Boolean; const emptyPChar: PAnsiChar = #0; var l_ID : AnsiString; begin l_ID := ID + #0; Result := False; aStr := ''; if (FSection <> '') then begin GetPrivateProfileStringA(PAnsiChar(FSection), @l_ID[1], EmptyPChar, tmpPChar, StrSize, FCfgFileName); if TmpPChar[0] <> #0 then begin aStr := l3GetStrPas(TmpPChar); ExpandBySubst(aStr); {AStr:=ConvFromReadable(aStr);} Result := True; end; end; end; function TCfgList.ReadParamFileName(const ID: ShortString; var aStr: TFileName): Boolean; var l_S : AnsiString; begin l_S := aStr; Result := ReadParamString(ID, l_S); aStr := l_S; // not realized //If (Length(aStr) > 0) and (aStr[1] = '%') then //%IniPath% //begin // ExtractFilePath(ExpandFileName(AnsiString(fCfgFileName))); // aStr := ExtractFilePath(ExpandFileName(AnsiString(fCfgFileName))) + Copy(aStr, 11, Length(aStr)); //end; end; function TCfgList.ReadParamInt(const ID: ShortString; var aInt: Longint): Boolean; var tmpStr : AnsiString; l_ID : AnsiString; begin l_ID := ID + #0; aInt := 0; Result := False; if (FSection <> '') then begin if ReadParamString(l_ID, tmpStr) then begin try aInt := StrToInt(tmpStr); Result := True; except Result := False; end; end; end; end; function TCfgList.ReadParamBool(const ID: ShortString; var aBool: Boolean): Boolean; var TmpStr : TCfgString; l_ID : AnsiString; begin Result := False; aBool := False; l_ID := ID + #0; if (FSection <> '') then begin if ReadParamString(l_ID, tmpStr) then begin TmpStr := AnsiUpperCase(TmpStr); if (TmpStr = YesStr) or (TmpStr = OnStr) or (TmpStr = OneStr) or (TmpStr = TrueStr) then begin aBool := True; Result := True; end else begin if (TmpStr = NoStr) or (TmpStr = OffStr) or (TmpStr = ZeroStr) or (TmpStr = FalseStr) then begin aBool := False; Result := True; end; end; end; end; end; function TCfgList.ReadParamDate(const ID: ShortString; var aDate: TDateTime): Boolean; var lSaveShortDateFormat : AnsiString; tmpStr : AnsiString; begin Result := ReadParamString(ID, tmpStr); aDate := 0; if Result then try lSaveShortDateFormat := {$IfDef XE}FormatSettings.{$EndIf}ShortDateFormat; {$IfDef XE}FormatSettings.{$EndIf}ShortDateFormat := 'd/m/y'; try aDate := StrToDate(NormalizeDate(tmpStr)); finally {$IfDef XE}FormatSettings.{$EndIf}ShortDateFormat := lSaveShortDateFormat; end; except Result := False; end; end; function TCfgList.ReadParamDateDef(const ID: ShortString; DefDate: TDateTime): TDateTime; begin if not ReadParamDate(ID, Result) then Result := DefDate; end; function TCfgList.WriteParamDate(const ID: ShortString; aDate: TDateTime): Boolean; begin try Result := WriteParamStr(ID, FormatDateTime('dd/mm/yyyy', aDate)); except Result := False; end; end; function TCfgList.ReadParamDateTime(const ID: ShortString; var aDateTime: TDateTime): Boolean; var lSaveShortDateFormat, lSaveShortTimeFormat : AnsiString; tmpStr : ShortString; begin Result := ReadParamStr(ID, tmpStr); aDateTime := 0; if Result then try lSaveShortDateFormat := {$IfDef XE}FormatSettings.{$EndIf}ShortDateFormat; lSaveShortTimeFormat := {$IfDef XE}FormatSettings.{$EndIf}ShortTimeFormat; {$IfDef XE}FormatSettings.{$EndIf}ShortDateFormat := 'd/m/y'; {$IfDef XE}FormatSettings.{$EndIf}ShortTimeFormat := 'h:n:s'; try aDateTime := StrToDateTime(tmpStr); finally {$IfDef XE}FormatSettings.{$EndIf}ShortDateFormat := lSaveShortDateFormat; {$IfDef XE}FormatSettings.{$EndIf}ShortTimeFormat := lSaveShortTimeFormat; end; except Result := False; end; end; function TCfgList.ReadParamDateTimeDef(const ID: ShortString; DefDateTime: TDateTime): TDateTime; begin if not ReadParamDateTime(ID, Result) then Result := DefDateTime; end; function TCfgList.WriteParamDateTime(const ID: ShortString; aDateTime: TDateTime): Boolean; begin try Result := WriteParamStr(ID, FormatDateTime('dd/mm/yyyy hh:nn:ss', aDateTime)); except Result := False; end; end; function TCfgList.ReadParamTime(const ID: ShortString; var aTime: TDateTime): Boolean; var lSaveShortTimeFormat : AnsiString; tmpStr : ShortString; begin Result := ReadParamStr(ID, tmpStr); aTime := 0; if Result then try lSaveShortTimeFormat := {$IfDef XE}FormatSettings.{$EndIf}ShortTimeFormat; {$IfDef XE}FormatSettings.{$EndIf}ShortTimeFormat := 'h:n:s'; try aTime := StrToTime({NormalizeDate}(tmpStr)); finally {$IfDef XE}FormatSettings.{$EndIf}ShortTimeFormat := lSaveShortTimeFormat; end; except Result := False; end; end; function TCfgList.ReadParamTimeDef(const ID: ShortString; DefTime: TDateTime): TDateTime; begin if not ReadParamTime(ID, Result) then Result := DefTime; end; function TCfgList.WriteParamTime(const ID: ShortString; aTime: TDateTime): Boolean; begin try Result := WriteParamStr(ID, FormatDateTime('hh:nn:ss', aTime)); except Result := False; end; end; function TCfgList.ReadParamStrDef(const ID: ShortString; const DefStr: AnsiString): AnsiString; begin if not ReadParamString(ID, Result) then Result := DefStr; end; function TCfgList.ReadParamFileNameDef(const ID: ShortString; const aDefStr: TFileName): TFileName; begin if not ReadParamFileName(ID, Result) then Result := aDefStr; end; function TCfgList.ReadParamIntDef(const ID: ShortString; DefInt: Longint): Longint; begin if not ReadParamInt(ID, Result) then Result := DefInt; end; function TCfgList.ReadParamBoolDef(const ID: ShortString; DefBool: Boolean): Boolean; begin if not ReadParamBool(ID, Result) then Result := DefBool; end; function TCfgList.WriteParamData(const ID: ShortString; Data: PAnsiChar; DataSize: Integer): Boolean; var lStr : AnsiString; begin lStr := DataToFormatString(Data, DataSize); Result := WriteParamStr(ID, lStr); end; procedure TCfgList.ReadParamData(const ID: ShortString; Data: PAnsiChar; DataSize: Integer); var lStr : AnsiString; lDataOffset : Integer; lIterFunc : TOnReadArrayItem; procedure IterFunc(aValue: Integer); begin if (lDataOffset >= DataSize) then exit; StrMove(Data + lDataOffset, @aValue, Min(4, DataSize - lDataOffset)); Inc(lDataOffset, 4); end; begin try if not ReadParamString(ID, lStr) then raise EcfgReadError.Create(''); lDataOffset := 0; l3FillChar(Data^, DataSize, 0); lIterFunc := MakeRAIStub(@IterFunc); try FormatStringToData(lStr, lIterFunc); finally FreeRAIStub(lIterFunc); end; except raise EcfgReadError.Create(rsReadError + ID); end; end; procedure TCfgList.ReadParamRec(const ID: ShortString; const FormStr: ShortString; var Rec); var RStr : AnsiString; begin try if not ReadParamString(ID, RStr) then raise EcfgReadError.Create(''); l3FormatStringToRec(RStr, Rec, FormStr); except raise EcfgReadError.Create(rsReadError + ID); end;//try..except end; function TCfgList.WriteParamRec(const ID: ShortString; const FormStr: ShortString; var Rec): Boolean; var ResStr : AnsiString; begin ResStr := l3RecToFormatString(Rec, FormStr); Result := WriteParamStr(ID, ResStr); end; function TCfgList.WriteExpression(const aStr: ShortString): Boolean; var I : Byte; ID : ShortString; begin I := Pos('=', AStr); if I = 0 then begin Result := False; Exit; end; ID := Trim(Copy(AStr, 1, I - 1)) + #0; Result := WritePrivateProfileStringA(PAnsiChar(FSection), @ID[1], PAnsiChar(Trim(Copy(AStr, I + 1, 255)) + #0), FCfgFileName); end; function TCfgList.WriteParamStr(const ID: ShortString; const aStr: AnsiString): Boolean; var STmp : AnsiString; l_ID : AnsiString; begin l_ID := ID + #0; STmp := aStr; STmp := STmp + #0; Result := WritePrivateProfileStringA(PAnsiChar(FSection), @l_ID[1], @STmp[1], FCfgFileName); end; function TCfgList.WriteParamInt(const ID: ShortString; aInt: Longint): Boolean; var AStr : ShortString; l_ID : AnsiString; begin l_ID := ID + #0; aStr := IntToStr(aInt) + #0; Result := WritePrivateProfileStringA(PAnsiChar(FSection), @l_ID[1], @aStr[1], FCfgFileName); end; function TCfgList.WriteParamBool(const ID: ShortString; aBool: Boolean): Boolean; var tmpStr : String[6]; l_ID : AnsiString; begin l_ID := ID + #0; if ABool then tmpStr := OneStr + #0 else tmpStr := ZeroStr + #0; Result := WritePrivateProfileStringA(PAnsiChar(FSection), @l_ID[1], @tmpStr[1], FCfgFileName) end; procedure TCfgList.InflateSubst(var aStr: AnsiString); var X : Integer; I : Integer; Substr : AnsiString; begin for I := 0 to Pred(fSubstList.Count) do begin {$IFDEF Delphi7} Substr := fSubstList.ValueFromIndex[I]; {$ELSE} Substr := fSubstList.Values[fSubstList.Names[I]]; {$ENDIF} X := PosEx(Substr, aStr, 1); if X > 0 then begin Delete(aStr, X, Length(Substr)); Insert(c_SubstBracket + fSubstList.Names[I] + c_SubstBracket, aStr, X); break; end; end; end; procedure InitConfigs; begin InitUserConfig; InitStationConfig; end; procedure InitUserConfig(aIniPath: AnsiString = ''); begin if UserConfig = Nil then g_UserConfig := TCfgList.Create(aIniPath) else Assert(SameText(UserConfig.CfgFileName, UserConfig.CorrectCfgFileName(aIniPath))); end; procedure InitStationConfig(aIniPath: AnsiString = ''); begin if StationConfig = Nil then g_StationConfig := TCfgList.Create(aIniPath) else Assert(SameText(StationConfig.CfgFileName, StationConfig.CorrectCfgFileName(aIniPath))); end; procedure DoneUserConfig; begin l3Free(g_UserConfig); end; procedure DoneConfigs; begin DoneUserConfig; l3Free(g_StationConfig); l3Free(g_ServerConfig); end; function ExtractSection(S: AnsiString): AnsiString; var STmp : AnsiString; begin STmp := Trim(S); if (STmp <> '') and (STmp[1] = '[') and (STmp[Length(STmp)] = ']') then Result := UpperCase(Copy(STmp, 2, Length(STmp) - 2)) else Result := ''; end; function IsComment(S: AnsiString): Boolean; var I : Integer; begin Result := S = ''; if not Result then begin I := 1; while (I <= Length(S)) and (S[I] in [' ', #9]) do Inc(I); if I <= Length(S) then Result := S[I] = ';'; end; end; procedure WriteStringIni(const IniFN: AnsiString; const Section, Key, Value: AnsiString); var lSectionFound : Boolean; lKey : AnsiString; I, X : Integer; STmp, lUpSect, lUpKey : AnsiString; Stream : TFileStream; List : TStringList; begin if FileExists(IniFN) then begin List := TStringList.Create; Stream := TFileStream.Create(IniFN, fmOpenReadWrite or fmShareDenyWrite); try List.LoadFromStream(Stream); I := 0; lUpSect := UpperCase(Section); // ищем секцию lSectionFound := False; while not ((I >= List.Count) or lSectionFound) do begin STmp := List[I]; Inc(I); if not IsComment(STmp) then if ExtractSection(STmp) = lUpSect then lSectionFound := True; end; // ищем ключ lUpKey := UpperCase(Key); while I < List.Count do begin STmp := List[I]; Inc(I); if not IsComment(STmp) then begin if ExtractSection(STmp) <> '' then // нашли следующую секцию - значит, ключ не найден begin List.Insert(I - 1, Key + '=' + Value); Break; end; X := Pos('=', STmp); if X > 0 then begin lKey := Trim(Copy(STmp, 1, X - 1)); if UpperCase(lKey) = lUpKey then // ключ найден! begin List[I - 1] := lKey + '=' + Value; Break; end; end; end; end; if not lSectionFound then begin List.Append('[' + Section + ']'); List.Append(Key + '=' + Value); end; finally if List.Count > 0 then begin Stream.Seek(0, soBeginning); List.SaveToStream(Stream); Stream.Size := Stream.Position; // чтобы установить конец файла end; l3Free(Stream); l3Free(List); end; end else // если это новый инишник... begin List := TStringList.Create; try List.Append('[' + Section + ']'); List.Append(Key + '=' + Value); finally List.SaveToFile(IniFN); l3Free(List); end; end; end; function ReadStringIni(const IniFN: AnsiString; const Section, Key: AnsiString): AnsiString; var I : Integer; lKey : AnsiString; X : Integer; STmp, lUpSect, lUpKey : AnsiString; List : TStringList; begin Result := ''; if not FileExists(IniFN) then Exit; List := TStringList.Create; try List.LoadFromFile(IniFN); I := 0; lUpSect := UpperCase(Section); // ищем секцию while I < List.Count do begin STmp := List[I]; Inc(I); if IsComment(STmp) then Continue; if ExtractSection(STmp) = lUpSect then Break; end; // ищем ключ lUpKey := UpperCase(Key); while I < List.Count do begin STmp := List[I]; Inc(I); if IsComment(STmp) then Continue; if ExtractSection(STmp) <> '' then // нашли следующую секцию - значит, ключ не найден Break; X := Pos('=', STmp); if X > 0 then begin lKey := UpperCase(Trim(Copy(STmp, 1, X - 1))); if lKey = lUpKey then // ключ найден! begin Result := Trim(Copy(STmp, X + 1, MaxInt)); Break; end; end; end; finally l3Free(List); end; end; procedure DeleteIniSection(const IniFN: AnsiString; const Section: AnsiString); var STmp : AnsiString; I : Integer; lSectionFound : Boolean; Stream : TFileStream; List : TStringList; lUpSect : AnsiString; begin if FileExists(IniFN) then begin List := TStringList.Create; Stream := TFileStream.Create(IniFN, fmOpenReadWrite or fmShareDenyWrite); try List.LoadFromStream(Stream); I := 0; lUpSect := UpperCase(Section); // ищем секцию lSectionFound := False; while not ((I >= List.Count) or lSectionFound) do begin STmp := List[I]; Inc(I); if not IsComment(STmp) then if ExtractSection(STmp) = lUpSect then lSectionFound := True; end; if lSectionFound then begin lSectionFound := False; Dec(I); List.Delete(I); while not ((I >= List.Count) or lSectionFound) do begin STmp := List[I]; if ExtractSection(STmp) <> '' then lSectionFound := True else List.Delete(I); end; end; finally Stream.Seek(0, soBeginning); List.SaveToStream(Stream); Stream.Size := Stream.Position; // чтобы установить конец файла l3Free(Stream); l3Free(List); end; end; end; procedure DeleteIniKey(const IniFN: AnsiString; const Section, Key: AnsiString); var lKeyFound : Boolean; lSectionFound : Boolean; lKey : AnsiString; I, X : Integer; STmp, lUpSect, lUpKey : AnsiString; Stream : TFileStream; List : TStringList; begin if FileExists(IniFN) then begin List := TStringList.Create; lKeyFound := False; Stream := TFileStream.Create(IniFN, fmOpenReadWrite or fmShareDenyWrite); try List.LoadFromStream(Stream); I := 0; lUpSect := UpperCase(Section); // ищем секцию lSectionFound := False; while not ((I >= List.Count) or lSectionFound) do begin STmp := List[I]; Inc(I); if not IsComment(STmp) then if ExtractSection(STmp) = lUpSect then lSectionFound := True; end; // ищем ключ lUpKey := UpperCase(Key); while I < List.Count do begin STmp := List[I]; Inc(I); if not IsComment(STmp) then begin if ExtractSection(STmp) <> '' then // нашли следующую секцию - значит, ключ не найден Break; X := Pos('=', STmp); if X > 0 then begin lKey := Trim(Copy(STmp, 1, X - 1)); if UpperCase(lKey) = lUpKey then // ключ найден! begin List.Delete(I - 1); lKeyFound := True; Break; end; end; end; end; finally if lKeyFound then // иначе, нафига его записывать? begin Stream.Seek(0, soBeginning); List.SaveToStream(Stream); Stream.Size := Stream.Position; // чтобы установить конец файла end; l3Free(Stream); l3Free(List); end; end; end; function NormalizedPath(const aPath: AnsiString): AnsiString; const c_BackSlash = '\'; var l_Str: AnsiString; begin if aPath = '' then begin Result := ''; Exit; end; // Замена всех '/' --> '\' l_Str := AnsiReplaceStr(Trim(aPath), '/', c_BackSlash); // Замена всех '\\' --> '\' (кроме первой пары) if (l_Str[1] = c_BackSlash) and (l_Str[2] = c_BackSlash) then Result := c_BackSlash + AnsiReplaceStr(l_Str, '\\', c_BackSlash) else Result := AnsiReplaceStr(l_Str, '\\', c_BackSlash); end; procedure InitStationAndServerConfig(aIniPath: AnsiString = ''); var l_ServerCfgPath: AnsiString; begin if g_StationConfig = nil then g_StationConfig:=TCfgList.Create(aIniPath) else Assert(SameText(g_StationConfig.CfgFileName, g_StationConfig.CorrectCfgFileName(aIniPath))); if g_ServerConfig = nil then begin StationConfig.Section := 'ServerConfig'; l_ServerCfgPath := StationConfig.ReadParamStrDef('ServerConfigINI',''); if Length(l_ServerCfgPath) = 0 then g_ServerConfig := StationConfig.Use else g_ServerConfig := TCfgList.Create(l_ServerCfgPath); end; end; function UserConfig: TCfgList; begin Result := g_UserConfig; end; function StationConfig: TCfgList; begin Result := g_StationConfig; end; function ServerConfig: TCfgList; begin Result := g_ServerConfig; end; class function TCfgList.CorrectCfgFileName( const aName: TFileName): TFileName; begin if Length(aName) = 0 then Result := ChangeFileExt(Application.ExeName, CfgExt) else Result := ExpandFileName(aName); end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\l3IniFile.pas initialization enter'); {$EndIf} {без initialization finalization не компилит} {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\l3IniFile.pas initialization leave'); {$EndIf} finalization DoneConfigs; end.
unit fmuSlipRegistration; interface uses // VCL Windows, ComCtrls, StdCtrls, Controls, Classes, SysUtils, ExtCtrls, Buttons, Dialogs, Spin, // This untPages, untDriver, untUtil, untTypes, Grids, ValEdit, untTestParams; type { TfmSlipRegistration } TfmSlipRegistration = class(TPage) btnStdRegistration: TBitBtn; btnRegistration: TBitBtn; vleParams: TValueListEditor; btnLoadFromTables: TButton; lblCount: TLabel; btnDefaultValues: TButton; btnSaveToTables: TButton; seCount: TSpinEdit; procedure btnRegistrationClick(Sender: TObject); procedure btnStdRegistrationClick(Sender: TObject); procedure vleParamsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure btnLoadFromTablesClick(Sender: TObject); procedure btnDefaultValuesClick(Sender: TObject); procedure btnSaveToTablesClick(Sender: TObject); procedure vleParamsSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); procedure FormResize(Sender: TObject); private function GetItem(const AName: string): Integer; function GetFloatItem(const AName: string): Double; function GetCurrItem(const AName: string): Currency; function LoadFromTables: Integer; function SaveToTables: Integer; public procedure Initialize; override; procedure UpdatePage; override; procedure UpdateObject; override; end; implementation {$R *.DFM} const C_Quantity = 'Количество'; C_Price = 'Цена'; C_Department = 'Отдел'; C_Tax = 'Налог'; C_Tax1 = 'Налог 1'; C_Tax2 = 'Налог 2'; C_Tax3 = 'Налог 3'; C_Tax4 = 'Налог 4'; C_StringForPrinting = 'Строка'; const RegSlipParams: array[0..2] of TIntParam = ( (Name: C_Quantity; Value: 1), (Name: C_Price; Value: 100), (Name: C_Department; Value: 0) ); const RegSlipExParams: array[0..20] of TIntParam = ( (Name: 'Формат целого кол-ва'; Value: 1), (Name: 'Количество строк в операции'; Value: 3), (Name: 'Строка текста'; Value: 1), (Name: 'Строка произведения кол-ва на цену'; Value: 2), (Name: 'Строка суммы'; Value: 3), (Name: 'Строка отдела'; Value: 2), (Name: 'Шрифт текста'; Value: 1), (Name: 'Шрифт кол-ва'; Value: 1), (Name: 'Шрифт знака умножения'; Value: 1), (Name: 'Шрифт цены'; Value: 1), (Name: 'Шрифт суммы'; Value: 1), (Name: 'Шрифт отдела'; Value: 1), (Name: 'Кол-во символов текста'; Value: 40), (Name: 'Кол-во символов кол-ва'; Value: 14), (Name: 'Кол-во символов цены'; Value: 14), (Name: 'Кол-во символов суммы'; Value: 14), (Name: 'Кол-во символов отдела'; Value: 40), (Name: 'Смещение текста'; Value: 1), (Name: 'Смещение произведения кол-ва на цену'; Value: 20), (Name: 'Смещение суммы'; Value: 1), (Name: 'Смещение отдела'; Value: 1) ); { TfmSlipRegistration } procedure TfmSlipRegistration.UpdateObject; function GetVal(Row: Integer): Integer; begin Result := StrToInt(Trim(vleParams.Cells[1, Row + 11])); end; begin // Основные параметры Driver.OperationBlockFirstString := seCount.Value; Driver.Quantity := GetFloatItem(C_Quantity); Driver.Price := GetCurrItem(C_Price); Driver.Department := GetItem(C_Department); Driver.StringForPrinting := VLE_GetPropertyValue(vleParams, C_StringForPrinting); Driver.Tax1 := VLE_GetPickPropertyValue(vleParams, C_Tax1); Driver.Tax2 := VLE_GetPickPropertyValue(vleParams, C_Tax2); Driver.Tax3 := VLE_GetPickPropertyValue(vleParams, C_Tax3); Driver.Tax4 := VLE_GetPickPropertyValue(vleParams, C_Tax4); // Дополнительные параметры Driver.Quantityformat := GetVal(0); Driver.StringQuantityinOperation := GetVal(1); Driver.TextStringNumber := GetVal(2); Driver.QuantityStringNumber := GetVal(3); Driver.SummStringNumber := GetVal(4); Driver.DepartmentStringNumber := GetVal(5); Driver.TextFont := GetVal(6); Driver.QuantityFont := GetVal(7); Driver.MultiplicationFont := GetVal(8); Driver.PriceFont := GetVal(9); Driver.SummFont := GetVal(10); Driver.DepartmentFont := GetVal(11); Driver.TextSymbolNumber := GetVal(12); Driver.QuantitySymbolNumber := GetVal(13); Driver.PriceSymbolNumber := GetVal(14); Driver.SummSymbolNumber := GetVal(15); Driver.DepartmentSymbolNumber := GetVal(16); Driver.TextOffset := GetVal(17); Driver.QuantityOffset := GetVal(18); Driver.SummOffset := GetVal(19); Driver.DepartmentOffset := GetVal(20); end; procedure TfmSlipRegistration.btnRegistrationClick(Sender: TObject); var Count: Integer; begin EnableButtons(False); try UpdateObject; Check(Driver.RegistrationOnSlipDocument); Count := Driver.OperationBlockFirstString; Count := Count + Driver.StringQuantityinOperation; Driver.OperationBlockFirstString := Count; UpdatePage; finally EnableButtons(True); end; end; procedure TfmSlipRegistration.UpdatePage; begin seCount.Value := Driver.OperationBlockFirstString; end; procedure TfmSlipRegistration.btnStdRegistrationClick(Sender: TObject); var Count: Integer; begin EnableButtons(False); try UpdateObject; Check(Driver.StandardRegistrationOnSlipDocument); Count := Driver.OperationBlockFirstString; Count := Count + Driver.ReadTableDef(13,1,2,3); Driver.OperationBlockFirstString := Count; UpdatePage; finally EnableButtons(True); end; end; procedure TfmSlipRegistration.Initialize; var i: Integer; begin VLE_AddSeparator(vleParams, 'Основные'); for i := Low(RegSlipParams) to High(RegSlipParams) do VLE_AddProperty(vleParams, RegSlipParams[i].Name, IntToStr(RegSlipParams[i].Value)); for i := 1 to 4 do VLE_AddPickProperty(vleParams, Format('%s %d', [C_Tax, i]), 'Нет', ['Нет', '1 группа', '2 группа', '3 группа', '4 группа'], [0, 1, 2, 3, 4]); VLE_AddProperty(vleParams, C_StringForPrinting, 'Строка для печати'); VLE_AddSeparator(vleParams, 'Дополнительные'); for i := Low(RegSlipExParams) to High(RegSlipExParams) do VLE_AddProperty(vleParams, RegSlipExParams[i].Name, IntToStr(RegSlipExParams[i].Value)); // Если были загружены настройки, записываем их в контрол if TestParams.ParamsLoaded then StringToVLEParams(vleParams, TestParams.SlipRegistration.Text) else TestParams.SlipRegistration.Text := VLEParamsToString(vleParams); end; function TfmSlipRegistration.LoadFromTables: Integer; var i: Integer; begin EnableButtons(False); try Driver.TableNumber := 13; Result := Driver.GetTableStruct; if Result <> 0 then Exit; Driver.RowNumber := 1; for i := 1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Result := Driver.ReadTable; if Result = 0 then vleParams.Cells[1, i + 10] := IntToSTr(Driver.ValueOfFieldInteger); end; Updatepage; finally EnableButtons(True); end; end; function TfmSlipRegistration.GetItem(const AName: string): Integer; begin Result := StrToInt(VLE_GetPropertyValue(vleParams, AName)); end; function TfmSlipRegistration.GetFloatItem(const AName: string): Double; begin Result := StrToFloat(VLE_GetPropertyValue(vleParams, AName)); end; function TfmSlipRegistration.GetCurrItem(const AName: string): Currency; begin Result := StrToCurr(VLE_GetPropertyValue(vleParams, AName)); end; procedure TfmSlipRegistration.vleParamsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin VLE_DrawCell(Sender, ACol, ARow, Rect, State); end; procedure TfmSlipRegistration.btnLoadFromTablesClick(Sender: TObject); begin Check(LoadFromTables); end; procedure TfmSlipRegistration.btnDefaultValuesClick(Sender: TObject); begin vleParams.Strings.Text := ''; Initialize; end; procedure TfmSlipRegistration.btnSaveToTablesClick(Sender: TObject); begin Check(SaveToTables); end; function TfmSlipRegistration.SaveToTables: Integer; var i: Integer; begin EnableButtons(False); try Driver.TableNumber := 13; Result := Driver.GetTableStruct; if Result <> 0 then Exit; Driver.RowNumber := 1; for i := 1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Driver.ValueOfFieldInteger := StrToInt(vleParams.Cells[1, i + 10]); Result := Driver.WriteTable; if Result <> 0 then Exit; end; Updatepage; finally EnableButtons(True); end; end; procedure TfmSlipRegistration.vleParamsSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); begin TestParams.SlipRegistration.Text := VLEParamsToString(vleParams); end; procedure TfmSlipRegistration.FormResize(Sender: TObject); begin if vleParams.Width > 392 then vleParams.DisplayOptions := vleParams.DisplayOptions + [doAutoColResize] else vleParams.DisplayOptions := vleParams.DisplayOptions - [doAutoColResize]; end; end.
unit gGUI; //============================================================================= // gGUI.pas //============================================================================= // // Responsible for drawing and handling user input for the main menu // //============================================================================= interface uses SwinGame, sgTypes, gTypes; procedure DrawMainMenu(var game : GameData); implementation procedure DrawMainMenu(var game : GameData); begin ClearScreen(ColorWhite); // Initial play/quit screen if game.menuStatus = MAIN_SCREEN then begin DrawBitmap('MainMenuBackground', 0, 0); if (MouseX() > 480) and (MouseY() > 320) and (MouseX() < 800) and (MouseY() < 400) then begin DrawBitmap('MainMenuPlayBtnHover', 480, 320); if MouseClicked(LeftButton) then begin PlaySoundEffect('UIClick'); StartReadingText(ColorBlack, 15, FontNamed('OpenSansSemiBold42'), 450, 325); game.menuStatus := CITY_NAME; end; end; if (MouseX() > 480) and (MouseY() > 430) and (MouseX() < 800) and (MouseY() < 510) then begin DrawBitmap('MainMenuQuitBtnHover', 480, 428); if MouseClicked(LeftButton) then begin PlaySoundEffect('UIClick'); game.guiStatus := SHUTDOWN; end; end; end; // City-name choosing screen if game.menuStatus = CITY_NAME then begin DrawBitmap('MainMenuName', 0, 0); if (MouseX() > 480) and (MouseY() > 430) and (MouseX() < 800) and (MouseY() < 510) then begin DrawBitmap('MainMenuOkBtnHover', 480, 428); if (MouseClicked(LeftButton)) then begin PlaySoundEffect('UIClick'); game.cityName := EndReadingText(); game.guiStatus := IN_GAME; game.moneyTimer := CreateTimer(); StartTimer(game.moneyTimer); end; end; if KeyTyped(ReturnKey) then begin game.cityName := EndReadingText(); game.guiStatus := IN_GAME; game.moneyTimer := CreateTimer(); StartTimer(game.moneyTimer); end; end; if DEBUG_MODE then begin DrawText('NOTE: GAME RUNNING IN DEBUG MODE', ColorBlack, 0,0); end; DrawText('101118713', ColorBlack, 'OpenSansSemiBold16', 0,680); DrawText('Music: Two Steps From Hell - Love You Forever', ColorBlack, 'OpenSansSemiBold16', 0,700); RefreshScreen(); end; end.
unit DelphiUp.View.Pages.Menu.Favoritos; 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.Layouts, DelphiUp.View.Styles, DelphiUp.View.Components.Button002; type TPageMenuFavoritos = class(TForm) Layout1: TLayout; Layout2: TLayout; Layout3: TLayout; Label1: TLabel; Rectangle1: TRectangle; private { Private declarations } FOnMenuShow : TProc; FOnMenuHide : TProc; public { Public declarations } function Component : TFMXObject; function OnMenuShow ( aValue : TProc ) : TPageMenuFavoritos; function OnMenuHide ( aValue : TProc ) : TPageMenuFavoritos; end; var PageMenuFavoritos: TPageMenuFavoritos; implementation uses Router4D; {$R *.fmx} { TForm1 } function TPageMenuFavoritos.Component: TFMXObject; begin Result := Layout1; Rectangle1.Fill.Color := PRIMARY; Label1.FontColor := INFO; Label1.TextSettings.Font.Size := FONT_SIZE_H1; Layout3.AddObject( TComponentButton002 .Create(Self) .Title('CADASTRAR ITEM') .Image('ico_barcode') .OnClick( procedure (Sender : TObject) begin if Assigned(FOnMenuHide) then FOnMenuHide; TRouter4D.Link.&To('Produto') end ) .Component ); Layout3.AddObject( TComponentButton002 .Create(Self) .Title('REPOR ESTOQUE') .Image('ico_box') .OnClick( procedure (Sender : TObject) begin if Assigned(FOnMenuHide) then FOnMenuHide; TRouter4D.Link.&To('ReporEstoque') end ) .Component ); Layout3.AddObject( TComponentButton002 .Create(Self) .Title('PAGAR CONTAS') .Image('ico_calculator') .OnClick( procedure (Sender : TObject) begin if Assigned(FOnMenuHide) then FOnMenuHide; TRouter4D.Link.&To('ContasPagar') end ) .Component ); Layout3.AddObject( TComponentButton002 .Create(Self) .Title('REALIZAR VENDA') .Image('ico_shopping') .OnClick( procedure (Sender : TObject) begin if Assigned(FOnMenuHide) then FOnMenuHide; TRouter4D.Link.&To('ContasPagar') end ) .Component ); end; function TPageMenuFavoritos.OnMenuHide(aValue: TProc): TPageMenuFavoritos; begin Result := Self; FOnMenuHide := aValue; end; function TPageMenuFavoritos.OnMenuShow(aValue: TProc): TPageMenuFavoritos; begin Result := Self; FOnMenuShow := aValue; end; end.
unit GX_SharedImages; {$I GX_CondDefine.inc} interface uses Classes, ImgList, Controls; type TdmSharedImages = class(TDataModule) Images: TImageList; DisabledImages: TImageList; end; const ImageIndexNew = 10; ImageIndexExpand = 12; ImageIndexContract = 13; ImageIndexInfo = 16; ImageIndexTrash = 30; ImageIndexFunction = 29; ImageIndexGear = 28; ImageIndexClosedFolder = 21; ImageIndexOpenFolder = 22; ImageIndexDocument = 23; ImageIndexArrow = 43; ImageIndexCheck = 46; ImageIndexBlank = 47; ImageIndexVisibility = 53; ImageIndexMemberType = 48; ImageIndexWindow = 57; ImageIndexWindows = 58; ImageIndexUnit = 59; ImageIndexToDoPriority = 71; function GetSharedImageList: TImageList; implementation uses GX_GExperts; {$R *.dfm} function GetSharedImageList: TImageList; begin Result := GExpertsInst.GetSharedImages; end; end.
unit graphicwebconst; interface resourcestring {error} ETransparencyError = 'Transparency must be between [0 and 9]'; EGraphicCreateError = 'Error creating'; EApiPasswordError = 'invalid password'; EApiServerOff = 'Server Off'; EApiCommunicationError = 'Unable to communicate with server'; {label} LTotal = 'Total'; implementation end.
namespace Sugar.Test; interface uses Sugar, Sugar.Collections, RemObjects.Elements.EUnit; type HashSetTest = public class (Test) private Data: HashSet<String>; public method Setup; override; method &Add; method Clear; method Contains; method &Remove; method Count; method Enumerator; method Intersect; method ForEach; method Constructors; method &Union; method IsSubsetOf; method IsSupersetOf; method SetEquals; end; implementation method HashSetTest.Setup; begin Data := new HashSet<String>; Data.Add("One"); Data.Add("Two"); Data.Add("Three"); end; method HashSetTest.Constructors; begin var Actual := new HashSet<String>(Data); Assert.AreEqual(Actual.Count, 3); Assert.AreEqual(Data.Count, 3); Actual.ForEach(item -> Assert.IsTrue(Data.Contains(item))); end; method HashSetTest.&Add; begin Assert.IsTrue(Data.Add("Four")); Assert.AreEqual(Data.Count, 4); Assert.IsTrue(Data.Contains("Four")); //no duplicates allowed Assert.IsFalse(Data.Add("Four")); Assert.AreEqual(Data.Count, 4); Assert.IsTrue(Data.Add(nil)); Assert.AreEqual(Data.Count, 5); end; method HashSetTest.Clear; begin Assert.AreEqual(Data.Count, 3); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method HashSetTest.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)); end; method HashSetTest.&Remove; begin Assert.IsTrue(Data.Remove("One")); Assert.AreEqual(Data.Count, 2); Assert.IsFalse(Data.Contains("One")); Assert.IsFalse(Data.Remove("One")); Assert.IsFalse(Data.Remove(nil)); Assert.IsFalse(Data.Remove("two")); Assert.AreEqual(Data.Count, 2); Assert.IsTrue(Data.Contains("Two")); end; method HashSetTest.Count; begin Assert.AreEqual(Data.Count, 3); Assert.IsTrue(Data.Remove("One")); Assert.AreEqual(Data.Count, 2); Data.Clear; Assert.AreEqual(Data.Count, 0); end; method HashSetTest.Enumerator; begin var Expected: HashSet<String> := new HashSet<String>; Expected.Add("One"); Expected.Add("Two"); Expected.Add("Three"); var lCount: Integer := 0; for Item: String in Data do begin inc(lCount); Assert.IsTrue(Expected.Contains(Item)); end; Assert.AreEqual(lCount, 3); end; method HashSetTest.ForEach; begin var Expected: HashSet<String> := new HashSet<String>; Expected.Add("One"); Expected.Add("Two"); Expected.Add("Three"); var lCount: Integer := 0; Data.ForEach(x -> begin inc(lCount); Assert.IsTrue(Expected.Contains(x)); end); Assert.AreEqual(lCount, 3); end; method HashSetTest.Intersect; begin var Value: HashSet<String> := new HashSet<String>; Value.Add("Zero"); Value.Add("Two"); Value.Add("Three"); Data.Intersect(Value); Assert.AreEqual(Data.Count, 2); Assert.IsTrue(Data.Contains("Two")); Assert.IsTrue(Data.Contains("Three")); Assert.AreEqual(Value.Count, 3); Data.Intersect(new HashSet<String>); Assert.AreEqual(Data.Count, 0); end; method HashSetTest.&Union; begin var Value: HashSet<String> := new HashSet<String>; Value.Add("Zero"); Value.Add("Two"); Value.Add("Three"); var Expected: HashSet<String> := new HashSet<String>; Expected.Add("One"); Expected.Add("Two"); Expected.Add("Three"); Expected.Add("Zero"); Data.Union(Value); Assert.AreEqual(Data.Count, 4); Assert.AreEqual(Value.Count, 3); Data.ForEach(item -> Assert.IsTrue(Expected.Contains(item))); end; method HashSetTest.IsSupersetOf; begin var Value: HashSet<String> := new HashSet<String>; Value.Add("Two"); Value.Add("Three"); Assert.IsTrue(Data.IsSupersetOf(Value)); Value.Add("One"); Assert.IsTrue(Data.IsSupersetOf(Value)); Value.Remove("One"); Value.Add("Zero"); Assert.IsFalse(Data.IsSupersetOf(Value)); Assert.IsTrue(Data.IsSupersetOf(new HashSet<String>)); Assert.Throws(->Data.IsSupersetOf(nil)); end; method HashSetTest.IsSubsetOf; begin var Value: HashSet<String> := new HashSet<String>; Value.Add("Two"); Value.Add("Three"); Assert.IsTrue(Value.IsSubsetOf(Data)); Value.Add("One"); Assert.IsTrue(Value.IsSubsetOf(Data)); Value.Remove("One"); Value.Add("Zero"); Assert.IsFalse(Value.IsSubsetOf(Data)); Assert.IsTrue(new HashSet<String>().IsSubsetOf(Data)); Assert.IsFalse(Data.IsSubsetOf(new HashSet<String>)); Assert.Throws(->Data.IsSubsetOf(nil)); end; method HashSetTest.SetEquals; begin var Value: HashSet<String> := new HashSet<String>; Value.Add("Two"); Value.Add("Three"); Assert.IsFalse(Data.SetEquals(Value)); Value.Add("One"); Assert.IsTrue(Data.SetEquals(Value)); Value.Clear; Data.Clear; Assert.IsTrue(Data.SetEquals(Value)); end; end.
unit IRoute4MeManagerUnit; interface uses IConnectionUnit, AddressBookContactActionsUnit, OptimizationActionsUnit, RouteActionsUnit, UserActionsUnit, AddressNoteActionsUnit, AddressActionsUnit, AvoidanceZoneActionsUnit, OrderActionsUnit, ActivityActionsUnit, TrackingActionsUnit, GeocodingActionsUnit, TerritoryActionsUnit, VehicleActionsUnit, FileUploadingActionsUnit, TelematicActionsUnit; type IRoute4MeManager = interface ['{2E31D4E6-C42A-4C9B-9ED5-445C3F6D6690}'] function Optimization: TOptimizationActions; function Route: TRouteActions; function AddressBookContact: TAddressBookContactActions; function User: TUserActions; function AddressNote: TAddressNoteActions; function Address: TAddressActions; function AvoidanceZone: TAvoidanceZoneActions; function Geocoding: TGeocodingActions; function Order: TOrderActions; function ActivityFeed: TActivityActions; function Tracking: TTrackingActions; function Territory: TTerritoryActions; function Vehicle: TVehicleActions; function Uploading: TFileUploadingActions; function Telematics: TTelematicActions; procedure SetConnectionProxy(Host: String; Port: integer; Username, Password: String); function Connection: IConnection; procedure Clear; end; implementation end.
unit BatchUpdatesU1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, ExtCtrls, DB, ADODB, StdCtrls; type TForm1 = class(TForm) ADODataSet1: TADODataSet; DataSource1: TDataSource; Panel1: TPanel; DBGrid1: TDBGrid; Button1: TButton; CheckBox1: TCheckBox; ADOConnection1: TADOConnection; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure CheckBox1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ADODataSet1.UpdateBatch; end; function ADOUpdatesPending(ADODataSet: TCustomADODataSet): boolean; var Clone: TADODataSet; begin Clone:=TADODataSet.Create(nil); try Clone.Clone(ADODataSet); Clone.FilterGroup:=fgPendingRecords; Clone.Filtered :=True; Result:=not (Clone.BOF and Clone.EOF); finally Clone.Free; end; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:=True; if ADOUpdatesPending(ADODataSet1) then CanClose:=(MessageDlg('Updates are still pending'+#13#10+ 'Close anyway ?', mtConfirmation, [mbYes, mbNo], 0)=mrYes); end; procedure TForm1.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then begin ADOConnection1.Connected:=True; ADODataSet1.Connection:=ADOConnection1; end else begin ADODataSet1.Connection:=nil; ADOConnection1.Connected:=False; end; end; procedure TForm1.Button2Click(Sender: TObject); begin ADODataSet1.SaveToFile('Local.ADTG'); end; procedure TForm1.Button3Click(Sender: TObject); begin ADODataSet1.SaveToFile('Local.XML', pfXML); end; end.
unit PessoaLive.Model.PessoaJuridica; interface uses PessoaLive.Interfaces, PessoaLive.Model.Endereco; type TPessoaJuridica = class(TInterfacedObject, iPessoaJuridica) private FCNPJ : String; FEndereco : iEndereco<iPessoaJuridica>; public constructor Create; destructor Destroy; override; class function New : iPessoaJuridica; function CNPJ ( aValue : String ) : iPessoaJuridica; overload; function CNPJ : String; overload; function Endereco : iEndereco<iPessoaJuridica>; end; implementation { TPessoaJuridica } function TPessoaJuridica.CNPJ: String; begin Result := FCNPJ; end; function TPessoaJuridica.CNPJ(aValue: String): iPessoaJuridica; begin Result := Self; FCNPJ := aValue; end; constructor TPessoaJuridica.Create; begin FEndereco := TEndereco<iPessoaJuridica>.New(Self); end; destructor TPessoaJuridica.Destroy; begin inherited; end; function TPessoaJuridica.Endereco: iEndereco<iPessoaJuridica>; begin Result := FEndereco; end; class function TPessoaJuridica.New: iPessoaJuridica; begin Result := Self.Create; end; end.
{$I Compilers.inc} // These functions are get from: (**************************************************************) (* *) (* TWebbrowser functions by toms *) (* Version 1.9 *) (* E-Mail: tom@swissdelphicenter.ch *) (* *) (* Contributors: www.swissdelphicenter.ch *) (* *) (* *) (**************************************************************) unit WBProc; interface uses Windows, SysUtils, {$ifdef COMPILER_6_UP} Variants, {$endif} ActiveX, SHDocVw, MSHTML, Dialogs; procedure WB_SetFocus(WB: TWebbrowser); procedure WB_Copy(WB: TWebbrowser); procedure WB_SelectAll(WB: TWebbrowser); procedure WB_ShowPrintDialog(WB: TWebbrowser); procedure WB_ShowPrintPreview(WB: TWebbrowser); procedure WB_ShowPageSetup(WB: TWebbrowser); procedure WB_ShowFindDialog(WB: TWebbrowser); implementation function InvokeCMD(WB: TWebbrowser; nCmdID: DWORD): Boolean; overload; forward; function InvokeCMD(WB: TWebbrowser; InvokeIE: Boolean; Value1, Value2: Integer; var vaIn, vaOut: OleVariant): Boolean; overload; forward; const CGID_WebBrowser: TGUID = '{ED016940-BD5B-11cf-BA4E-00C04FD70816}'; HTMLID_FIND = 1; function InvokeCMD(WB: TWebbrowser; nCmdID: DWORD): Boolean; var vaIn, vaOut: OleVariant; begin Result := InvokeCMD(WB, True, nCmdID, unassigned, vaIn, vaOut); end; function InvokeCMD(WB: TWebbrowser; InvokeIE: Boolean; Value1, Value2: Integer; var vaIn, vaOut: OleVariant): Boolean; var CmdTarget: IOleCommandTarget; PtrGUID: PGUID; begin Result:= False; New(PtrGUID); if InvokeIE then PtrGUID^ := CGID_WebBrowser else PtrGuid := PGUID(nil); if WB.Document <> nil then try WB.Document.QueryInterface(IOleCommandTarget, CmdTarget); if CmdTarget <> nil then try CmdTarget.Exec(PtrGuid, Value1, Value2, vaIn, vaOut); Result:= True; finally CmdTarget._Release; end; except end; Dispose(PtrGUID); end; function WB_DocumentLoaded(WB: TWebbrowser): Boolean; var iDoc: IHtmlDocument2; begin Result := False; if Assigned(WB) then begin if WB.Document <> nil then begin WB.ControlInterface.Document.QueryInterface(IHtmlDocument2, iDoc); Result := Assigned(iDoc); end; end; end; procedure WB_SetFocus(WB: TWebbrowser); begin if WB_DocumentLoaded(WB) then (WB.Document as IHTMLDocument2).ParentWindow.Focus; end; procedure WB_Copy(WB: TWebbrowser); var vaIn, vaOut: Olevariant; begin InvokeCmd(WB, FALSE, OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut); end; procedure WB_SelectAll(WB: TWebbrowser); var vaIn, vaOut: Olevariant; begin InvokeCmd(WB, FALSE, OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut); end; procedure WB_ShowPrintDialog(WB: TWebbrowser); var OleCommandTarget: IOleCommandTarget; Command: TOleCmd; Success: HResult; begin if WB_DocumentLoaded(WB) then begin WB.Document.QueryInterface(IOleCommandTarget, OleCommandTarget); Command.cmdID := OLECMDID_PRINT; if OleCommandTarget.QueryStatus(nil, 1, @Command, nil) <> S_OK then begin // ShowMessage('Nothing to print'); Exit; end; if (Command.cmdf and OLECMDF_ENABLED) <> 0 then begin Success := OleCommandTarget.Exec(nil, OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, EmptyParam, EmptyParam); case Success of S_OK: ; OLECMDERR_E_CANCELED: ShowMessage('Canceled by user'); else ShowMessage('Error while printing'); end; end else // ShowMessage('Printing not possible'); end; end; procedure WB_ShowPrintPreview(WB: TWebbrowser); var vaIn, vaOut: OleVariant; begin if WB_DocumentLoaded(WB) then try // Execute the print preview command. WB.ControlInterface.ExecWB(OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_DONTPROMPTUSER, vaIn, vaOut); except end; end; procedure WB_ShowPageSetup(WB: TWebbrowser); var vaIn, vaOut: OleVariant; begin if WB_DocumentLoaded(WB) then try // Execute the page setup command. WB.ControlInterface.ExecWB(OLECMDID_PAGESETUP, OLECMDEXECOPT_PROMPTUSER, vaIn, vaOut); except end; end; procedure WB_ShowFindDialog(WB: TWebbrowser); begin InvokeCMD(WB, HTMLID_FIND); end; initialization OleInitialize(nil); finalization OleUninitialize; end.
unit DocImage; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TDocImage = class(TComponent) private FZoomFactor: integer; procedure SetZoomFactor(const Value: integer); { Private declarations } protected { Protected declarations } public { Public declarations } ms : TMemoryStream; function Scan:boolean; function View:boolean; constructor Create(AOwner:TComponent);override; destructor Destroy;override; published { Published declarations } property ZoomFactor:integer read FZoomFactor write SetZoomFactor; end; procedure Register; implementation uses ScanDocs, ViewDocs; procedure Register; begin RegisterComponents('FFS Dialogs', [TDocImage]); end; { TDocImage } constructor TDocImage.Create(AOwner: TComponent); begin inherited; ms := TMemoryStream.Create; end; destructor TDocImage.Destroy; begin ms.Free; inherited; end; function TDocImage.Scan: boolean; var ScanForm : TfrmScanDocs; begin ScanForm := TfrmScanDocs.Create(self); try ScanForm.cbScale.ItemIndex := ZoomFactor; if ScanForm.ShowModal = mrOk then begin ms.Clear; ScanForm.ms.Seek(0, soFromBeginning); ms.LoadFromStream(ScanForm.ms); result := true; end else result := false; finally ZoomFactor := ScanForm.cbScale.ItemIndex; ScanForm.Free; end; end; procedure TDocImage.SetZoomFactor(const Value: integer); begin FZoomFactor := Value; end; function TDocImage.View: boolean; var ViewForm : TfrmViewDocs; begin if ms.Size = 0 then exit; ViewForm := TfrmViewDocs.Create(self); try ViewForm.cbScale.ItemIndex := ZoomFactor; ViewForm.ms.LoadFromStream(ms); ViewForm.ShowModal; finally ZoomFactor := ViewForm.cbScale.ItemIndex; ViewForm.Free; end; end; end.
{---------------------------------------------------------------------------- | | Library: Envision | | Module: EnScan | | Description: Scanning class. | | History: Feb 28, 1999. Michel Brazeau, first version | |---------------------------------------------------------------------------} unit EnScan; {$I Envision.Inc} interface uses Windows, { for THandle } SysUtils, { for Exception } EnTwain, { for TTwainData } EnMisc; { for TImageFormat, AddBackSlashToPath } type TScanner = class(TObject) protected FTwainData : TTwainData; { FCreated is set True when the object is properly created. This is used when destroying a partially created TScanner } FCreated : Boolean; procedure LoadTwain; procedure UnloadTwain; function GetShowUI : Boolean; procedure SetShowUI( const Show : Boolean ); function GetRequestedXDpi : Word; procedure SetRequestedXDpi( const Dpi : Word ); function GetRequestedYDpi : Word; procedure SetRequestedYDpi( const Dpi : Word ); function GetRequestedImageFormat : TImageFormat; procedure SetRequestedImageFormat( const ImageFormat : TImageFormat ); public constructor Create; destructor Destroy; override; { IsConfigured returns True if the scanner drivers are configured on computer. } function IsConfigured : Boolean; { Displays a modal dialog box which allows the user to select the scanner. Returns False on user cancel.} function SelectScanner : Boolean; procedure Acquire( const AcquireEvent : TAcquireEvent; const CallBackData : LongInt ); property ShowUI : Boolean read GetShowUI write SetShowUI; { these options are used when ShowUI is set False before invoking Acquire. Defaults: RequestedXDpi = 200 RequestedYDpi = 200 RequestedImageFormat = ifBlackWhite } property RequestedXDpi : Word read GetRequestedXDpi write SetRequestedXDpi; property RequestedYDpi : Word read GetRequestedYDpi write SetRequestedYDpi; property RequestedImageFormat : TImageFormat read GetRequestedImageFormat write SetRequestedImageFormat; end; EScannerError = class(Exception); {--------------------------------------------------------------------------} implementation uses EnMsg; { msgXXXX } var InstanceCreated : Boolean; {--------------------------------------------------------------------------} constructor TScanner.Create; begin inherited Create; if InstanceCreated then raise EScannerError.Create(msgOnlyOneScannerObjectPermitted); FillChar(FTwainData, SizeOf(FTwainData), 0); with FTwainData.AppId do begin Id := 0; Version.MajorNum := 1; Version.MinorNum := 0; Version.Language := TWLG_ENG; Version.Country := TWCY_USA; StrPCopy(@Version.Info, ''); ProtocolMajor := TWON_PROTOCOLMAJOR; ProtocolMinor := TWON_PROTOCOLMINOR; SupportedGroups := DG_IMAGE or DG_CONTROL; StrPCopy(@Manufacturer, ''); StrPCopy(@ProductFamily, ''); StrPCopy(@ProductName, ''); end; ShowUI := True; RequestedXDpi := 200; RequestedYDpi := 200; RequestedImageFormat := ifBlackWhite; InstanceCreated := True; FCreated := True; { the drivers are only loaded upon the first usage } end; {--------------------------------------------------------------------------} destructor TScanner.Destroy; begin UnloadTwain; if FCreated then InstanceCreated := False; inherited Destroy; end; {--------------------------------------------------------------------------} function TScanner.GetShowUI : Boolean; begin Result := FTwainData.ShowUI; end; {--------------------------------------------------------------------------} procedure TScanner.SetShowUI( const Show : Boolean ); begin FTwainData.ShowUI := Show; end; {--------------------------------------------------------------------------} function TScanner.GetRequestedXDpi : Word; begin Result := FTwainData.XDpi; end; {--------------------------------------------------------------------------} procedure TScanner.SetRequestedXDpi( const Dpi : Word ); begin FTwainData.XDpi := Dpi; end; {--------------------------------------------------------------------------} function TScanner.GetRequestedYDpi : Word; begin Result := FTwainData.YDpi; end; {--------------------------------------------------------------------------} procedure TScanner.SetRequestedYDpi( const Dpi : Word ); begin FTwainData.YDpi := Dpi; end; {--------------------------------------------------------------------------} function TScanner.GetRequestedImageFormat : TImageFormat; begin Result := FTwainData.ImageFormat; end; {--------------------------------------------------------------------------} procedure TScanner.SetRequestedImageFormat( const ImageFormat : TImageFormat ); begin FTwainData.ImageFormat := ImageFormat; end; {--------------------------------------------------------------------------} procedure TScanner.LoadTwain; var TempStr : String; Handle32 : TW_INT32; begin if FTwainData.DllHandle <> 0 then Exit; { already loaded } SetLength(TempStr, 255); if GetWindowsDirectory(PChar(TempStr), 255) = 0 then raise EScannerError.Create('GetWindowsDirectory failed'); SetLength(TempStr, StrLen(PChar(TempStr))); TempStr := AddBackSlashToPath(TempStr) + CTwainDllFileName; FTwainData.DllHandle := LoadLibrary(PChar(TempStr)); if FTwainData.DllHandle <= HINSTANCE_ERROR then begin { set DllHandle to 0 for proper clean up in UnloadTwain} FTwainData.DllHandle := 0; raise EScannerError.Create('LoadLibrary(' + TempStr + ') failed'); end; TempStr := 'DSM_Entry'; FTwainData.DSMEntry := TDSM_Entry(GetProcAddress( FTwainData.DLLHandle, PChar(TempStr))); if @FTwainData.DSMEntry = nil then raise EScannerError.Create('GetProcAddress failed: ' + TempStr); FTwainData.ParentHandle := CreateWindow( PChar('STATIC'), PChar('Twain Window'), WS_POPUPWINDOW, Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT), Integer(CW_USEDEFAULT), HWND_DESKTOP, 0, hInstance, nil); if FTwainData.ParentHandle = 0 then raise EScannerError.Create('CreateWindow failed'); Handle32 := FTwainData.ParentHandle; if not CallTriplet( nil, @FTwainData.AppId, DG_CONTROL, DAT_PARENT, MSG_OPENDSM, @Handle32, nil, FTwainData.DsmEntry) then raise EScannerError.Create(msgUnableToOpenTWAINSourceManager); { assert: TWAIN is currently in state 4, 'Source Opened' } end; {--------------------------------------------------------------------------} procedure TScanner.UnloadTwain; var Handle32 : TW_INT32; begin if FTwainData.ParentHandle <> 0 then begin Handle32 := FTwainData.ParentHandle; CallTriplet( nil, @FTwainData.AppId, DG_CONTROL, DAT_PARENT, MSG_CLOSEDSM, @Handle32, nil, FTwainData.DsmEntry); DestroyWindow(FTwainData.ParentHandle); FTwainData.ParentHandle := 0; end; if FTwainData.DLLHandle <> 0 then begin FreeLibrary(FTwainData.DLLHandle); FTwainData.DLLHandle := 0; FTwainData.DSMEntry := nil; end; end; {--------------------------------------------------------------------------} function TScanner.SelectScanner : Boolean; begin LoadTwain; FillChar(FTwainData.SourceId, SizeOf(FTwainData.SourceId), 0); Result := CallTriplet( nil, @FTwainData.AppId, DG_CONTROL, DAT_IDENTITY, MSG_USERSELECT, @FTwainData.SourceId, nil, FTwainData.DsmEntry); end; {--------------------------------------------------------------------------} function TScanner.IsConfigured : Boolean; begin { check is loaded first } Result := (FTwainData.DLLHandle <> 0); if not Result then begin Result := True; try LoadTwain; except Result := False; end; end; end; {--------------------------------------------------------------------------} procedure TScanner.Acquire( const AcquireEvent : TAcquireEvent; const CallBackData : LongInt ); { applies the current options in pTwainData^ to the currently opened source. } procedure ApplyOptions; var Fix32 : TW_FIX32; PixelType : TW_UINT16; BitDepth : TW_UINT16; begin Fix32.Whole := FTwainData.XDpi; Fix32.Frac := 0; SetSingleValueCap( ICAP_XRESOLUTION, TWTY_FIX32, Fix32.Long, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); Fix32.Whole := FTwainData.YDpi; Fix32.Frac := 0; SetSingleValueCap( ICAP_YRESOLUTION, TWTY_FIX32, Fix32.Long, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); case FTwainData.ImageFormat of ifBlackWhite : begin PixelType := TWPT_BW; BitDepth := 1; end; ifGray16 : begin PixelType := TWPT_GRAY; BitDepth := 4; end; ifGray256: begin PixelType := TWPT_GRAY; BitDepth := 8; end; ifColor16 : begin PixelType := TWPT_PALETTE; BitDepth := 4; end; ifColor256: begin PixelType := TWPT_PALETTE; BitDepth := 8; end; ifTrueColor: begin PixelType := TWPT_RGB; BitDepth := 24; end; else raise ETwainError.Create('Invalid image type'); end; { case } { NOTE: pixel type must be set before bit depth } SetSingleValueCap( ICAP_PIXELTYPE, TWTY_UINT16, PixelType, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); SetSingleValueCap( ICAP_BITDEPTH, TWTY_UINT16, BitDepth, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); end; { ApplyOptions } var WasEnabled : Boolean; TwainUI : TW_USERINTERFACE; begin LoadTwain; FillChar(FTwainData.SourceId, SizeOf(FTwainData.SourceId), 0); if not CallTriplet( nil, @FTwainData.AppId, DG_CONTROL, DAT_IDENTITY, MSG_OPENDS, @FTwainData.SourceId, nil, FTwainData.DsmEntry) then raise ETwainError.Create('Unable to open TWAIN data source'); try WasEnabled := not EnableWindow(FTwainData.ParentHandle, False); try { ensure native transfer mode is used } SetSingleValueCap( ICAP_XFERMECH, TWTY_UINT16, TWSX_NATIVE, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); { ensure any number of images may be scanned } SetSingleValueCap( CAP_XFERCOUNT, TWTY_INT16, -1, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); { ensure units is inches } SetSingleValueCap( ICAP_UNITS, TWTY_UINT16, TWUN_INCHES, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry); { apply the options even if ShowUI is True, as this may set the default in the scanner's interface. } ApplyOptions; FillChar(TwainUI, SizeOf(TwainUI), 0); TwainUI.ShowUI := FTwainData.ShowUI; TwainUI.hParent := FTwainData.ParentHandle; if not CallTriplet( @FTwainData.SourceId, @FTwainData.AppId, DG_CONTROL, DAT_USERINTERFACE, MSG_ENABLEDS, @TwainUI, nil, FTwainData.DsmEntry) then raise ETwainError.Create('Unable to enable twain source.'); try ProcessImages( AcquireEvent, @FTwainData.SourceId, @FTwainData.AppId, FTwainData.DsmEntry, CallBackData); finally CallTriplet( @FTwainData.SourceId, @FTwainData.AppId, DG_CONTROL, DAT_USERINTERFACE, MSG_DISABLEDS, @TwainUI, nil, FTwainData.DsmEntry); end; finally EnableWindow(FTwainData.ParentHandle, WasEnabled); end; finally if FTwainData.SourceId.Id <> 0 then begin if not CallTriplet( nil, @FTwainData.AppId, DG_CONTROL, DAT_IDENTITY, MSG_CLOSEDS, @FTwainData.SourceId, nil, FTwainData.DsmEntry) then raise ETwainError.Create('Unable to close TWAIN data source'); FillChar(FTwainData.SourceId, SizeOf(FTwainData.SourceId), 0); end; end; end; {--------------------------------------------------------------------------} initialization InstanceCreated := False; end.
unit phoenix_audio_digital; interface uses sound_engine; procedure phoenix_audio_reset; procedure phoenix_audio_update; procedure phoenix_audio_cerrar; procedure phoenix_audio_start; procedure phoenix_wsound_a(valor:byte); procedure phoenix_wsound_b(valor:byte); implementation uses principal,sysutils; type phoenix_voz=record frec:byte; vol:byte; activa:boolean; dentro_onda:integer; tsample:byte; end; pphoenix_voz=^phoenix_voz; c_state=record counter:integer; level:integer; end; n_state=record counter:integer; polyoffs:integer; polybit:integer; lowpass_counter:integer; lowpass_polybit:integer; tsample:byte; end; const phoenix_wave:array[0..31] of byte=( $07,$06,$05,$03,$03,$04,$04,$03,$03,$04,$03,$06,$07,$07,$06,$00, $73,$6F,$70,$73,$76,$73,$74,$74,$74,$76,$76,$76,$74,$70,$70,$74); VMIN=0; VMAX=32767; var phoenix_sound:array[0..1] of pphoenix_voz; poly18:array[0..8191] of cardinal; sound_latch_a:byte; c24_state,c25_state:c_state; noise_state:n_state; procedure phoenix_audio_reset; begin phoenix_sound[0].activa:=false; phoenix_sound[1].activa:=false; end; procedure phoenix_audio_start; var i,j:integer; shiftreg,bits:cardinal; begin getmem(phoenix_sound[0],sizeof(phoenix_voz)); getmem(phoenix_sound[1],sizeof(phoenix_voz)); fillchar(phoenix_sound[0]^,sizeof(phoenix_voz),0); fillchar(phoenix_sound[1]^,sizeof(phoenix_voz),0); phoenix_sound[0].tsample:=init_channel; phoenix_sound[1].tsample:=init_channel; noise_state.tsample:=init_channel; //Audio digital fillchar(c24_state,sizeof(c_state),0); fillchar(c25_state,sizeof(c_state),0); fillchar(noise_state,sizeof(c_state),0); sound_latch_a:=0; shiftreg:=0; for i:=0 to 8191 do begin bits:=0; for j:=0 to 31 do begin bits:=(bits shr 1) or (shiftreg shl 31); if (((shiftreg shr 16) and 1)=((shiftreg shr 17) and 1)) then shiftreg:= (shiftreg shl 1) or 1 else shiftreg:=shiftreg shl 1; end; poly18[i]:= bits; end; end; procedure phoenix_audio_cerrar; begin freemem(phoenix_sound[0]); freemem(phoenix_sound[1]); phoenix_sound[0]:=nil; phoenix_sound[1]:=nil; end; function update_c24(samplerate:integer):integer; var n:integer; temp:extended; {* Noise frequency control (Port B): * Bit 6 lo charges C24 (6.8u) via R51 (330) and when * bit 6 is hi, C24 is discharged through R52 (20k) * in approx. 20000 * 6.8e-6 = 0.136 seconds} const C24=6.8e-6; R49=1000; R51=330; R52=20000; begin if (sound_latch_a and $40)<>0 then begin if (c24_state.level > VMIN) then begin temp:=(c24_state.level - VMIN)/(R52 * C24); c24_state.counter:=c24_state.counter-trunc(temp); if (c24_state.counter<=0) then begin temp:= -c24_state.counter / samplerate + 1; n:=trunc(temp); c24_state.counter:=c24_state.counter+(n* samplerate); c24_state.level:=c24_state.level-n; if (c24_state.level<VMIN) then c24_state.level:= VMIN; end; end; end else begin if (c24_state.level< VMAX) then begin temp:=(VMAX-c24_state.level) / ((R51+R49) * C24); c24_state.counter:=c24_state.counter-trunc(temp); if (c24_state.counter<= 0) then begin temp:=-c24_state.counter/ samplerate + 1; n:=trunc(temp); c24_state.counter:=c24_state.counter+(n * samplerate); c24_state.level:=c24_state.level+n; if (c24_state.level>VMAX) then c24_state.level:=VMAX; end; end; end; update_c24:=VMAX-c24_state.level; end; function update_c25(samplerate:integer):integer; var n:integer; temp:extended; { * Bit 7 hi charges C25 (6.8u) over a R50 (1k) and R53 (330) and when * bit 7 is lo, C25 is discharged through R54 (47k) * in about 47000 * 6.8e-6 = 0.3196 seconds} const C25=6.8e-6; R50=1000; R53=330; R54=47000; begin if (sound_latch_a and $80)<>0 then begin if (c25_state.level< VMAX) then begin temp:=(VMAX -c25_state.level) / ((R50+R53) * C25); c25_state.counter:=c25_state.counter-trunc(temp); if (c25_state.counter<= 0) then begin temp:=-c25_state.counter/samplerate + 1; n:=trunc(temp); c25_state.counter:=c25_state.counter+(n * samplerate); c25_state.level:=c25_state.level+n; if (c25_state.level> VMAX ) then c25_state.level:= VMAX; end; end; end else begin if (c25_state.level> VMIN) then begin temp:=(c25_state.level- VMIN) / (R54 * C25); c25_state.counter:=c25_state.counter-trunc(temp); if (c25_state.counter<= 0 ) then begin temp:=-c25_state.counter / samplerate + 1; n:=trunc(temp); c25_state.counter:=c25_state.counter+(n*samplerate); c25_state.level:=c25_state.level-n; if (c25_state.level< VMIN ) then c25_state.level:=VMIN; end; end; end; update_c25:=c25_state.level; end; function noise(samplerate:integer):integer; var vc24,vc25,sum,n:integer; level,frequency,temp:extended; begin vc24:=update_c24(FREQ_BASE_AUDIO); vc25:=update_c25(FREQ_BASE_AUDIO); sum:=0; { * The voltage levels are added and control I(CE) of transistor TR1 * (NPN) which then controls the noise clock frequency (linearily?). * level = voltage at the output of the op-amp controlling the noise rate.} if( vc24 < vc25 ) then level:= vc24 + (vc25 - vc24) / 2 else level:= vc25 + (vc24 - vc25) / 2; frequency:= 588 + 6325 * level / 32768; { * NE555: Ra=47k, Rb=1k, C=0.05uF * minfreq = 1.44 / ((47000+2*1000) * 0.05e-6) = approx. 588 Hz * R71 (2700 Ohms) parallel to R73 (47k Ohms) = approx. 2553 Ohms * maxfreq = 1.44 / ((2553+2*1000) * 0.05e-6) = approx. 6325 Hz } noise_state.counter:=noise_state.counter-trunc(frequency); if (noise_state.counter <= 0) then begin temp:=(-noise_state.counter / samplerate) + 1; n:=trunc(temp); noise_state.counter:=noise_state.counter+(n * samplerate); noise_state.polyoffs:= (noise_state.polyoffs + n) and $3ffff; noise_state.polybit:= (poly18[noise_state.polyoffs shr 5] shr (noise_state.polyoffs and 31)) and 1; end; if (noise_state.polybit=0) then sum:=sum+vc24; // 400Hz crude low pass filter: this is only a guess!! */ noise_state.lowpass_counter:=noise_state.lowpass_counter-400; if (noise_state.lowpass_counter<=0) then begin noise_state.lowpass_counter:=noise_state.lowpass_counter+samplerate; noise_state.lowpass_polybit:=noise_state.polybit; end; if (noise_state.lowpass_polybit=0) then sum:=sum+vc25; noise:=sum; end; procedure phoenix_audio_update; var numero_voz:byte; i:word; offset,offset_step:integer; sum:integer; begin for numero_voz:=0 to 1 do begin if phoenix_sound[numero_voz].activa then begin offset:=phoenix_sound[numero_voz].dentro_onda; offset_step:=(FREQ_BASE_AUDIO div (16-phoenix_sound[numero_voz].frec)); for i:=0 to (sound_status.long_sample-1) do begin offset:=offset+offset_step; tsample[phoenix_sound[numero_voz].tsample,i]:=phoenix_wave[(offset shr 16) and $1f]*($20*(3-phoenix_sound[numero_voz].vol)); end; phoenix_sound[numero_voz].dentro_onda:=offset; end; end; for i:=0 to (sound_status.long_sample-1) do begin sum:=noise(FREQ_BASE_AUDIO) div 2; if sum>32767 then sum:=32767 else if sum<-32767 then sum:=-32767; tsample[noise_state.tsample,i]:=sum; end; end; procedure phoenix_wsound_a(valor:byte); begin sound_latch_a:=valor; //form1.statusbar1.panels[2].text:=inttostr(valor and $f); phoenix_sound[0].frec:=valor and $f; phoenix_sound[0].vol:=(valor and $30) shr 4; phoenix_sound[0].activa:=phoenix_sound[0].frec<$f; end; procedure phoenix_wsound_b(valor:byte); begin phoenix_sound[1].frec:=valor and $f; phoenix_sound[1].vol:=(valor and $10) shr 4; phoenix_sound[1].activa:=phoenix_sound[0].frec<$f; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Bluetooth, FMX.Layouts, FMX.ListBox, FMX.StdCtrls, FMX.Memo, FMX.Controls.Presentation, FMX.Edit, FMX.TabControl, FMX.ScrollBox, FMX.ListView.Types, FMX.ListView, FMX.ListView.Appearances, System.ImageList, FMX.ImgList, FMX.ListView.Adapters.Base; type TServerConnectionTH = class(TThread) private { Private declarations } FServerSocket: TBluetoothServerSocket; FSocket: TBluetoothSocket; protected procedure Execute; override; public { Public declarations } constructor Create(ACreateSuspended: Boolean); destructor Destroy; override; end; TForm1 = class(TForm) ButtonDiscover: TButton; ButtonPair: TButton; ButtonUnPair: TButton; ButtonPairedDevices: TButton; DisplayR: TMemo; Edit1: TEdit; Button2: TButton; FreeSocket: TButton; Labeldiscoverable: TLabel; ComboBoxDevices: TComboBox; ComboBoxPaired: TComboBox; Panel1: TPanel; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; LabelNameSarver: TLabel; ButtonServices: TButton; PanelClient: TPanel; LabelClient: TLabel; ButtonConnectToRFCOMM: TButton; PanelServer: TPanel; ButtonOpenReadingSocket: TButton; LabelServer: TLabel; PnlDiscover: TPanel; PnlPairedDevs: TPanel; Panel2: TPanel; AniIndicator1: TAniIndicator; StyleBook1: TStyleBook; ListView1: TListView; ImageList1: TImageList; AniIndicator2: TAniIndicator; procedure ButtonDiscoverClick(Sender: TObject); procedure ButtonPairClick(Sender: TObject); procedure ButtonUnPairClick(Sender: TObject); procedure ButtonPairedDeviceClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ButtonOpenReadingSocketClick(Sender: TObject); procedure ButtonConnectToRFCOMMClick(Sender: TObject); procedure ButtonCloseReadingSocketClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FreeSocketClick(Sender: TObject); function ManagerConnected:Boolean; function GetServiceName(GUID: string): string; procedure ComboBoxPairedChange(Sender: TObject); procedure ButtonServicesClick(Sender: TObject); private { Private declarations } FBluetoothManager: TBluetoothManager; FDiscoverDevices: TBluetoothDeviceList; FPairedDevices: TBluetoothDeviceList; FAdapter: TBluetoothAdapter; FSocket: TBluetoothSocket; ItemIndex: Integer; ServerConnectionTH: TServerConnectionTH; procedure DevicesDiscoveryEnd(const Sender: TObject; const ADevices: TBluetoothDeviceList); procedure PairedDevices; procedure SendData; function GetServiceImageIndex(const AServiceUUID: TGUID): Integer; public { Public declarations } end; Const ServiceName = 'Basic Text Server'; ServiceGUI = '{B62C4E8D-62CC-404B-BBBF-BF3E3BBB1378}'; var Form1: TForm1; implementation {$R *.fmx} {$R *.Windows.fmx MSWINDOWS} procedure TForm1.ButtonPairClick(Sender: TObject); begin if ManagerConnected then if ComboboxDevices.ItemIndex > -1 then FAdapter.Pair(FDiscoverDevices[ComboboxDevices.ItemIndex]) else ShowMessage('No device selected'); end; procedure TForm1.ButtonUnPairClick(Sender: TObject); begin if ManagerConnected then if ComboboxPaired.ItemIndex > -1 then FAdapter.UnPair(FPairedDevices[ComboboxPaired.ItemIndex]) else ShowMessage('No Paired device selected'); end; procedure TForm1.ComboBoxPairedChange(Sender: TObject); begin LabelNameSarver.Text := ComboBoxPaired.Items[ComboBoxPaired.ItemIndex]; end; procedure TForm1.PairedDevices; var I: Integer; begin ComboboxPaired.Clear; if ManagerConnected then begin FPairedDevices := FBluetoothManager.GetPairedDevices; if FPairedDevices.Count > 0 then for I:= 0 to FPairedDevices.Count - 1 do ComboboxPaired.Items.Add(FPairedDevices[I].DeviceName) else ComboboxPaired.Items.Add('No Paired Devices'); end; end; procedure TForm1.ButtonPairedDeviceClick(Sender: TObject); begin PairedDevices; ComboboxPaired.DropDown; end; procedure TForm1.ButtonServicesClick(Sender: TObject); var LServices: TBluetoothServiceList; LDevice: TBluetoothDevice; I: Integer; LListItem : TListViewItem; begin ListView1.Items.Clear; if ManagerConnected then if ComboboxPaired.ItemIndex > -1 then begin LDevice := FPairedDevices[ComboboxPaired.ItemIndex] as TBluetoothDevice; AniIndicator2.Visible := True; LServices := LDevice.GetServices; AniIndicator2.Visible := False; for I := 0 to LServices.Count - 1 do begin LListItem := ListView1.Items.Add; LListItem.ImageIndex := GetServiceImageIndex(LServices[I].UUID); LListItem.Text := LServices[I].Name; if LListItem.Text = '' then LListItem.Text := '<Unknown>'; LListItem.Detail := GUIDToString(LServices[I].UUID); end; end else ShowMessage('No paired device selected'); end; procedure TForm1.FreeSocketClick(Sender: TObject); begin FreeAndNil(FSocket); DisplayR.Lines.Add('Client socket set free'); DisplayR.GoToLineEnd; end; procedure TForm1.Button2Click(Sender: TObject); begin DisplayR.ReadOnly := False; DisplayR.SelectAll; DisplayR.DeleteSelection; DisplayR.ReadOnly := True; end; function TForm1.GetServiceName(GUID: string): string; var LServices: TBluetoothServiceList; LDevice: TBluetoothDevice; I: Integer; begin LDevice := FPairedDevices[ComboboxPaired.ItemIndex] as TBluetoothDevice; LServices := LDevice.GetServices; for I := 0 to LServices.Count - 1 do begin if StringToGUID(GUID) = LServices[I].UUID then begin Result := LServices[I].Name; break; end; end; end; procedure TForm1.ButtonConnectToRFCOMMClick(Sender: TObject); begin if ManagerConnected then try SendData; except on E : Exception do begin DisplayR.Lines.Add(E.Message); DisplayR.GoToTextEnd; FreeAndNil(FSocket); end; end; end; function TForm1.ManagerConnected:Boolean; begin if FBluetoothManager.ConnectionState = TBluetoothConnectionState.Connected then begin Labeldiscoverable.Text := 'Device discoverable as "'+FBluetoothManager.CurrentAdapter.AdapterName+'"'; Result := True; end else begin Result := False; DisplayR.Lines.Add('No Bluetooth device Found'); DisplayR.GoToTextEnd; end end; procedure TForm1.SendData; var ToSend: TBytes; LDevice: TBluetoothDevice; begin if (FSocket = nil) or (ItemIndex <> ComboboxPaired.ItemIndex) then begin if ComboboxPaired.ItemIndex > -1 then begin LDevice := FPairedDevices[ComboboxPaired.ItemIndex] as TBluetoothDevice; DisplayR.Lines.Add(GetServiceName(ServiceGUI)); DisplayR.GoToTextEnd; FSocket := LDevice.CreateClientSocket(StringToGUID(ServiceGUI), False); if FSocket <> nil then begin ItemIndex := ComboboxPaired.ItemIndex; FSocket.Connect; ToSend := TEncoding.UTF8.GetBytes(Edit1.Text); FSocket.SendData(ToSend); DisplayR.Lines.Add('Text Sent'); DisplayR.GoToTextEnd; end else ShowMessage('Out of time -15s-'); end else ShowMessage('No paired device selected'); end else begin ToSend := TEncoding.UTF8.GetBytes(Edit1.Text); FSocket.SendData(ToSend); DisplayR.Lines.Add('Text Sent'); DisplayR.GoToTextEnd; end; end; procedure TForm1.ButtonDiscoverClick(Sender: TObject); begin AniIndicator1.Visible := True; ButtonDiscover.Text := 'Discovering...'; ButtonDiscover.Enabled := False; ComboboxDevices.Clear; if ManagerConnected then begin FAdapter := FBluetoothManager.CurrentAdapter; FBluetoothManager.StartDiscovery(10000); FBluetoothManager.OnDiscoveryEnd := DevicesDiscoveryEnd; end; end; procedure TForm1.DevicesDiscoveryEnd(const Sender: TObject; const ADevices: TBluetoothDeviceList); begin TThread.Synchronize(nil, procedure var I: Integer; begin ButtonDiscover.Text := 'Discover devices'; ButtonDiscover.Enabled := True; AniIndicator1.Visible := False; FDiscoverDevices := ADevices; for I := 0 to ADevices.Count - 1 do ComboboxDevices.Items.Add(ADevices[I].DeviceName + ' -> ' + ADevices[I].Address); ComboboxDevices.ItemIndex := 0; end); end; procedure TForm1.ButtonOpenReadingSocketClick(Sender: TObject); begin if ButtonOpenReadingSocket.IsPressed then begin if (ServerConnectionTH = nil) and ManagerConnected then begin try FAdapter := FBluetoothManager.CurrentAdapter; ServerConnectionTH := TServerConnectionTH.Create(True); ServerConnectionTH.FServerSocket := FAdapter.CreateServerSocket(ServiceName, StringToGUID(ServiceGUI), False); ServerConnectionTH.Start; DisplayR.Lines.Add(' - Service created: "'+ServiceName+'"'); DisplayR.GoToTextEnd; ButtonOpenReadingSocket.Text := 'Stop Text Service'; except on E : Exception do begin DisplayR.Lines.Add(E.Message); DisplayR.GoToTextEnd; ButtonOpenReadingSocket.IsPressed := False; end; end; end; end else if ServerConnectionTH <> nil then begin ServerConnectionTH.Terminate; ServerConnectionTH.WaitFor; FreeAndNil(ServerConnectionTH); DisplayR.Lines.Add(' - Service removed -'); DisplayR.GoToTextEnd; ButtonOpenReadingSocket.Text := 'Start Text Service'; end end; procedure TForm1.ButtonCloseReadingSocketClick(Sender: TObject); begin if ServerConnectionTH <> nil then begin ServerConnectionTH.Terminate; ServerConnectionTH.WaitFor; FreeAndNil(ServerConnectionTH); DisplayR.Lines.Add(' - Service removed -'); DisplayR.GoToTextEnd; end end; procedure TForm1.FormShow(Sender: TObject); begin try LabelServer.Text := ServiceName; LabelClient.Text := 'Client of '+ServiceName; FBluetoothManager := TBluetoothManager.Current; FAdapter := FBluetoothManager.CurrentAdapter; if ManagerConnected then begin PairedDevices; ComboboxPaired.ItemIndex := 0; end; except on E : Exception do begin ShowMessage(E.Message); end; end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin if ServerConnectionTH <> nil then begin ServerConnectionTH.Terminate; ServerConnectionTH.WaitFor; FreeAndNil(ServerConnectionTH); end end; {TServerConnection} constructor TServerConnectionTH.Create(ACreateSuspended: Boolean); begin inherited; end; destructor TServerConnectionTH.Destroy; begin FSocket.Free; FServerSocket.Free; inherited; end; procedure TServerConnectionTH.Execute; var Msg: string; LData: TBytes; begin while not Terminated do try FSocket := nil; while not Terminated and (FSocket = nil) do FSocket := FServerSocket.Accept(100); if(FSocket <> nil) then begin while not Terminated do begin LData := FSocket.ReceiveData; if Length(LData) > 0 then Synchronize(procedure begin Form1.DisplayR.Lines.Add(TEncoding.UTF8.GetString(LData)); Form1.DisplayR.GoToTextEnd; end); Sleep(100); end; end; except on E : Exception do begin Msg := E.Message; Synchronize(procedure begin Form1.DisplayR.Lines.Add('Server Socket closed: ' + Msg); Form1.DisplayR.GoToTextEnd; end); end; end; end; function TForm1.GetServiceImageIndex(const AServiceUUID: TGUID): Integer; type TServiceImg = record Name: string; UUID: TBluetoothUUID; ImageIndex: Integer; end; TServiceImages = array [0..27] of TServiceImg; const ServiceImages: TServiceImages = ( (Name: 'LAN Access Using PPP'; UUID:'{00001102-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'DialupNetworking'; UUID:'{00001103-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'OBEXObjectPush'; UUID:'{00001105-0000-1000-8000-00805F9B34FB}'; ImageIndex: 8), (Name: 'OBEXFileTransfer'; UUID:'{00001106-0000-1000-8000-00805F9B34FB}'; ImageIndex: 8), (Name: 'Cordless Telephony'; UUID:'{00001109-0000-1000-8000-00805F9B34FB}'; ImageIndex: 5), (Name: 'Audio Source'; UUID:'{0000110A-0000-1000-8000-00805F9B34FB}'; ImageIndex: 1), (Name: 'Audio Sink'; UUID:'{0000110B-0000-1000-8000-00805F9B34FB}'; ImageIndex: 1), (Name: 'AV Remote Control Target'; UUID:'{0000110C-0000-1000-8000-00805F9B34FB}'; ImageIndex: 2), (Name: 'Advanced Audio Distribution'; UUID:'{0000110D-0000-1000-8000-00805F9B34FB}'; ImageIndex: 1), (Name: 'AV Remote Control'; UUID:'{0000110E-0000-1000-8000-00805F9B34FB}'; ImageIndex: 2), (Name: 'Headset Audio Gateway'; UUID:'{00001112-0000-1000-8000-00805F9B34FB}'; ImageIndex: 6), (Name: 'WAP'; UUID:'{00001113-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'WAP Client'; UUID:'{00001114-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'Personal Area Network User (PANU)'; UUID:'{00001115-0000-1000-8000-00805F9B34FB}'; ImageIndex: 9), (Name: 'Network Access Point (NAP)'; UUID:'{00001116-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'Group Ad-hoc Network (GN)'; UUID:'{00001117-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'Handsfree'; UUID:'{0000111E-0000-1000-8000-00805F9B34FB}'; ImageIndex: 5), (Name: 'Handsfree Audio Gateway'; UUID:'{0000111F-0000-1000-8000-00805F9B34FB}'; ImageIndex: 5), (Name: 'SIM Access'; UUID:'{0000112D-0000-1000-8000-00805F9B34FB}'; ImageIndex: 10), (Name: 'Phonebook Access - PCE'; UUID:'{0000112E-0000-1000-8000-00805F9B34FB}'; ImageIndex: 0), (Name: 'Phonebook Access - PSE'; UUID:'{0000112F-0000-1000-8000-00805F9B34FB}'; ImageIndex: 0), (Name: 'Phonebook Access'; UUID:'{00001130-0000-1000-8000-00805F9B34FB}'; ImageIndex: 0), (Name: 'Headset headset'; UUID:'{00001131-0000-1000-8000-00805F9B34FB}'; ImageIndex: 6), (Name: 'Message Access Server'; UUID:'{00001132-0000-1000-8000-00805F9B34FB}'; ImageIndex: 4), (Name: 'Message Notification Server'; UUID:'{00001133-0000-1000-8000-00805F9B34FB}'; ImageIndex: 4), (Name: 'Message Access Profile'; UUID:'{00001134-0000-1000-8000-00805F9B34FB}'; ImageIndex: 4), (Name: 'Generic Networking'; UUID:'{00001201-0000-1000-8000-00805F9B34FB}'; ImageIndex: 7), (Name: 'Generic Audio'; UUID:'{00001203-0000-1000-8000-00805F9B34FB}'; ImageIndex: 1) ); var I: Integer; begin Result := 3; for I := Low(ServiceImages) to High(ServiceImages) do if ServiceImages[I].UUID = AServiceUUID then Exit(ServiceImages[I].ImageIndex); end; end.
program oddEven1(input, output); var k : integer; isEven : boolean; procedure odd(n : integer; var b : boolean); forward; procedure even(n : integer; var b : boolean); begin if n = 0 then b := true else odd(n - 1, b) end; { even } procedure odd; begin if n = 0 then b := false else even(n - 1, b) end; { odd } begin write('Value of k: '); read(k); even(k, isEven); if isEven then writeln('The value was even.') else writeln('The value was odd.') end.
unit tfwWordWorker; {* Поддержка исполняемых скомпилированных слов. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwWordWorker.pas" // Стереотип: "SimpleClass" // Элемент модели: "TtfwWordWorker" MUID: (4DCBD489023A) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwAnonimousWord , kwCompiledWordWorker , tfwScriptingInterfaces , kwCompiledWordPrim ; type TtfwWordWorker = {abstract} class(TtfwAnonimousWord) {* Поддержка исполняемых скомпилированных слов. } protected function CompiledWorkerClass(const aCtx: TtfwContext): RkwCompiledWordWorker; virtual; abstract; procedure FillCompiledWorker(aWorker: TtfwWord; const aContext: TtfwContext); virtual; procedure CompileWordWorker(const aContext: TtfwContext; aRightParams: TkwCompiledWordPrim); function MakeCompiledWordWorker(const aContext: TtfwContext; aRightParams: TkwCompiledWordPrim): TtfwWord; virtual; function EndBracket(const aContext: TtfwContext; aSilent: Boolean): RtfwWord; override; procedure AfterCompile(var theNewContext: TtfwContext; aCompiled: TkwCompiledWordPrim); override; function AfterWordMaxCount(const aCtx: TtfwContext): Integer; override; function CompiledWordClass(const aCtx: TtfwContext): RkwCompiledWordPrim; override; end;//TtfwWordWorker {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , kwTemporaryCompiledCode , SysUtils //#UC START# *4DCBD489023Aimpl_uses* //#UC END# *4DCBD489023Aimpl_uses* ; procedure TtfwWordWorker.FillCompiledWorker(aWorker: TtfwWord; const aContext: TtfwContext); //#UC START# *4F219FA10268_4DCBD489023A_var* //#UC END# *4F219FA10268_4DCBD489023A_var* begin //#UC START# *4F219FA10268_4DCBD489023A_impl* // - ничего не делаем, это чтобы предок мог aWorker заполнить по своему усмотрению //#UC END# *4F219FA10268_4DCBD489023A_impl* end;//TtfwWordWorker.FillCompiledWorker procedure TtfwWordWorker.CompileWordWorker(const aContext: TtfwContext; aRightParams: TkwCompiledWordPrim); //#UC START# *4F41566A02E5_4DCBD489023A_var* var l_CPW : TtfwWord{TkwCompiledWordWorker}; //#UC END# *4F41566A02E5_4DCBD489023A_var* begin //#UC START# *4F41566A02E5_4DCBD489023A_impl* l_CPW := MakeCompiledWordWorker(aContext, aRightParams); try //_Assert(l_CPW.Key = nil); if (l_CPW.Key = nil) then //l_CPW.Key := aContext.rKeyWordDefiningNow; l_CPW.Key := Self.Key; // - чтобы легче было опознавать слова по их Runner'ам FillCompiledWorker(l_CPW, aContext); DoCompiledWord(l_CPW, aContext); finally FreeAndNil(l_CPW); end;//try..finally //#UC END# *4F41566A02E5_4DCBD489023A_impl* end;//TtfwWordWorker.CompileWordWorker function TtfwWordWorker.MakeCompiledWordWorker(const aContext: TtfwContext; aRightParams: TkwCompiledWordPrim): TtfwWord; //#UC START# *5284D8180211_4DCBD489023A_var* //#UC END# *5284D8180211_4DCBD489023A_var* begin //#UC START# *5284D8180211_4DCBD489023A_impl* if (AfterWordMaxCount(aContext) = 1) then begin CompilerAssert((aRightParams.CodeCount = 1), 'Допустим только один параметр после слова, a их: ' + IntToStr(aRightParams.CodeCount), aContext); Result := CompiledWorkerClass(aContext).Create(aRightParams.GetCode(aContext)[0], Self, aContext); end//AfterWordMaxCount = 1 else Result := CompiledWorkerClass(aContext).Create(aRightParams, Self, aContext); //#UC END# *5284D8180211_4DCBD489023A_impl* end;//TtfwWordWorker.MakeCompiledWordWorker function TtfwWordWorker.EndBracket(const aContext: TtfwContext; aSilent: Boolean): RtfwWord; //#UC START# *4DB6C99F026E_4DCBD489023A_var* //#UC END# *4DB6C99F026E_4DCBD489023A_var* begin //#UC START# *4DB6C99F026E_4DCBD489023A_impl* Result := DisabledEndBracket(aContext, aSilent); //#UC END# *4DB6C99F026E_4DCBD489023A_impl* end;//TtfwWordWorker.EndBracket procedure TtfwWordWorker.AfterCompile(var theNewContext: TtfwContext; aCompiled: TkwCompiledWordPrim); //#UC START# *4DB6CE2302C9_4DCBD489023A_var* //#UC END# *4DB6CE2302C9_4DCBD489023A_var* begin //#UC START# *4DB6CE2302C9_4DCBD489023A_impl* CompileWordWorker(theNewContext.rPrev^, aCompiled); inherited; //#UC END# *4DB6CE2302C9_4DCBD489023A_impl* end;//TtfwWordWorker.AfterCompile function TtfwWordWorker.AfterWordMaxCount(const aCtx: TtfwContext): Integer; //#UC START# *4DB9B446039A_4DCBD489023A_var* //#UC END# *4DB9B446039A_4DCBD489023A_var* begin //#UC START# *4DB9B446039A_4DCBD489023A_impl* Result := 1; //#UC END# *4DB9B446039A_4DCBD489023A_impl* end;//TtfwWordWorker.AfterWordMaxCount function TtfwWordWorker.CompiledWordClass(const aCtx: TtfwContext): RkwCompiledWordPrim; //#UC START# *4DBAEE0D028D_4DCBD489023A_var* //#UC END# *4DBAEE0D028D_4DCBD489023A_var* begin //#UC START# *4DBAEE0D028D_4DCBD489023A_impl* Result := TkwTemporaryCompiledCode; //#UC END# *4DBAEE0D028D_4DCBD489023A_impl* end;//TtfwWordWorker.CompiledWordClass initialization TtfwWordWorker.RegisterClass; {* Регистрация TtfwWordWorker } {$IfEnd} // NOT Defined(NoScripts) end.
unit Rule_LLV; interface uses BaseRule, BaseRuleData; type TRule_LLV = class(TBaseRule) protected fParamN: Word; fInt64Ret: PArray; fFloatRet: PArray; function GetLLVValueF(AIndex: integer): double; function GetLLVValueI(AIndex: integer): int64; function GetParamN: Word; procedure SetParamN(const Value: Word); procedure ComputeInt64; procedure ComputeFloat; public constructor Create(ADataType: TRuleDataType); override; destructor Destroy; override; procedure Execute; override; property ValueF[AIndex: integer]: double read GetLLVValueF; property ValueI[AIndex: integer]: int64 read GetLLVValueI; property ParamN: Word read GetParamN write SetParamN; end; implementation { TRule_LLV } constructor TRule_LLV.Create(ADataType: TRuleDataType); begin inherited; fParamN := 20; fInt64Ret := nil; fFloatRet := nil; // SetLength(fFloatRet, 0); // SetLength(fInt64Ret, 0); end; destructor TRule_LLV.Destroy; begin CheckInArray(fFloatRet); CheckInArray(fInt64Ret); inherited; end; procedure TRule_LLV.Execute; begin if Assigned(OnGetDataLength) then begin fBaseRuleData.DataLength := OnGetDataLength; case fBaseRuleData.DataType of dtInt64: begin ComputeInt64; end; dtDouble: begin ComputeFloat; end; end; end; end; procedure TRule_LLV.ComputeInt64; var tmpInt64_Meta: PArray; //tmpInt64_MetaNode: PArrayInt64Node; //tmpInt64RetNode: PArrayInt64Node; i: integer; tmpCounter: integer; tmpValue: int64; tmpPreValue: Int64; begin if Assigned(OnGetDataI) then begin if fInt64Ret = nil then fInt64Ret := CheckOutArrayInt64; tmpInt64_Meta := CheckOutArrayInt64; try SetArrayLength(fInt64Ret, fBaseRuleData.DataLength); SetArrayLength(tmpInt64_Meta, fBaseRuleData.DataLength); //tmpInt64RetNode := fInt64Ret.FirstValueNode; //tmpInt64_MetaNode := tmpInt64_Meta.FirstValueNode; for i := 0 to fBaseRuleData.DataLength - 1 do begin tmpValue := OnGetDataI(i); SetArrayInt64Value(tmpInt64_Meta, i, tmpValue); //tmpInt64_MetaNode.Value[i] := OnGetDataI(i); tmpCounter := fParamN - 1; while tmpCounter > 0 do begin if i > tmpCounter - 1 then begin //tmpPreValue := tmpInt64_MetaNode.Value[i - tmpCounter]; tmpPreValue := GetArrayInt64Value(tmpInt64_Meta, i - tmpCounter); if tmpValue > tmpPreValue then begin tmpValue := tmpPreValue; end; end; Dec(tmpCounter); end; //SetArrayInt64NodeValue(tmpInt64RetNode, i, tmpValue); SetArrayInt64Value(fInt64Ret, i, tmpValue); end; finally CheckInArray(tmpInt64_Meta); end; end; end; procedure TRule_LLV.ComputeFloat; var tmpFloat_Meta: PArray; i: integer; tmpCounter: integer; tmpValue: double; tmpPreValue: double; begin if Assigned(OnGetDataF) then begin if fFloatRet = nil then fFloatRet := CheckOutArrayDouble; tmpFloat_Meta := CheckOutArrayDouble; try SetArrayLength(fFloatRet, fBaseRuleData.DataLength); SetArrayLength(tmpFloat_Meta, fBaseRuleData.DataLength); //tmpFloatRetNode := fFloatRet.FirstValueNode; //tmpFloat_MetaNode := tmpFloat_Meta.FirstValueNode; for i := 0 to fBaseRuleData.DataLength - 1 do begin tmpValue := OnGetDataF(i); SetArrayDoubleValue(tmpFloat_Meta, i, tmpValue); //tmpFloat_MetaNode.Value[i] := tmpValue; tmpCounter := fParamN - 1; while tmpCounter > 0 do begin if i > tmpCounter - 1 then begin //tmpPreValue := tmpFloat_MetaNode.Value[i - tmpCounter]; tmpPreValue := GetArrayDoubleValue(tmpFloat_Meta, i - tmpCounter); if tmpValue > tmpPreValue then begin tmpValue := tmpPreValue; end; end; Dec(tmpCounter); end; //SetArrayDoubleNodeValue(tmpFloatRetNode, i, tmpValue); SetArrayDoubleValue(fFloatRet, i, tmpValue); end; finally CheckInArray(tmpFloat_Meta); end; end; end; function TRule_LLV.GetParamN: Word; begin Result := fParamN; end; procedure TRule_LLV.SetParamN(const Value: Word); begin if Value > 0 then begin fParamN := Value; end; end; function TRule_LLV.GetLLVValueF(AIndex: integer): double; begin Result := 0; if fBaseRuleData.DataType = dtDouble then begin if fFloatRet <> nil then Result := GetArrayDoubleValue(fFloatRet, AIndex); end; end; function TRule_LLV.GetLLVValueI(AIndex: integer): int64; begin Result := 0; if fBaseRuleData.DataType = dtInt64 then begin if fInt64Ret <> nil then Result := GetArrayInt64Value(fInt64Ret, AIndex); end; end; end.
unit SheetHandlers; interface uses Classes, Controls, VoyagerInterfaces, VoyagerServerInterfaces, ObjectInspectorInterfaces, SyncObjs; const htmlAction_RefreshSheet = 'REFRESHSHEET'; type TSheetHandler = class(TInterfacedObject, IPropertySheetHandler) protected fContainer : IPropertySheetContainerHandler; fLoaded : boolean; fLastUpdate : integer; fExposed : boolean; public function GetContainer : IPropertySheetContainerHandler; procedure SetContainer(aContainer : IPropertySheetContainerHandler); virtual; procedure UnsetContainer; virtual; procedure StartSettingProperties; virtual; procedure StopSettingProperties; virtual; function Busy : boolean; virtual; function CreateControl(Owner : TControl) : TControl; virtual; function GetControl : TControl; virtual; procedure RenderProperties(Properties : TStringList); virtual; procedure SetFocus; virtual; procedure LostFocus; virtual; procedure Clear; virtual; procedure Refresh; virtual; function HandleURL(URL : TURL) : TURLHandlingResult; virtual; function Exposed : boolean; procedure Lock; virtual; procedure Unlock; virtual; function Loaded : boolean; virtual; end; TLockableSheetHandler = class(TSheetHandler) public constructor Create; destructor Destroy; override; private fLock : TCriticalSection; public procedure Lock; override; procedure Unlock; override; end; implementation uses URLParser; function TSheetHandler.GetContainer : IPropertySheetContainerHandler; begin result := fContainer; end; procedure TSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin fContainer := aContainer; end; procedure TSheetHandler.UnsetContainer; begin fContainer := nil; end; procedure TSheetHandler.StartSettingProperties; begin end; procedure TSheetHandler.StopSettingProperties; begin end; function TSheetHandler.Busy : boolean; begin result := false; end; function TSheetHandler.CreateControl(Owner : TControl) : TControl; begin result := nil; end; procedure TSheetHandler.RenderProperties(Properties : TStringList); begin end; function TSheetHandler.GetControl : TControl; begin result := nil; end; procedure TSheetHandler.SetFocus; begin fExposed := true; fLoaded := true; inc(fLastUpdate); end; procedure TSheetHandler.Clear; begin fExposed := false; fLoaded := false; inc(fLastUpdate); end; procedure TSheetHandler.LostFocus; begin //fExposed := false; end; procedure TSheetHandler.Refresh; begin fLoaded := false; Clear; SetFocus; end; function TSheetHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin try if GetURLAction(URL) = htmlAction_RefreshSheet then begin Refresh; result := urlHandled; end else result := urlNotHandled; except result := urlNotHandled; end; end; function TSheetHandler.Exposed : boolean; begin result := fExposed; end; procedure TSheetHandler.Lock; begin end; procedure TSheetHandler.Unlock; begin end; function TSheetHandler.Loaded : boolean; begin result := fLoaded; end; // TLockableSheetHandler constructor TLockableSheetHandler.Create; begin inherited Create; fLock := TCriticalSection.Create; end; destructor TLockableSheetHandler.Destroy; begin fLock.Free; inherited; end; procedure TLockableSheetHandler.Lock; begin fLock.Enter; end; procedure TLockableSheetHandler.Unlock; begin fLock.Leave; end; end.
unit DAO.TiposVerbasExpressas; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.TiposVerbasExpressas; type TTiposVerbasExpressasDAO = class private FConexao : TConexao; public constructor Create(); function Insert(aTipos: TTiposVerbasExpressas): Boolean; function Update(aTipos: TTiposVerbasExpressas): Boolean; function Delete(aTipos: TTiposVerbasExpressas): Boolean; function Localizar(aParam: Array of variant): TFDQuery; end; const TABLENAME = 'expressas_tipos_verbas'; implementation { TTiposVerbasExpressasDAO } constructor TTiposVerbasExpressasDAO.Create; begin FConexao := TConexao.Create; end; function TTiposVerbasExpressasDAO.Delete(aTipos: TTiposVerbasExpressas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_tipo = :pcod_tipoS', [aTipos.Codigo]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TTiposVerbasExpressasDAO.Insert(aTipos: TTiposVerbasExpressas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('insert into ' + TABLENAME + ' (cod_tipo, des_tipo, des_colunas) ' + 'values ' + '(:pcod_tipo, :pdes_tipo, :pdes_colunas);', [ATipos.Codigo, ATipos.Descricao, ATipos.Colunas]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TTiposVerbasExpressasDAO.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin if Length(aParam) < 2 then Exit; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_tipo = :pcod_tipo'); FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('where des_tipo like :pdes_tipo'); FDQuery.ParamByName('pdes_tipo').AsInteger := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TTiposVerbasExpressasDAO.Update(aTipos: TTiposVerbasExpressas): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + 'set ' + 'cod_tipo = :pcod_tipo, des_tipo = :pdes_tipo, des_colunas = :pdes_colunas ' + 'where ' + 'cod_tipo = :pcod_tipo;', [ATipos.Descricao, ATipos.Colunas, ATipos.Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit gameconfigform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, // LCL ExtCtrls, // TappyTux tappymodules, gameplayform; type { TformConfig } TformConfig = class(TForm) buttonLoad: TButton; btnWordlist: TButton; comboLanguage: TComboBox; comboGameType: TComboBox; comboSound: TComboBox; comboMusic: TComboBox; comboLevel: TComboBox; labelGameType: TLabel; labelWordlist: TLabel; lblLanguage: TLabel; labelSettings: TLabel; lblSound: TLabel; lblMusic: TLabel; lblLevel: TLabel; lblCredits: TLabel; listWordlist: TListBox; memoGameType: TMemo; memoCredits: TMemo; procedure buttonLoadClick(Sender: TObject); procedure btnWordlistClick(Sender: TObject); procedure comboGameTypeChange(Sender: TObject); procedure comboLanguageChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure memoCreditsChange(Sender: TObject); private { private declarations } public { public declarations } procedure TranslateUI(); end; var formConfig: TformConfig; implementation {$R *.lfm} { TformConfig } procedure TformConfig.comboGameTypeChange(Sender: TObject); var lModule: TTappyModule; begin lModule := GetModule(comboGameType.itemIndex); memoGameType.Text := lModule.LongDescription; labelWordlist.Caption := lModule.ConfigCaption; listWordlist.Items.Text := lModule.ConfigItems; if listWordlist.Items.Count >= comboLanguage.ItemIndex then begin if comboLanguage.ItemIndex < listWordlist.Items.Count then listWordlist.ItemIndex := comboLanguage.ItemIndex; end; end; procedure TformConfig.comboLanguageChange(Sender: TObject); begin case comboLanguage.ItemIndex of 0: // english begin labelGameType.Caption := 'Game Type'; //labelWordlist.Caption := 'Select Wordlist'; labelSettings.Caption := 'Settings'; lblLanguage.Caption := 'Language'; lblSound.Caption := 'SoundFX'; lblMusic.Caption := 'Music'; lblLevel.Caption := 'Starting Level'; lblCredits.Caption := 'Credits'; buttonLoad.Caption := 'Play'; formTappyTuxGame.LabelLevels.Caption := 'Level'; formTappyTuxGame.LabelScore.Caption := 'Score'; formTappyTuxGame.LabelLives.Caption := 'Lives'; formTappyTuxGame.btnExit.Caption := 'Exit'; end; 1: // portuguese begin labelGameType.Caption := 'Tipo de Jogo'; //labelWordlist.Caption := 'Selecione Lista de Palavras'; labelSettings.Caption := 'Configurações'; lblLanguage.Caption := 'Idioma'; lblSound.Caption := 'Efeitos Sonoros'; lblMusic.Caption := 'Música'; lblLevel.Caption := 'Nível de início'; lblCredits.Caption := 'Créditos'; buttonLoad.Caption := 'Jogar'; formTappyTuxGame.LabelLevels.Caption := 'Nível'; formTappyTuxGame.LabelScore.Caption := 'Pontos'; formTappyTuxGame.LabelLives.Caption := 'Vidas'; formTappyTuxGame.btnExit.Caption := 'Sair'; end; end; end; procedure TformConfig.buttonLoadClick(Sender: TObject); begin SetCurrentModule(comboGameType.ItemIndex); formTappyTuxGame.Show; GetCurrentModule().StartNewGame(comboSound.ItemIndex, comboMusic.ItemIndex, comboLevel.ItemIndex, listWordlist.ItemIndex); Hide; end; procedure TformConfig.btnWordlistClick(Sender: TObject); begin end; procedure TformConfig.FormCreate(Sender: TObject); var i: Integer; begin TranslateUI(); // Initialize modules for i := 0 to GetModuleCount() -1 do GetModule(i).InitModule(); end; procedure TformConfig.FormShow(Sender: TObject); begin comboLanguageChange(Self); comboGameTypeChange(Self); end; procedure TformConfig.memoCreditsChange(Sender: TObject); begin end; procedure TformConfig.TranslateUI; var i: Integer; lModule: TTappyModule; begin comboGameType.Items.Clear; for i := 0 to GetModuleCount() - 1 do begin lModule := GetModule(i); comboGameType.Items.Add(lModule.ShortDescription); end; comboGameType.ItemIndex := 0; end; end.
unit AceMerge; // // Copyright 2009 SCT Associates, Inc. // Written by Steven Tyrakowski and Kevin Maher // // Revised October 2, 2009 to support Unicode interface uses classes, Acefile, Aceutil, AceStr, SysUtils, AceTypes, AceSetup; type //---------------------------------------------------------------------- TAceMerge = class(TObject) private FStream: TAceStream; FPages: TAceList; FObjects, FNewObjects: TList; FDescription: String; FUserStream: TMemoryStream; FAcePrinterSetup: TAcePrinterSetup; FAceFileHeader: TAceFileHeader; FAceFileInfo: TAceFileInfo; { FAceFilePrinterInfo: TAceFilePrinterInfo;} FAceFilesAdded: LongInt; FPageStart: LongInt; procedure GetPrinterSetup(LoadStream: TStream; afh: TAceFileHeader); procedure GetUserStream(LoadStream: TStream); procedure GetPages(LoadStream: TStream;afi: TAceFileInfo); procedure GetObjects(LoadStream: TStream; afi: TAceFileInfo); procedure GetPageData(LoadStream: TStream; afh: TAceFileHeader); procedure ChangeObjects(RecType: Word; afh: TAceFileHeader); protected public constructor Create; virtual; destructor Destroy; override; procedure Clear; procedure LoadFromStream(LoadStream: TStream); procedure LoadFromFile(FileName: String); procedure SaveToFile(FileName: String); procedure SaveToStream(SaveStream: TStream); end; //---------------------------------------------------------------------- TAceMergeObject = class(TObject) private FObjectType: TAceAceFileObjectTypes; FLogPen: TAceLogPen; FLogBrush: TAceLogBrush; FLogFont: TAceLogFont; FUseObject: LongInt; protected public constructor Create; virtual; destructor Destroy; override; procedure Assign(Source: TObject); function IsEqual(Source: TObject): Boolean; function FontSame(lf: TAceLogFont): boolean; function PenSame(lp: TAceLogPen): boolean; function BrushSame(lb: TAceLogBrush): boolean; procedure Write(Stream: TStream); procedure Read(Stream: TStream); end; implementation //---------------------------------------------------------------------- constructor TAceMerge.Create; begin FObjects := TList.Create; FNewObjects := TList.Create; FUserStream := TMemoryStream.Create; FPages := TAceList.Create; FAcePrinterSetup := TAcePrinterSetup.Create; FStream := TAceStream.Create; end; //---------------------------------------------------------------------- destructor TAceMerge.Destroy; begin Clear; if FStream <> nil then FStream.Free; if FUserStream <> nil then FUserStream.Free; if FPages <> nil then FPages.Free; if FAcePrinterSetup <> nil then FAcePrinterSetup.Free; if FObjects <> nil then FObjects.Free; if FNewObjects <> nil then FNewObjects.Free; inherited Destroy; end; //---------------------------------------------------------------------- procedure TAceMerge.Clear; var Spot: Integer; begin FAceFilesAdded := 0; if FStream <> nil then FStream.Clear; if FPages <> nil then begin for Spot := 0 to FPages.Count - 1 do TObject(FPages.items(Spot)).Free; FPages.Clear; end; if FObjects <> nil then begin for Spot := 0 to FObjects.Count - 1 do TObject(FObjects.Items[Spot]).Free; FObjects.Clear; end; if FNewObjects <> nil then begin for Spot := 0 to FNewObjects.Count - 1 do TObject(FNewObjects.Items[Spot]).Free; FNewObjects.Clear; end; if FUserStream <> nil then TMemoryStream(FUserStream).Clear; end; //---------------------------------------------------------------------- procedure TAceMerge.GetPrinterSetup(LoadStream: TStream; afh: TAceFileHeader); var aps: TAcePrinterSetup; afpi: TAceFilePrinterInfo; rc: Word; begin if FAceFilesAdded = 1 then aps := FAcePrinterSetup else aps := TAcePrinterSetup.Create; if afh.Version < 3.0 then begin LoadStream.Read(afpi, SizeOf(afpi)- SizeOf(afpi.CollatedCopies)); afpi.CollatedCopies := True; aps.SetPrintInfo( afpi ); end else if afh.Version < 4.0 then begin LoadStream.Read(afpi, SizeOf(TAceFilePrinterInfo)); aps.SetPrintInfo( afpi); end else begin LoadStream.Read(rc, SizeOf(rc)); aps.ReadFromStream(LoadStream); end; if FAceFilesAdded > 1 then aps.Free; end; //---------------------------------------------------------------------- procedure TAceMerge.GetUserStream(LoadStream: TStream); var Len: LongInt; begin if FAceFilesAdded = 1 then begin TMemoryStream(FUserStream).Clear; LoadStream.Read(Len, SizeOf(Len)); if Len > 0 then FUserStream.CopyFrom(LoadStream, Len); end else begin LoadStream.Read(Len, SizeOf(Len)); if Len > 0 then LoadStream.Position := LoadStream.Position + Len; end; end; //---------------------------------------------------------------------- procedure TAceMerge.GetPages(LoadStream: TStream;afi: TAceFileInfo); var PageDataStart, PagePos, PageSpot: LongInt; pp: TAcePagePosition; begin FPageStart := FPages.Count; PageDataStart := FStream.Size; for PageSpot := 0 to afi.Pages - 1 do begin pp := TAcePagePosition.Create; LoadStream.Read(PagePos, SizeOf(PagePos)); pp.Pos := PagePos + PageDataStart; FPages.Add(pp); end; end; //---------------------------------------------------------------------- procedure TAceMerge.GetObjects(LoadStream: TStream; afi: TAceFileInfo); var rc: Word; obj, newobj: TAceMergeObject; Spot, OldSpot: Integer; begin // if we already used FNewObjects, clear it out if FNewObjects <> nil then begin for Spot := 0 to FNewObjects.Count - 1 do TObject(FNewObjects.Items[Spot]).Free; FNewObjects.Clear; end; // Loop over the objects in the ACE file being added to the // merge file and add each one to the FNewObjects TList for Spot := 0 to afi.Objects - 1 do begin LoadStream.Read(rc, SizeOf(rc)); obj := TAceMergeObject.Create; case rc of AceRT_Font: begin obj.FObjectType := aotFont; LoadStream.Read(obj.FLogFont, SizeOf(TAceLogFont)); end; AceRT_Pen: begin obj.FObjectType := aotPen; LoadStream.Read(obj.FLogPen, SizeOf(TAceLogPen)); end; AceRT_Brush: begin obj.FObjectType := aotBrush; LoadStream.Read(obj.FLogBrush, SizeOf(TAceLogBrush)); end; end; FNewObjects.Add(obj); end; // then loop over those objects and see if it is the same as // one of the objects already in the merge file // if so, set the UseObject property to that equal object // otherwise add the object to the list and set the reference to the // new location in the object list for the merged file for Spot := 0 to FNewObjects.Count - 1 do begin obj := FNewObjects.Items[Spot]; OldSpot := 0; while OldSpot < FObjects.Count do begin if obj.IsEqual(FObjects.Items[OldSpot]) then begin obj.FUseObject := OldSpot; OldSpot := FObjects.Count; end else Inc(OldSpot); end; if obj.FUseObject = -1 then begin newobj := TAceMergeObject.Create; newobj.Assign(obj); FObjects.Add(newobj); obj.FUseObject := FObjects.Count - 1; end; end; end; //---------------------------------------------------------------------- procedure TAceMerge.GetPageData(LoadStream: TStream; afh: TAceFileHeader); var pp: TAcePagePosition; RecType: Word; StreamSize: LongInt; Spot: LongInt; begin FStream.Seek(0,soFromEnd); FStream.CopyFrom(LoadStream, LoadStream.Size - LoadStream.Position); StreamSize := FStream.Size; for Spot := FPageStart to FPages.Count - 1 do begin pp := FPages.Items(Spot); FStream.Position := pp.Pos; // as we read in the page data, we need to modify any "Objects" to // point to its new position in the list of objects in the // merged file FStream.Read(RecType, SizeOf(RecType)); while (RecType <> AceRT_EndPage) And (FStream.Position < StreamSize) do begin ChangeObjects(RecType, afh); FStream.Read(RecType, SizeOf(RecType)); end; end; end; //---------------------------------------------------------------------- procedure TAceMerge.ChangeObjects(RecType: Word; afh: TAceFileHeader); var Spot: SmallInt; obj: TAceMergeObject; Count :LongInt; //---------------------------- procedure StreamMove(Len: LongInt); begin FStream.Position := FStream.Position + Len; end; //---------------------------- procedure ReadRect; begin StreamMove(SizeOf(SmallInt) * 4); end; //---------------------------- procedure ReadWord; begin StreamMove(SizeOf(Word)); end; //---------------------------- function ReadSmallInt: SmallInt; begin FStream.Read(Result, SizeOf(Result)); end; //---------------------------- function ReadLongInt: LongInt; begin FStream.Read(Result, SizeOf(Result)); end; //---------------------------- procedure ReadString; var Len: SmallInt; LongLen: LongInt; begin if afh.Version < 4.0 then begin FStream.Read(Len, SizeOf(Len)); LongLen := Len; end else begin FStream.Read(LongLen, SizeOf(LongLen)); end; StreamMove(LongLen); end; //---------------------------- procedure ReadStream; var Len: LongInt; begin FStream.Read(Len, SizeOf(Len)); StreamMove(Len); end; //---------------------------- procedure ReadBoolean; begin StreamMove(SizeOf(Boolean)); end; //---------------------------- begin // This will read in the Ace Record and if it is something that // needs to be modified, then change it in the stream, otherwise // just determine the record's size and set the position to be after // its end so it is ready for the next iteration of the calling loop case RecType of AceRT_SelectObject: begin Spot := ReadSmallInt; obj := TAceMergeObject(FNewObjects.Items[Spot]); StreamMove(-SizeOf(SmallInt)); FStream.Write(obj.FUseObject, SizeOf(SmallInt)); end; AceRT_StartPage, AceRT_EndPage:; AceRT_SetTextAlign: ReadWord; AceRT_TextOut: begin ReadSmallInt; ReadSmallInt; ReadString; end; AceRT_MoveTo, AceRT_LineTo: begin ReadSmallInt; ReadSmallInt; end; AceRT_PTextOut: begin ReadSmallInt; ReadSmallInt; Count := ReadLongInt; StreamMove(Count); end; AceRT_ExtTextOut: begin ReadSmallInt; ReadSmallInt; ReadSmallInt; ReadRect; Count := ReadLongInt; StreamMove(Count); end; AceRT_TextRect: begin ReadRect; ReadSmallInt; ReadSmallInt; ReadString; end; AceRT_FillRect, AceRT_Rectangle: ReadRect; AceRT_RoundRect: StreamMove(SizeOf(SmallInt) * 6); AceRT_Ellipse: ReadRect; AceRT_Draw: begin ReadSmallInt; ReadSmallInt; ReadSmallInt; ReadStream; end; AceRT_StretchDraw: begin ReadRect; ReadSmallInt; ReadStream; end; AceRT_ShadeRect: begin ReadRect; ReadSmallInt; end; AceRT_PrinterInfo: StreamMove(SizeOF(TAceFilePrinterInfo)); AceRT_NewPrinterInfo: begin Count := ReadLongInt; StreamMove(Count); end; AceRT_SetBkColor: ReadLongInt; AceRT_TextJustify: begin ReadRect; ReadSmallInt; ReadSmallInt; ReadString; ReadBoolean; if afh.Version > 1.0 then ReadRect; end; AceRT_AceDrawBitmap: begin ReadSmallInt; ReadSmallInt; ReadStream; end; AceRT_AceStretchDrawBitmap: begin ReadRect; ReadStream; end; AceRT_RtfDraw: begin ReadLongInt; ReadRect; ReadBoolean; ReadLongInt; ReadLongInt; ReadStream; end; AceRT_DrawCheckBox: begin ReadRect; ReadSmallInt; ReadLongInt; ReadSmallInt; end; AceRT_DrawShapeType: begin ReadSmallInt; StreamMove(SizeOf(LongInt) * 8); end; AceRT_PolyDrawType: begin ReadSmallInt; Count := ReadSmallInt; StreamMove(SizeOf(LongInt) * 2 * Count); end; AceRT_3of9BarCode,AceRT_2of5BarCode: begin ReadSmallInt; ReadSmallInt; ReadSmallInt; ReadSmallInt; ReadSmallInt; ReadSmallInt; ReadBoolean; ReadBoolean; ReadString; end else StreamMove(ReadLongInt); end; end; //---------------------------------------------------------------------- procedure TAceMerge.LoadFromStream(LoadStream: TStream); var afh: TAceFileHeader; afi: TAceFileInfo; begin LoadStream.Read(afh, SizeOf(TAceFileHeader)); if (afh.Key = 101071) then begin if (FAceFilesAdded > 0) And (afh.Version <> FAceFileHeader.Version) then Raise Exception.Create('You cannot combine ACE files from different versions.') else begin {$IFDEF UNICODE} if afh.Version < 5 then Raise Exception.Create('This UNICODE exe cannot combine non-Unicode ACE files.') {$ELSE} if afh.Version >= 5 then Raise Exception.Create('This exe cannot combine Unicode ACE files.') {$ENDIF} else begin Inc(FAceFilesAdded); LoadStream.Read(afi, SizeOf(TAceFileInfo)); if FAceFilesAdded = 1 then begin FAceFileHeader := afh; FAceFileInfo := afi; FDescription := StrPas(afh.Description); end; // This reads in PrinterSetup only for 1st file and skips over // the data in subsequent files to set stream position GetPrinterSetup(LoadStream, afh); // This collects UserStream for 1st file, then skips over // the data in subsequent files to set stream position GetUserStream(LoadStream); // This reads in the page position information and adds records to the // FPages TList for each page's position in the output ACE file GetPages(LoadStream,afi); // Update the Page Count after adding this file FAceFileInfo.Pages := FPages.Count; // This reads in the Pen, Brush and Font objects from the ACE file // and adds them to the list of objects after comparing them to // existing objects for uniqueness in the output file GetObjects(LoadStream, afi); // Update the count of Objects FAceFileInfo.Objects := FObjects.Count; // This copies the page data to FStream GetPageData(LoadStream, afh); end; end; end else Raise Exception.Create('Invalid ACE file format.'); end; //---------------------------------------------------------------------- procedure TAceMerge.LoadFromFile(FileName: String); var fs: TFileStream; begin fs := nil; try fs := TFileStream.Create(FileName, fmOpenRead); LoadFromStream(fs); finally if fs <> nil then fs.Free; end; end; //---------------------------------------------------------------------- procedure TAceMerge.SaveToFile(FileName: String); var fs: TFileStream; begin fs := nil; try fs := TFileStream.Create(FileName, fmCreate); SaveToStream(fs); finally if fs <> nil then fs.Free; end; end; //---------------------------------------------------------------------- procedure TAceMerge.SaveToStream(SaveStream: TStream); var SavePos: LongInt; Pos: Integer; Spot: LongInt; Len: LongInt; begin for Pos := 0 to Length(FAceFileHeader.Description) -1 do FAceFileHeader.Description[Pos] := #0; StrPLCopy(FAceFileHeader.Description, FDescription,SizeOf(FAceFileHeader.Description)-1); SaveStream.Write(FAceFileHeader, SizeOf(FAceFileHeader)); SaveStream.Write(FAceFileInfo, SizeOf(FAceFileInfo)); FAcePrinterSetup.WriteToStream(SaveStream); Len := FUserStream.Size;; SaveStream.Write(Len, SizeOf(Len)); FUserStream.Position := 0; SaveStream.CopyFrom(FUserStream, FUserStream.Size); for Pos := 0 to FPages.Count - 1 do begin Spot := TAcePagePosition(FPages.Items(Pos)).Pos; SaveStream.Write(Spot, SizeOf(Spot)); end; for Pos := 0 to FObjects.count - 1 do TAceMergeObject(FObjects.Items[Pos]).Write(SaveStream); FAceFileHeader.HeaderLen := SaveStream.Size; SaveStream.Position := 0; SaveStream.Write(FAceFileHeader, SizeOf(FAceFileHeader)); SaveStream.Position := SaveStream.Size; SavePos := FStream.Position; FStream.Position := 0; SaveStream.CopyFrom(FStream, FStream.Size); FStream.Position := SavePos; end; //---------------------------------------------------------------------- { TAceMergeObject } //---------------------------------------------------------------------- constructor TAceMergeObject.Create; begin FObjectType := aotNone; FUseObject := -1; end; //---------------------------------------------------------------------- destructor TAceMergeObject.Destroy; begin inherited Destroy; end; //---------------------------------------------------------------------- procedure TAceMergeObject.Assign(Source: TObject); var mo: TAceMergeObject; begin if Source is TAceMergeObject then begin mo := Source as TAceMergeObject; FObjectType := mo.FObjectType; case mo.FObjectType of aotFont: FLogFont := mo.FLogFont; aotBrush: FLogBrush := mo.FLogBrush; aotPen: FLogPen := mo.FLogPen; end; end; end; //---------------------------------------------------------------------- function TAceMergeObject.IsEqual(Source: TObject): Boolean; var mo: TAceMergeObject; begin Result := False; if Source is TAceMergeObject then begin mo := Source as TAceMergeObject; if FObjectType = mo.FObjectType then begin case mo.FObjectType of aotFont: Result := FontSame(mo.FLogFont); aotBrush: Result := BrushSame(mo.FLogBrush); aotPen: Result := PenSame(mo.FLogPen); end; end; end; end; //---------------------------------------------------------------------- function TAceMergeObject.FontSame(lf: TAceLogFont): boolean; begin Result := AceIsPCharEqual(@FLogFont, @lf, SizeOf(FLogFont) - SizeOf(FLogFont.Name)); if result And (StrComp(FLogFont.Name, lf.Name) <> 0) then Result := False; end; //---------------------------------------------------------------------- function TAceMergeObject.PenSame(lp: TAceLogPen): boolean; begin Result := AceIsPCharEqual(@lp, @FLogPen, SizeOf(FLogPen)); end; //---------------------------------------------------------------------- function TAceMergeObject.BrushSame(lb: TAceLogBrush): boolean; begin Result := False; // AceIsPCharEqual(@lb, @FLogBrush, SizeOf(FLogBrush)); end; //---------------------------------------------------------------------- procedure TAceMergeObject.Write(Stream: TStream); var ot: Word; begin case FObjectType of aotFont: begin ot := AceRT_Font; Stream.Write( ot, SizeOf(ot)); Stream.Write( FLogFont, SizeOf(FLogFont)); end; aotBrush: begin ot := AceRT_Brush; Stream.Write( ot, SizeOf(ot)); Stream.Write( FLogBrush, SizeOf(FLogBrush)); end; aotPen: begin ot := AceRT_Pen; Stream.Write( ot, SizeOf(ot)); Stream.Write( FLogPen, SizeOf(FLogPen)); end; end; end; //---------------------------------------------------------------------- procedure TAceMergeObject.Read(Stream: TStream); var rt: Word; begin Stream.Read(rt, SizeOf(rt)); case rt of AceRT_Font: begin FObjectType := aotFont; Stream.Read( FLogFont, SizeOf(FLogFont)); end; AceRT_Brush: begin FObjectType := aotBrush; Stream.Read( FLogBrush, SizeOf(FLogBrush)); end; AceRT_Pen: begin FObjectType := aotPen; Stream.Read( FLogPen, SizeOf(FLogPen)); end; end; end; end.
// This file is unused, for now unit GX_IdePackageRenameDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TfmIdxPackageRenameDlg = class(TForm) l_PackageFn: TLabel; l_Description: TLabel; ed_Description: TEdit; b_Ok: TButton; b_Cancel: TButton; private procedure SetData(const _fn: string; const _Description: string); procedure GetData(out _Description: string); public class function Execute(_Owner: TWinControl; const _fn: string; var _Description: string): Boolean; constructor Create(_Owner: TComponent); override; end; implementation {$R *.dfm} uses GX_dzVclUtils; { TfmIdxPackageRenameDlg } class function TfmIdxPackageRenameDlg.Execute(_Owner: TWinControl; const _fn: string; var _Description: string): Boolean; var frm: TfmIdxPackageRenameDlg; begin frm := TfmIdxPackageRenameDlg.Create(_Owner); try frm.SetData(_fn, _Description); Result := (frm.ShowModal = mrok); if Result then begin frm.GetData(_Description); end; finally FreeAndNil(frm); end; end; constructor TfmIdxPackageRenameDlg.Create(_Owner: TComponent); begin inherited; TControl_SetMinConstraints(Self); end; procedure TfmIdxPackageRenameDlg.GetData(out _Description: string); begin _Description := ed_Description.Text; end; procedure TfmIdxPackageRenameDlg.SetData(const _fn, _Description: string); begin l_PackageFn.Caption := _fn; ed_Description.Text := _Description; end; end.
unit GX_IdeSearchPathEnhancer; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, StdCtrls, Forms; type TGxIdeSearchPathEnhancer = class public class function GetEnabled: Boolean; class procedure SetEnabled(_Value: Boolean); end; implementation uses Windows, Controls, Menus, Buttons, ActnList, StrUtils, ComCtrls, GX_IdeFormEnhancer, GX_dzVclUtils, GX_dzFileUtils, GX_OtaUtils, GX_dzSelectDirectoryFix, GX_IdeSearchPathFavorites, GX_ConfigurationInfo; type ///<summary> /// defines the strings used to identify the search path edit dialog </summary> TSearchPathDlgStrings = record DialogClass: string; DialogName: string; DialogCaptionEn: string; DialogCaptionFr: string; DialogCaptionDe: string; end; type TSearchPathEnhancer = class private FCallbackHandle: TFormChangeHandle; FForm: TCustomForm; FListbox: TListbox; FMemo: TMemo; FPageControl: TPageControl; FTabSheetList: TTabSheet; FTabSheetMemo: TTabSheet; FEdit: TEdit; FUpClick: TNotifyEvent; FDownClick: TNotifyEvent; FUpBtn: TCustomButton; FDownBtn: TCustomButton; FDeleteBtn: TCustomButton; FDeleteInvalidBtn: TCustomButton; FReplaceBtn: TCustomButton; FAddBtn: TCustomButton; FMakeRelativeBtn: TButton; FMakeAbsoluteBtn: TButton; FAddRecursiveBtn: TButton; FFavoritesPm: TPopupMenu; FFavoritesBtn: TButton; FFavorites: TStringList; FEnabled: Boolean; {$IFNDEF GX_VER300_up} FBrowseBtn: TCustomButton; FBrowseClick: TNotifyEvent; procedure BrowseBtnClick(_Sender: TObject); {$ENDIF GX_VER300_up} procedure HandleFilesDropped(_Sender: TObject; _Files: TStrings); ///<summary> /// frm can be nil </summary> procedure HandleFormChanged(_Sender: TObject; _Form: TCustomForm); function IsSearchPathForm(_Form: TCustomForm): Boolean; function TryGetElementEdit(_Form: TCustomForm; out _ed: TEdit): Boolean; procedure HandleMemoChange(_Sender: TObject); procedure UpBtnClick(_Sender: TObject); procedure DownBtnClick(_Sender: TObject); procedure AddBtnClick(_Sender: TObject); procedure PageControlChanging(_Sender: TObject; var AllowChange: Boolean); procedure MakeRelativeBtnClick(_Sender: TObject); procedure MakeAbsoluteBtnClick(_Sender: TObject); procedure AddRecursiveBtnClick(_Sender: TObject); function MatchesDlg(_Form: TCustomForm; _Strings: TSearchPathDlgStrings): Boolean; procedure FavoritesBtnClick(_Sender: TObject); procedure FavoritesPmConfigureClick(_Sender: TObject); procedure InitFavoritesMenu; procedure FavoritesPmHandleFavoriteClick(_Sender: TObject); procedure SetEnabled(const Value: Boolean); procedure LoadSettings; procedure SaveSettings; function ConfigurationKey: string; procedure PageControlChange(_Sender: TObject); public constructor Create; destructor Destroy; override; property Enabled: Boolean read FEnabled write SetEnabled; end; var TheSearchPathEnhancer: TSearchPathEnhancer = nil; { TGxIdeSearchPathEnhancer } class function TGxIdeSearchPathEnhancer.GetEnabled: Boolean; begin Result := Assigned(TheSearchPathEnhancer) and TheSearchPathEnhancer.Enabled; end; class procedure TGxIdeSearchPathEnhancer.SetEnabled(_Value: Boolean); begin if not _Value then begin if Assigned(TheSearchPathEnhancer) then TheSearchPathEnhancer.Enabled := False; end else begin if not Assigned(TheSearchPathEnhancer) then TheSearchPathEnhancer := TSearchPathEnhancer.Create; TheSearchPathEnhancer.Enabled := True; end; end; { TSearchPathEnhancer } constructor TSearchPathEnhancer.Create; begin inherited Create; FFavorites := TStringList.Create; LoadSettings; // FFavorites.Values['jvcl'] := '..\libs\jvcl\common;..\libs\jvcl\run;..\libs\jvcl\resources'; // FFavorites.Values['jcl'] := '..\libs\jcl\source\include;..\libs\jcl\source\include\jedi;..\libs\jcl\source\common;..\libs\jcl\source\windows;..\libs\jcl\source\vcl'; end; destructor TSearchPathEnhancer.Destroy; begin TIDEFormEnhancements.UnregisterFormChangeCallback(FCallbackHandle); FreeAndNil(FFavorites); inherited; end; function TSearchPathEnhancer.ConfigurationKey: string; begin Result := 'IDEEnhancements'; end; procedure TSearchPathEnhancer.LoadSettings; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin ExpSettings := nil; Settings := TGExpertsSettings.Create; try ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); ExpSettings.ReadStrings('SearchPathFavorites', FFavorites); finally FreeAndNil(ExpSettings); FreeAndNil(Settings); end; end; procedure TSearchPathEnhancer.SaveSettings; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin Assert(ConfigInfo <> nil, 'No ConfigInfo found'); // do not localize any of the below items ExpSettings := nil; Settings := TGExpertsSettings.Create; try ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); ExpSettings.WriteStrings('SearchPathFavorites', FFavorites); finally FreeAndNil(ExpSettings); FreeAndNil(Settings); end; end; procedure TSearchPathEnhancer.HandleFilesDropped(_Sender: TObject; _Files: TStrings); var frm: TCustomForm; begin frm := Screen.ActiveCustomForm; if not IsSearchPathForm(frm) then Exit; if _Sender is TEdit then TEdit(_Sender).Text := _Files[0] else if _Sender is TMemo then TMemo(_Sender).Lines.AddStrings(_Files) else if _Sender is TListbox then TListbox(_Sender).Items.AddStrings(_Files); end; function TSearchPathEnhancer.TryGetElementEdit(_Form: TCustomForm; out _ed: TEdit): Boolean; var cmp: TComponent; begin Result := False; cmp := _Form.FindComponent('ElementEdit'); if not Assigned(cmp) then Exit; if not (cmp is TEdit) then Exit; _ed := cmp as TEdit; Result := True; end; // SearchPathDialogClassArr: TSearchPathDialogClassArr = ( // 'TInheritedListEditDlg', 'TInheritedListEditDlg', 'TOrderedListEditDlg' {$IFDEF GX_VER300_up} // Delphi 10 and up const ProjectSearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TInheritedListEditDlg'; DialogName: 'InheritedListEditDlg'; DialogCaptionEn: 'Search Path'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); const LibrarySearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TOrderedListEditDlg'; DialogName: 'OrderedListEditDlg'; DialogCaptionEn: 'Directories'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); {$ELSE GX_VER300_up} {$IFDEF GX_VER220_up} // Delphi XE and up const ProjectSearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TInheritedListEditDlg'; DialogName: 'InheritedListEditDlg'; DialogCaptionEn: 'Search Path'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); const LibrarySearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TOrderedListEditDlg'; DialogName: 'OrderedListEditDlg'; DialogCaptionEn: 'Directories'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); {$ELSE GX_VER220_up} {$IFDEF GX_VER200_up} // Delphi 2009 and up const ProjectSearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TInheritedListEditDlg'; DialogName: 'InheritedListEditDlg'; DialogCaptionEn: 'Search Path'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); const LibrarySearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TOrderedListEditDlg'; DialogName: 'OrderedListEditDlg'; DialogCaptionEn: 'Directories'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); {$ELSE GX_VER200_up} // Delphi 2007 and earlier const ProjectSearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TOrderedListEditDlg'; DialogName: 'OrderedListEditDlg'; DialogCaptionEn: 'Search Path'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); const LibrarySearchPathDlg: TSearchPathDlgStrings = ( DialogClass: 'TOrderedListEditDlg'; DialogName: 'OrderedListEditDlg'; DialogCaptionEn: 'Directories'; DialogCaptionFr: 'Chemin de recherche'; DialogCaptionDe: 'Verzeichnisse'; ); {$ENDIF GX_VER200_up} {$ENDIF GX_VER220_up} {$ENDIF GX_VER300_up} function TSearchPathEnhancer.MatchesDlg(_Form: TCustomForm; _Strings: TSearchPathDlgStrings): Boolean; begin Result := False; if not SameText(_Form.ClassName, _Strings.DialogClass) then Exit; //==> if not SameText(_Form.Name, _Strings.DialogName) then Exit; //==> if not SameText(_Form.Caption, _Strings.DialogCaptionEn) and not SameText(_Form.Caption, _Strings.DialogCaptionFr) and not SameText(_Form.Caption, _Strings.DialogCaptionDe) then Exit; Result := True; end; function TSearchPathEnhancer.IsSearchPathForm(_Form: TCustomForm): Boolean; begin if Assigned(_Form) then begin Result := True; if MatchesDlg(_Form, ProjectSearchPathDlg) then Exit; //==> if MatchesDlg(_Form, LibrarySearchPathDlg) then Exit; //==> end; Result := False; end; type TCustomButtonHack = class(TCustomButton) end; procedure TSearchPathEnhancer.HandleFormChanged(_Sender: TObject; _Form: TCustomForm); var TheActionList: TActionList; function TryFindBitBtn(const _BtnName: string; out _Btn: TCustomButton): Boolean; var cmp: TComponent; begin cmp := _Form.FindComponent(_BtnName); Result := Assigned(cmp) and (cmp is TBitBtn); if Result then _Btn := cmp as TBitBtn; end; function TryFindButton(const _BtnName: string; out _Btn: TCustomButton): Boolean; var cmp: TComponent; begin cmp := _Form.FindComponent(_BtnName); Result := Assigned(cmp) and (cmp is TButton); if Result then _Btn := cmp as TButton else _Btn := nil; end; procedure AssignActionToButton(const _BtnName: string; const _Caption: string; _OnExecute: TNotifyEvent; _Shortcut: TShortCut; out _Btn: TCustomButton; out _OnClick: TNotifyEvent); var act: TAction; begin // Unfortunately we can't just assign the button's OnClick event to the // OnExecute event of the action because Delphi apparently assigns the // same event to both buttons and then checks which one was pressed // by inspecting the Sender parameter. So, instead we save the OnClick // event, assign our own event to OnExecute and there call the original // OnClick event with the original Sender parameter. if TryFindBitBtn(_BtnName, _Btn) or TryFindButton(_BtnName, _Btn) then begin _OnClick := TCustomButtonHack(_Btn).OnClick; act := TActionlist_Append(TheActionList, '', _OnExecute, _Shortcut); act.Hint := _Caption; _Btn.Action := act; _Btn.ShowHint := True; end; end; var cmp: TComponent; btn: TCustomButton; begin if not FEnabled then Exit; if not IsSearchPathForm(_Form) or not TryGetElementEdit(_Form, FEdit) then Exit; if _Form.FindComponent('TheActionList') = nil then begin FForm := _Form; TEdit_ActivateAutoComplete(FEdit, [acsFileSystem], [actSuggest]); TWinControl_ActivateDropFiles(FEdit, HandleFilesDropped); cmp := _Form.FindComponent('CreationList'); if Assigned(cmp) and (cmp is TListbox) then begin FListbox := TListbox(cmp); TheActionList := TActionList.Create(_Form); TheActionList.Name := 'TheActionList'; // Assign shortcuts to the Up/Down buttons via actions AssignActionToButton('UpButton', 'Move Up', UpBtnClick, ShortCut(VK_UP, [ssCtrl]), FUpBtn, FUpClick); AssignActionToButton('DownButton', 'Move Down', DownBtnClick, ShortCut(VK_DOWN, [ssCtrl]), FDownBtn, FDownClick); {$IFNDEF GX_VER300_up} // Delphi 10 and later no longer uses SelectDirectory, so we don't need to fix it. AssignActionToButton('BrowseButton', 'Browse', BrowseBtnClick, ShortCut(VK_DOWN, [ssAlt]), FBrowseBtn, FBrowseClick); {$ENDIF GX_VER300_up} TWinControl_ActivateDropFiles(FListbox, HandleFilesDropped); FPageControl := TPageControl.Create(_Form); FTabSheetList := TTabSheet.Create(_Form); FTabSheetMemo := TTabSheet.Create(_Form); FPageControl.Name := 'pc_PathList'; FPageControl.Parent := _Form; FPageControl.BoundsRect := FListbox.BoundsRect; FPageControl.Anchors := [akLeft, akTop, akRight, akBottom]; FPageControl.TabPosition := tpBottom; FPageControl.ActivePage := FTabSheetList; FPageControl.OnChange := PageControlChange; FPageControl.OnChanging := PageControlChanging; FTabSheetList.Name := 'ts_List'; FTabSheetList.Parent := FPageControl; FTabSheetList.PageControl := FPageControl; FTabSheetList.Caption := '&List'; FTabSheetMemo.Name := 'ts_Memo'; FTabSheetMemo.Parent := FPageControl; FTabSheetMemo.PageControl := FPageControl; FTabSheetMemo.Caption := '&Memo'; FMemo := TMemo.Create(_Form); FMemo.Parent := FTabSheetMemo; FMemo.Align := alClient; FMemo.Lines.Text := FListbox.Items.Text; FMemo.OnChange := Self.HandleMemoChange; FMemo.ScrollBars := ssBoth; FMemo.WordWrap := False; FListbox.Parent := FTabSheetList; FListbox.Align := alClient; if Assigned(FUpBtn) then begin FFavoritesBtn := TButton.Create(_Form); FFavoritesBtn.Parent := _Form; FFavoritesBtn.Left := FUpBtn.Left; FFavoritesBtn.Top := FPageControl.Top; FFavoritesBtn.Width := FUpBtn.Width; FFavoritesBtn.Height := FUpBtn.Height; FFavoritesBtn.Anchors := [akRight, akTop]; FFavoritesBtn.Caption := '&Fav'; FFavoritesBtn.OnClick := FavoritesBtnClick; FFavoritesBtn.TabOrder := FPageControl.TabOrder + 1; FFavoritesBtn.Visible := False; FFavoritesPm := TPopupMenu.Create(_Form); InitFavoritesMenu; end; TWinControl_ActivateDropFiles(FMemo, HandleFilesDropped); if TryFindButton('AddButton', FAddBtn) then begin TCustomButtonHack(FAddBtn).OnClick := AddBtnClick; end; if TryFindButton('ReplaceButton', FReplaceBtn) then begin FMakeRelativeBtn := TButton.Create(_Form); FMakeRelativeBtn.Name := 'MakeRelativeBtn'; FMakeRelativeBtn.Parent := FReplaceBtn.Parent; FMakeRelativeBtn.BoundsRect := FReplaceBtn.BoundsRect; FMakeRelativeBtn.Anchors := [akRight, akBottom]; FMakeRelativeBtn.Caption := 'Make Relative'; FMakeRelativeBtn.Visible := False; FMakeRelativeBtn.OnClick := MakeRelativeBtnClick; end; if TryFindButton('DeleteButton', FDeleteBtn) then begin FMakeAbsoluteBtn := TButton.Create(_Form); FMakeAbsoluteBtn.Name := 'MakeAbsoluteBtn'; FMakeAbsoluteBtn.Parent := FDeleteBtn.Parent; FMakeAbsoluteBtn.BoundsRect := FDeleteBtn.BoundsRect; FMakeAbsoluteBtn.Anchors := [akRight, akBottom]; FMakeAbsoluteBtn.Caption := 'Make Absolute'; FMakeAbsoluteBtn.Visible := False; FMakeAbsoluteBtn.OnClick := MakeAbsoluteBtnClick; end; if TryFindButton('DeleteInvalidBtn', FDeleteInvalidBtn) then begin FAddRecursiveBtn := TButton.Create(_Form); FAddRecursiveBtn.Name := 'AddRecursiveBtn'; FAddRecursiveBtn.Parent := FDeleteInvalidBtn.Parent; FAddRecursiveBtn.BoundsRect := FDeleteInvalidBtn.BoundsRect; FAddRecursiveBtn.Anchors := [akRight, akBottom]; FAddRecursiveBtn.Caption := 'Add Recursive'; FAddRecursiveBtn.Visible := False; FAddRecursiveBtn.OnClick := AddRecursiveBtnClick; end; if TryFindButton('OkButton', btn) then TCustomButtonHack(btn).Caption := '&OK'; cmp := _Form.FindComponent('InvalidPathLbl'); if cmp is TLabel then TLabel(cmp).Caption := TLabel(cmp).Caption + ' Drag and drop is enabled.'; end; end; end; procedure TSearchPathEnhancer.InitFavoritesMenu; var i: Integer; mi: TMenuItem; FavName: string; begin FFavoritesPm.Items.Clear; for i := 0 to FFavorites.Count - 1 do begin FavName := FFavorites.Names[i]; mi := TPopupMenu_AppendMenuItem(FFavoritesPm, FavName, FavoritesPmHandleFavoriteClick); mi.Tag := i + 1; end; TPopupMenu_AppendMenuItem(FFavoritesPm, 'Configure ...', FavoritesPmConfigureClick); end; procedure TSearchPathEnhancer.FavoritesBtnClick(_Sender: TObject); var pnt: TPoint; begin pnt := FFavoritesBtn.ClientToScreen(Point(0, FFavoritesBtn.Height)); FFavoritesPm.Popup(pnt.X, pnt.Y); end; procedure TSearchPathEnhancer.FavoritesPmConfigureClick(_Sender: TObject); begin Tf_SarchPathFavorites.Execute(FForm, FFavorites); SaveSettings; InitFavoritesMenu; end; procedure TSearchPathEnhancer.FavoritesPmHandleFavoriteClick(_Sender: TObject); var mi: TMenuItem; sl: TStringList; FavName: string; begin mi := _Sender as TMenuItem; sl := TStringList.Create; try FavName := FFavorites.Names[mi.Tag - 1]; sl.Delimiter := ';'; sl.DelimitedText := FFavorites.Values[FavName]; if FPageControl.ActivePage = FTabSheetList then FListbox.Items.AddStrings(sl) else FMemo.Lines.AddStrings(sl); finally FreeAndNil(sl); end; end; {$IFNDEF GX_VER170_up} function StartsText(const ASubText, AText: string): Boolean; var P: PChar; L, L2: Integer; begin P := PChar(AText); L := Length(ASubText); L2 := Length(AText); if L > L2 then Result := False else Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, P, L, PChar(ASubText), L) = 2; end; {$ENDIF} procedure TSearchPathEnhancer.MakeAbsoluteBtnClick(_Sender: TObject); var i: Integer; ProjectFile: string; ProjectDir: string; AbsoluteDir: string; RelativeDir: string; begin ProjectFile := GxOtaGetCurrentProjectFileName(True); if ProjectFile = '' then Exit; //==> ProjectDir := ExtractFilePath(ProjectFile); FMemo.Lines.BeginUpdate; try for i := 0 to FMemo.Lines.Count - 1 do begin RelativeDir := FMemo.Lines[i]; if not StartsText('$(BDS)\', RelativeDir) then begin AbsoluteDir := TFileSystem.ExpandFileNameRelBaseDir(RelativeDir, ProjectDir); FMemo.Lines[i] := AbsoluteDir; end; end; RelativeDir := FEdit.Text; if not StartsText('$(BDS)\', RelativeDir) then begin AbsoluteDir := TFileSystem.ExpandFileNameRelBaseDir(RelativeDir, ProjectDir); FEdit.Text := AbsoluteDir; end; finally FMemo.Lines.EndUpdate; end; end; procedure TSearchPathEnhancer.MakeRelativeBtnClick(_Sender: TObject); var i: Integer; ProjectFile: string; ProjectDir: string; AbsoluteDir: string; RelativeDir: string; begin ProjectFile := GxOtaGetCurrentProjectFileName(True); if ProjectFile = '' then Exit; //==> ProjectDir := ExtractFilePath(ProjectFile); FMemo.Lines.BeginUpdate; try for i := 0 to FMemo.Lines.Count - 1 do begin AbsoluteDir := FMemo.Lines[i]; if not StartsText('$(BDS)\', AbsoluteDir) then begin RelativeDir := ExtractRelativePath(IncludeTrailingPathDelimiter(ProjectDir), AbsoluteDir); FMemo.Lines[i] := RelativeDir; end; end; AbsoluteDir := FEdit.Text; if not StartsText('$(BDS)\', AbsoluteDir) then begin RelativeDir := ExtractRelativePath(IncludeTrailingPathDelimiter(ProjectDir), AbsoluteDir); FEdit.Text := RelativeDir; end; finally FMemo.Lines.EndUpdate; end; end; procedure TSearchPathEnhancer.AddRecursiveBtnClick(_Sender: TObject); var Dirs: TStringList; i: Integer; RecurseIdx: Integer; begin if FEdit.Text = '' then Exit; Dirs := TStringList.Create; try TSimpleDirEnumerator.EnumDirsOnly(FEdit.Text + '\*', Dirs, True); for i := Dirs.Count - 1 downto 0 do begin if AnsiStartsStr('.', Dirs[i]) then Dirs.Delete(i); end; RecurseIdx := 0; while RecurseIdx < Dirs.Count do begin TSimpleDirEnumerator.EnumDirsOnly(Dirs[RecurseIdx] + '\*', Dirs, True); for i := Dirs.Count - 1 downto 0 do begin if AnsiStartsStr('.', Dirs[i]) then Dirs.Delete(i); end; Inc(RecurseIdx); end; FMemo.Lines.AddStrings(Dirs); finally FreeAndNil(Dirs); end; end; procedure TSearchPathEnhancer.PageControlChanging(_Sender: TObject; var AllowChange: Boolean); var SwitchingToMemo: Boolean; begin SwitchingToMemo := (FPageControl.ActivePage = FTabSheetList); if SwitchingToMemo then begin FMemo.Lines.Text := FListbox.Items.Text; FMemo.CaretPos := Point(FMemo.CaretPos.X, FListbox.ItemIndex); end else begin FListbox.ItemIndex := FMemo.CaretPos.Y; end; end; procedure TSearchPathEnhancer.PageControlChange(_Sender: TObject); procedure TrySetButtonVisibility(_Btn: TCustomButton; _Visible: Boolean); begin if Assigned(_Btn) then _Btn.Visible := _Visible; end; var SwitchedToMemo: Boolean; begin SwitchedToMemo := (FPageControl.ActivePage = FTabSheetMemo); TrySetButtonVisibility(FFavoritesBtn, SwitchedToMemo); TrySetButtonVisibility(FDeleteBtn, not SwitchedToMemo); TrySetButtonVisibility(FMakeAbsoluteBtn, SwitchedToMemo); TrySetButtonVisibility(FDeleteInvalidBtn, not SwitchedToMemo); TrySetButtonVisibility(FAddRecursiveBtn, SwitchedToMemo); TrySetButtonVisibility(FReplaceBtn, not SwitchedToMemo); TrySetButtonVisibility(FMakeRelativeBtn, SwitchedToMemo); end; procedure TSearchPathEnhancer.SetEnabled(const Value: Boolean); begin FEnabled := Value; if FEnabled then begin if not Assigned(FCallbackHandle) then FCallbackHandle := TIDEFormEnhancements.RegisterFormChangeCallback(HandleFormChanged) end; end; procedure TSearchPathEnhancer.UpBtnClick(_Sender: TObject); var LineIdx: Integer; Pos: TPoint; begin if FPageControl.ActivePage = FTabSheetMemo then begin Pos := FMemo.CaretPos; LineIdx := Pos.Y; if LineIdx > 0 then FMemo.Lines.Exchange(LineIdx - 1, LineIdx); FMemo.SetFocus; Pos.Y := Pos.Y - 1; FMemo.CaretPos := Pos; end else FUpClick(FUpBtn); end; procedure TSearchPathEnhancer.DownBtnClick(_Sender: TObject); var LineIdx: Integer; begin if FPageControl.ActivePage = FTabSheetMemo then begin LineIdx := FMemo.CaretPos.Y; if LineIdx < FMemo.Lines.Count - 1 then FMemo.Lines.Exchange(LineIdx, LineIdx + 1); FMemo.SetFocus; end else FDownClick(FDownBtn); end; procedure TSearchPathEnhancer.AddBtnClick(_Sender: TObject); var Idx: Integer; begin if FPageControl.ActivePage = FTabSheetMemo then begin FMemo.Lines.Add(FEdit.Text); end else begin Idx := FListbox.Items.Add(FEdit.Text); // In order to prevent adding the path twice, we need to select the new entry and // call the OnClick event. FListbox.ItemIndex := Idx; FListbox.OnClick(FListbox); end; end; {$IFNDEF GX_VER300_up} procedure TSearchPathEnhancer.BrowseBtnClick(_Sender: TObject); var ProjectFile: string; ProjectDir: string; Dir: string; begin Dir := FEdit.Text; ProjectFile := GxOtaGetCurrentProjectFileName(True); if ProjectFile <> '' then begin ProjectDir := ExtractFilePath(ProjectFile); Dir := TFileSystem.ExpandFileNameRelBaseDir(Dir, ProjectDir); end; if dzSelectDirectory(FBrowseBtn.Hint, '', Dir, FBrowseBtn) then FEdit.Text := Dir; end; {$ENDIF GX_VER300_up} procedure TSearchPathEnhancer.HandleMemoChange(_Sender: TObject); begin if Assigned(FListbox) and Assigned(FMemo) then FListbox.Items := FMemo.Lines; end; initialization TheSearchPathEnhancer := TSearchPathEnhancer.Create; finalization FreeAndNil(TheSearchPathEnhancer); end.
unit DW.Androidapi.JNI.SystemClock; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses Androidapi.JNIBridge, Androidapi.JNI.JavaTypes; type JSystemClock = interface; JSystemClockClass = interface(JObjectClass) ['{771C5E34-6252-4BA7-8292-DD6BC82AA9B8}'] {class} function currentThreadTimeMillis: Int64; cdecl; {class} function elapsedRealtime: Int64; cdecl; {class} function elapsedRealtimeNanos: Int64; cdecl; {class} function setCurrentTimeMillis(millis: Int64): Boolean; cdecl; {class} procedure sleep(ms: Int64); cdecl; {class} function uptimeMillis: Int64; cdecl; end; [JavaSignature('android/os/SystemClock')] JSystemClock = interface(JObject) ['{6F88CF0F-2D6B-43D4-A23D-A04C1C56D88E}'] end; TJSystemClock = class(TJavaGenericImport<JSystemClockClass, JSystemClock>) end; implementation end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.0 15/04/2005 7:25:02 AM GGrieve first ported to INdy } unit IdASN1Coder; interface {$i IdCompilerDefines.inc} uses Classes, Contnrs; type TIdASN1IdentifierType = (aitUnknown, aitSequence, aitBoolean, aitInteger, aitEnum, aitString, aitOID, aitReal); TIdASN1IdentifierClass = (aicUniversal, aicApplication, aicContextSpecific, aicPrivate); TIdASN1Identifier = record Position : Integer; IdClass : TIdASN1IdentifierClass; Constructed : Boolean; TagValue : Integer; TagType : TIdASN1IdentifierType; ContentLength : integer; end; TIdASN1Sequence = Class Private FIdClass : TIdASN1IdentifierClass; FTag : Integer; FContents : String; Public Property IdClass : TIdASN1IdentifierClass Read FIdClass Write FIdClass; Property Tag : integer Read FTag Write FTag; Property Contents : String Read FContents Write FContents; End; TIdASN1Sequences = Class(TObjectList) Private Function GetElement(Const iIndex : Integer) : TIdASN1Sequence; function GetLast: TIdASN1Sequence; Public Property LastElement : TIdASN1Sequence read GetLast; procedure Pop; Property Elements[Const iIndex : Integer] : TIdASN1Sequence Read GetElement; Default; End; TIdASN1Encoder = class private FSequences : TIdASN1Sequences; FReadyToWrite : Boolean; function FormatEncoding(aClass : TIdASN1IdentifierClass; bConstructed : Boolean; iTag : integer; const sContent : String) : String; procedure AddEncoding(const sContent : String); procedure WriteInt(iTag : integer; iValue : integer); function EncodeLength(iLen : Integer):String; protected // must call this as an outer wrapper Procedure StartWriting; Procedure StopWriting; // sequences procedure StartSequence; overload; procedure StartSequence(iTag : Integer); overload; procedure StartSequence(aClass : TIdASN1IdentifierClass; iTag : Integer); overload; procedure StopSequence; // primitives procedure WriteBoolean(bValue : Boolean); procedure WriteInteger(iValue : Integer); procedure WriteEnum(iValue : Integer); procedure WriteString(sValue : String); overload; procedure WriteString(iTag : integer; sValue : String); overload; public Constructor Create; destructor Destroy; override; procedure WriteToStream(Stream : TStream); end; TIntegerList = class (TList) private function GetValue(iIndex: integer): Integer; procedure SetValue(Index: integer; const Value: Integer); public procedure AddInt(value : integer); procedure InsertInt(Index, Value : integer); property Value[iIndex : integer]:Integer read GetValue write SetValue; default; end; TIdASN1Decoder = class private FLengths : TIntegerList; FPosition : Integer; FNextHeader : TIdASN1Identifier; FNextHeaderUsed : Boolean; FStream: TStream; function ReadHeader : TIdASN1Identifier; // -1 in length means that no definite length was specified function DescribeIdentifier(const aId : TIdASN1Identifier) : String; Function ReadByte : Byte; function ReadChar : Char; function ReadContentLength : Integer; protected procedure Check(bCondition : Boolean; const sMethod, sMessage : String); overload; virtual; // must call this as an outer wrapper Procedure StartReading; Procedure StopReading; // sequences and choices procedure ReadSequenceBegin; function SequenceEnded : Boolean; procedure ReadSequenceEnd; function NextTag : integer; function NextTagType : TIdASN1IdentifierType; // primitives function ReadBoolean : Boolean; Function ReadInteger : Integer; function ReadEnum : Integer; Function ReadString : String; public Constructor Create; destructor Destroy; override; property Stream : TStream read FStream write FStream; end; const NAMES_ASN1IDENTIFIERTYPE : array [TIdASN1IdentifierType] of String = ('Unknown', 'Sequence', 'Boolean', 'Integer', 'Enum', 'String', 'OID', 'Real'); TAGS_ASN1IDENTIFIERTYPE : array [TIdASN1IdentifierType] of Integer = (0, $10, $01, $02, $0A, $04, $06, 0 {?}); NAMES_ASN1IDENTIFIERCLASS : array [TIdASN1IdentifierClass] of String = ('Universal', 'Application', 'ContextSpecific', 'Private'); function ToIdentifierType(iTag : integer) : TIdASN1IdentifierType; implementation uses IdException, SysUtils; function ToIdentifierType(iTag : integer) : TIdASN1IdentifierType; begin case iTag of $10 : result := aitSequence; $01 : result := aitBoolean; $02 : result := aitInteger; $04 : result := aitString; $06 : result := aitOID; $0A : result := aitEnum; else result := aitUnknown; end; end; { TIdASN1Encoder } constructor TIdASN1Encoder.Create; begin inherited Create; FSequences := TIdASN1Sequences.create; end; destructor TIdASN1Encoder.Destroy; begin FSequences.Free; inherited Destroy; end; procedure TIdASN1Encoder.WriteToStream(Stream : TStream); begin assert(FReadyToWrite, 'not ready to write'); if length(FSequences[0].Contents[1]) <> 0 then Stream.Write(FSequences[0].Contents[1], length(FSequences[0].Contents[1])); end; procedure TIdASN1Encoder.StartWriting; begin FSequences.Clear; StartSequence(aicUniversal, 0); end; procedure TIdASN1Encoder.StopWriting; begin assert(FSequences.Count = 1, 'Writing left an open Sequence'); FReadyToWrite := true; // todo - actually commit to stream Produce(Fsequences[0].Contents); end; procedure TIdASN1Encoder.StartSequence(aClass: TIdASN1IdentifierClass; iTag: Integer); var oSequence : TIdASN1Sequence; begin oSequence := TIdASN1Sequence.create; try oSequence.IdClass := aClass; oSequence.Tag := iTag; oSequence.Contents := ''; FSequences.add(oSequence); finally oSequence.Free; end; end; procedure TIdASN1Encoder.StartSequence(iTag: Integer); begin if iTag = -1 then StartSequence(aicUniversal, TAGS_ASN1IDENTIFIERTYPE[aitSequence]) else StartSequence(aicApplication, iTag); end; procedure TIdASN1Encoder.StartSequence; begin StartSequence(aicUniversal, TAGS_ASN1IDENTIFIERTYPE[aitSequence]); end; procedure TIdASN1Encoder.StopSequence; var sSequence : String; begin sSequence := FormatEncoding(FSequences.LastElement.IdClass, true, FSequences.LastElement.Tag, FSequences.LastElement.Contents); FSequences.Pop; AddEncoding(sSequence); end; procedure TIdASN1Encoder.WriteBoolean(bValue: Boolean); begin // RLebeau 1/7/09: using Char() for #128-#255 because in D2009, the compiler // may change characters >= #128 from their Ansi codepage value to their true // Unicode codepoint value, depending on the codepage used for the source code. // For instance, #128 may become #$20AC... if bValue then AddEncoding(FormatEncoding(aicUniversal, False, TAGS_ASN1IDENTIFIERTYPE[aitBoolean], Char($FF))) else AddEncoding(FormatEncoding(aicUniversal, False, TAGS_ASN1IDENTIFIERTYPE[aitBoolean], #$00)); end; procedure TIdASN1Encoder.WriteEnum(iValue: Integer); begin WriteInt(TAGS_ASN1IDENTIFIERTYPE[aitEnum], iValue); end; procedure TIdASN1Encoder.WriteInteger(iValue: Integer); begin WriteInt(TAGS_ASN1IDENTIFIERTYPE[aitInteger], iValue); end; procedure TIdASN1Encoder.WriteInt(iTag, iValue: integer); var sValue : String; x, y: Cardinal; bNeg: Boolean; begin bNeg := iValue < 0; x := Abs(iValue); if bNeg then x := not (x - 1); sValue := ''; {Do not Localize} repeat y := x mod 256; x := x div 256; sValue := Char(y) + sValue; until x = 0; if (not bNeg) and (sValue[1] > #$7F) then sValue := #0 + sValue; AddEncoding(FormatEncoding(aicUniversal, False, iTag, sValue)) end; procedure TIdASN1Encoder.WriteString(sValue: String); begin AddEncoding(FormatEncoding(aicUniversal, False, TAGS_ASN1IDENTIFIERTYPE[aitString], sValue)) end; procedure TIdASN1Encoder.WriteString(iTag : integer; sValue: String); begin AddEncoding(FormatEncoding(aicContextSpecific, False, iTag, sValue)) end; procedure TIdASN1Encoder.AddEncoding(const sContent: String); begin FSequences.LastElement.Contents := FSequences.LastElement.Contents + sContent; end; function TIdASN1Encoder.FormatEncoding(aClass: TIdASN1IdentifierClass; bConstructed : Boolean; iTag: integer; const sContent: String): String; begin if bConstructed then result := chr((ord(aClass) shl 6) or $20 or iTag) + EncodeLength(length(sContent)) + sContent else result := chr((ord(aClass) shl 6) or iTag) + EncodeLength(length(sContent)) + sContent; end; function TIdASN1Encoder.EncodeLength(iLen: Integer): String; var x, y: Integer; begin if iLen < $80 then Result := Char(iLen) else begin x := iLen; Result := ''; repeat y := x mod 256; x := x div 256; Result := Char(y) + Result; until x = 0; y := Length(Result); y := y or $80; Result := Char(y) + Result; end; end; { TIdASN1Sequences } function TIdASN1Sequences.GetElement(const iIndex: Integer): TIdASN1Sequence; begin result := TIdASN1Sequence(items[iIndex]); end; function TIdASN1Sequences.GetLast: TIdASN1Sequence; begin if Count = 0 then result := nil else result := GetElement(Count - 1); end; procedure TIdASN1Sequences.Pop; begin if Count > 0 then Delete(Count-1); end; { TIdASN1Decoder } Constructor TIdASN1Decoder.Create; begin inherited Create; FLengths := TIntegerList.create; end; destructor TIdASN1Decoder.Destroy; begin FLengths.Free; Inherited Destroy; end; procedure TIdASN1Decoder.Check(bCondition: Boolean; const sMethod, sMessage: String); begin if not bCondition then raise EIdException.create(sMessage); end; Procedure TIdASN1Decoder.StartReading; begin FLengths.Clear; FLengths.AddInt(-1); FNextHeaderUsed := False; FPosition := 0; end; Procedure TIdASN1Decoder.StopReading; begin Check(FLengths.Count = 1, 'StopReading', 'Reading was incomplete'); FLengths.Clear; end; function TIdASN1Decoder.DescribeIdentifier(const aId : TIdASN1Identifier) : String; begin result := '[Pos '+IntToStr(aId.Position)+', Type '+NAMES_ASN1IDENTIFIERTYPE[aId.TagType]+', '+ 'Tag '+IntToStr(aId.TagValue)+', Class '+NAMES_ASN1IDENTIFIERCLASS[aId.IdClass]+']'; end; Function TIdASN1Decoder.ReadByte : Byte; begin Check(FLengths[0] <> 0, 'ReadByte', 'Attempt to read past end of Sequence'); Stream.Read(result, 1); inc(FPosition); FLengths[0] := FLengths[0] - 1; end; function TIdASN1Decoder.ReadChar : Char; begin result := Chr(readByte); end; function TIdASN1Decoder.ReadContentLength: Integer; var iNext : Byte; iLoop: Integer; begin iNext := ReadByte; if iNext < $80 then Result := iNext else begin Result := 0; iNext := iNext and $7F; if iNext = 0 then raise EIdException.create('Indefinite lengths are not yet handled'); for iLoop := 1 to iNext do begin Result := Result * 256; iNext := ReadByte; Result := Result + iNext; end; end; end; function TIdASN1Decoder.ReadHeader : TIdASN1Identifier; var iNext : Byte; begin if FNextHeaderUsed then begin result := FNextHeader; FNextHeaderUsed := False; end else begin FillChar(result, sizeof(TIdASN1Identifier), #0); result.Position := FPosition; iNext := ReadByte; result.Constructed := iNext and $20 > 0; result.IdClass := TIdASN1IdentifierClass(iNext shr 6); if iNext and $1F = $1F then begin raise EIdException.create('Todo'); end else result.TagValue := iNext and $1F; result.TagType := ToIdentifierType(result.TagValue); result.ContentLength := ReadContentLength; end; end; function TIdASN1Decoder.NextTag: integer; begin if not FNextHeaderUsed then begin FNextHeader := ReadHeader; FNextHeaderUsed := true; end; result := FNextHeader.TagValue; end; function TIdASN1Decoder.NextTagType: TIdASN1IdentifierType; begin if not FNextHeaderUsed then begin FNextHeader := ReadHeader; FNextHeaderUsed := true; end; result := FNextHeader.TagType; end; function TIdASN1Decoder.ReadBoolean : Boolean; var aId : TIdASN1Identifier; begin aId := ReadHeader; Check((aId.IdClass = aicApplication) or (aId.TagType = aitBoolean), 'ReadBoolean', 'Found '+DescribeIdentifier(aId)+' expecting a Boolean'); Check(aId.ContentLength = 1, 'ReadBoolean', 'Boolean Length should be 1'); result := ReadByte <> 0; end; Function TIdASN1Decoder.ReadInteger : Integer; var aId : TIdASN1Identifier; iVal : Integer; iNext : Byte; bNeg : Boolean; iLoop : integer; begin aId := ReadHeader; Check((aId.IdClass = aicApplication) or (aId.TagType = aitInteger), 'ReadInteger', 'Found '+DescribeIdentifier(aId)+' expecting an Integer'); Check(aId.ContentLength >= 1, 'ReadInteger', 'Boolean Length should not be 0'); iVal := 0; bNeg := False; for iLoop := 1 to aId.ContentLength do begin iNext := ReadByte; if (iLoop = 1) and (iNext > $7F) then bNeg := True; if bNeg then iNext := not iNext; iVal := iVal * 256 + iNext; end; if bNeg then iVal := -(iVal + 1); Result := iVal; end; function TIdASN1Decoder.ReadEnum : Integer; var aId : TIdASN1Identifier; iVal : Integer; iNext : Byte; bNeg : Boolean; iLoop : integer; begin aId := ReadHeader; Check((aId.IdClass = aicApplication) or (aId.TagType = aitEnum), 'ReadEnum', 'Found '+DescribeIdentifier(aId)+' expecting an Enum'); Check(aId.ContentLength >= 1, 'ReadEnum', 'Boolean Length should not be 0'); iVal := 0; bNeg := False; for iLoop := 1 to aId.ContentLength do begin iNext := ReadByte; if (iLoop = 1) and (iNext > $7F) then bNeg := True; if bNeg then iNext := not iNext; iVal := iVal * 256 + iNext; end; if bNeg then iVal := -(iVal + 1); Result := iVal; end; Function TIdASN1Decoder.ReadString : String; var aId : TIdASN1Identifier; iLoop : integer; begin aId := ReadHeader; Check((aId.IdClass = aicApplication) or (aId.TagType in [aitUnknown, aitString]), 'ReadString', 'Found '+DescribeIdentifier(aId)+' expecting a String'); SetLength(result, aId.ContentLength); for iLoop := 1 to aId.ContentLength do result[iLoop] := ReadChar; end; procedure TIdASN1Decoder.ReadSequenceBegin; var aId : TIdASN1Identifier; begin aId := ReadHeader; Check((aId.IdClass = aicApplication) or (aId.TagType in [aitUnknown, aitSequence]), 'ReadSequenceBegin', 'Found '+DescribeIdentifier(aId)+' expecting a Sequence'); FLengths[0] := FLengths[0] - aId.ContentLength; FLengths.InsertInt(0, aId.ContentLength); end; function TIdASN1Decoder.SequenceEnded: Boolean; begin Check(FLengths.Count > 1, 'SequenceEnded', 'Not in a Sequence'); result := FLengths[0] <= 0; end; procedure TIdASN1Decoder.ReadSequenceEnd; begin Check(SequenceEnded, 'ReadSequenceEnd', 'Sequence has not ended'); FLengths.Delete(0); end; { TIntegerList } procedure TIntegerList.AddInt(value: integer); begin Add(pointer(value)); end; function TIntegerList.GetValue(iIndex: integer): Integer; begin result := integer(items[iIndex]); end; procedure TIntegerList.InsertInt(Index, Value: integer); begin insert(Index, pointer(value)); end; procedure TIntegerList.SetValue(Index: integer; const Value: Integer); begin items[Index] := pointer(value); end; end.
program Control; uses DataTypes, Crt, Generics, Streams, Dos, Graph, GAPI; const efSTRINGCUT = $0001; efUSERBREAK = $0002; efREACHLIMIT = $0004; efUNKNOWN = $0008; efEXTERNALSTOP = $0010; efRESERVED1 = $0020; efRESERVED2 = $0040; efRESERVED3 = $0080; efRESERVED4 = $0100; efRESERVED5 = $0200; efRESERVED6 = $0400; efRESERVED7 = $0800; efRESERVED8 = $1000; efRESERVEDMASK = $1FE0; efJUMPERRORMASK = efSTRINGCUT or efUSERBREAK or efREACHLIMIT or efUNKNOWN or efRESERVEDMASK or efEXTERNALSTOP; efMOVEERRORMASK = efUSERBREAK or efUNKNOWN or efRESERVEDMASK; efRESETPOSERRORMASK = efUSERBREAK or efUNKNOWN or efRESERVEDMASK; errNONE = 0; errSTRINGCUT = 1; errREACHLIMIT = 2; errUSERBREAK = 3; errCOMMANDBREAK = 4; errEXTERNALSTOP = 5; errUNKNOWN = -1; lmtLOX = $04; lmtHIX = $02; lmtLOY = $10; lmtHIY = $08; FASTJUMPLIMIT = 50; JUMPSBEFORESLOWACTIVE = 5; STARTUPDOWNCOUNT = 5; MAXWAITTESTS = 100000; prtINIT1 = $030B; prtINIT2 = $030F; prtXMOVE = $030C; prtYMOVE = $030D; prtCONTR = $030A; prtTEST1 = $0308; prtTEST2 = $0309; const Color: Integer = 1; NidleUp: Boolean = True; type PSendData = ^TSendData; PBookMark = ^TBookMark; TBookMark = object(TGeneric) Info: TBookMarkInfo; constructor Create; end; TSendData = object(TGeneric) private Data: TJumpTableCollection; public OffsetX, OffsetY: Longint; Width, Height: Longint; constructor Create; destructor Destroy; virtual; procedure Clear; virtual; function LoadDataFromStream(AStream: PStream): Boolean; procedure ProcessDistanceJumps(ASlowLength: Integer); virtual; function IsFirst: Boolean; virtual; function IsLast: Boolean; virtual; function GetCurrent( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; virtual; function GetFirst( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; virtual; function GetLast( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; virtual; function GetNext( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; virtual; function GetPrev( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; virtual; function MoveToFirst: Boolean; virtual; function MoveToLast: Boolean; virtual; function MoveToNext: Boolean; virtual; function MoveToPrev: Boolean; virtual; function GetBookMark: PBookMark; virtual; function GetCurrentIndex: Longint; virtual; function GotoBookMark( ABookMark: PBookMark): Boolean; virtual; function GetNumCommands: Longint; end; PViewPort = ^TViewPort; PMachine = ^TMachine; TMachine = object(TGeneric) private OutputPort: PViewPort; LimitsErrorOcred: Boolean; { Switched to True if limits reached at normal work state (not in pos. rest operation) } UserBreakOcured: Boolean; { Switched to True if detected ESC key down while testing error, and rested to False at the first call of ~Jump~ or ~Move~ or any extrenal Method } ExternalBreakOcured: Boolean; LastCntrolOut: Byte; { Keeps the last control byte sended to machine and used to detect machine working states } function IsEngineWorks: Boolean; { Test one bit of ~LastCntrolOut~ variable } function SwitchEngineOn: Boolean; { Sends Engine whitch on command and wait nidle move from up to down, if no motion detected it outs engine switch off command and return false } function SwitchEngineOff: Boolean; { Waits for nidle up state and out engine switch off command, if not matched nidle up state is return false, but the switch off command sended in all cases } function IsSlowMode: Boolean; { it tests only the ~LastCntrolOut~ variable and return result accordingly } function SwitchToNormalMode: Boolean; { Outs the normal speed command only } function SwitchToSlowMode(AWaitForSlow: Boolean): Boolean; { Outs the slow speed command and if engine on it waits smoe moves of nidle from up to down and then returns true if moves ocured correctly } function GetLimitsState: Byte; { getslimts flags by reading the in value from the port } function IsNidleUp: Boolean; function WaitForNidleUp: Boolean; function WaitForNidleDown: Boolean; procedure OutInitializeCommands; procedure OutQuitCommands; procedure OutMoveCommand(AX, AY: Integer); procedure OutSlowModeCommand; procedure OutNormalModeCommand; procedure OutSwitchOffCommand; procedure OutSwitchOnCommand; public constructor Create( AMessagePort: PViewPort); destructor Destroy; virtual; function GetErrorFalgs: Word; function Jump(AX, AY: Integer; ALongJump: Boolean): Boolean; function Move(AX, AY: Integer): Boolean; function Stop: Boolean; function ResetPos: Boolean; function WaitNidleUpDown(ACount: Longint): Boolean; end; TViewPort = object(TGeneric) private X1, X2, Y1 , Y2: Integer; BackColor, TextColor: Integer; Zoom: Integer; public constructor Create(AX1, AY1, AX2, AY2, ABackColor, ATextColor: Integer); destructor Destroy; virtual; procedure SetZoom(AZoom: Integer); procedure Activate; function GetWidth: Integer; function GetHeight: Integer; function GetOriginX: Integer; function GetOriginY: Integer; procedure Clear; procedure SetTextColor(AColor: Integer); function GetTextColor: Integer; procedure OutTextXY(AX, AY: Integer; AS: string; ATransparent: Boolean); procedure Line(AX1, AY1, AX2, AY2: Integer); procedure DrawJump(AX1, AY1, AX2, AY2: Integer); procedure Circle(AX, AY, ARadios: Integer); procedure Bar(AX1, AY1, AX2, AY2: Integer); procedure Rectangle(AX1, AY1, AX2, AY2: Integer); end; PCanvas = ^TCanvas; TCanvas = object(TGeneric) private public DrawnViewPort, InfoViewPort, SignalsViewPort, MessagesViewPort: TViewPort; constructor Create; destructor Destroy; virtual; procedure DrawFrame; function GetOption(ATextColor, ABackColor: Integer; AOptions: string; ADefault: Integer): Integer; procedure OutMessage(AMessage: string); function InputString(ATitle: string; var AStr: string; AMaxLength: Integer): Boolean; function InputInteger(ATitle: string; var AValue: Longint; Min, Max: Longint): Boolean; end; PController = ^TController; TController = object(TGeneric) private ErrorCode: Integer; Data: TSendData; Machine: TMachine; ViewSendData: Boolean; CurrentX, CurrentY: Integer; procedure ProcessMachineError; public Canvas: TCanvas; constructor Create; destructor Destroy; virtual; procedure Run; function LoadDataFromFile( AFileName: string): Boolean; function InitSendData: Boolean; function SendData: Boolean; function MoveBack(ACount: Longint): Boolean; function MoveForward(ACount: Longint): Boolean; procedure DisplayDrawn; procedure DisplayUntilCurrentPos; function GetErrorCode: Integer; procedure UpdateInfoView; function ShiftNidle(AOffsetX, AOffsetY: Integer): Boolean; end; PState = ^TState; TState = object(TGeneric) procedure RunState; virtual; function GetNextState: PState; virtual; function Enter: Boolean; virtual; function Leave: Boolean; virtual; end; PControllerState = ^TControllerState; TControllerState = object(TState) private Controller: PController; public constructor Create( AController: PController); end; PMainMenuState = ^TMainMenuState; TMainMenuState = object(TControllerState) private Option: Integer; public procedure RunState; virtual; function GetNextState: PState; virtual; end; PLoadDataState = ^TLoadDataState; TLoadDataState = object(TControllerState) procedure RunState; virtual; function GetNextState: PState; virtual; end; PViewDataState = ^TViewDataState; TViewDataState = object(TControllerState) procedure RunState; virtual; function GetNextState: PState; virtual; end; PSendDataState = ^TSendDataState; TSendDataState = object(TControllerState) private SendResult: Boolean; UserBreakAtInitialize: Boolean; public procedure RunState; virtual; function GetNextState: PState; virtual; function Enter: Boolean; virtual; function Leave: Boolean; virtual; end; PResumeSendDataState = ^TResumeSendDataState; TResumeSendDataState = object(TSendDataState) procedure RunState; virtual; end; PBreakState = ^TBreakState; TBreakState = object(TControllerState) private UserCommand: Integer; public procedure RunState; virtual; function GetNextState: PState; virtual; end; PJumpsManipulationState = ^TJumpsManipulationState; TJumpsManipulationState = object(TControllerState) private ErrorOcured: Boolean; public procedure RunState; virtual; function GetNextState: PState; virtual; end; PExternalManipulationState = ^TExternalManipulationState; TExternalManipulationState = object(TControllerState) private ErrorOcured: Boolean; public procedure RunState; virtual; function GetNextState: PState; virtual; end; {*************************************************************} {* *} {* *} {*************************************************************} const ActiveViewPort: PViewPort = nil; {*************************************************************} {* *} {* *} {*************************************************************} constructor TBookMark.Create; begin inherited Create; FillChar(Info, SizeOf(Info), #0); end; {*************************************************************} {* *} {* *} {*************************************************************} constructor TSendData.Create; begin inherited Create; InitJumpTableCollection( Data); end; destructor TSendData.Destroy; begin FreeJmpTableCollection( Data); inherited Destroy; end; procedure TSendData.Clear; begin FreeJmpTableCollection( Data); end; function TSendData.LoadDataFromStream(AStream: PStream): Boolean; var Table: PJumpTable; Count: Longint; TableSize: Longint; TempFileID: TFileID; begin if (AStream <> nil) then begin AStream^.ReadBlock(TempFileID, SizeOf(TempFileID)); if (TempFileID = ControlFileID) then begin AStream^.ReadBlock(Count, SizeOf(Count)); AStream^.ReadBlock(OffsetX, SizeOf(OffsetX)); AStream^.ReadBlock(OffsetY, SizeOf(OffsetY)); AStream^.ReadBlock(Width, SizeOf(Width)); AStream^.ReadBlock(Height, SizeOf(Height)); while (Count > 0) do begin if (Count >= MaxTableSize) then TableSize := MaxTableSize else TableSize := Count; Table := AllocateJumpTable( TableSize ); AStream^.ReadBlock( Table^.Items, SizeOf(TJumpRec) * TableSize); Table^.Used := TableSize; AppendTableToCollection( Data, Table); Count := Count - TableSize; end; LoadDataFromStream := True; end else LoadDataFromStream := False; end else LoadDataFromStream := False; end; procedure TSendData.ProcessDistanceJumps(ASlowLength: Integer); var Item: TJumpRec; SqrLength: Longint; Count: Longint; SkipX, SkipY: Integer; begin { Simple processing for long jumps, Depends on the length of the juump only ...} SkipX := 0; SkipY := 0; SqrLength := LongInt(ASlowLength) * LongInt(ASlowLength); if GetFirstJumpItem(Data, Item) then repeat if ((Item.Mode <> modStop) and (Item.Mode <> modReset)) then begin Item.DeltaX := Item.DeltaX + SkipX; Item.DeltaY := Item.DeltaY + SkipY; if ((Item.DeltaX = 1) or (Item.DeltaX = -1)) then begin SkipX := Item.DeltaX; Item.DeltaX := 0; {Sound(1000); Delay(10); NoSound;} end else SkipX := 0; if ((Item.DeltaY = 1) or (Item.DeltaY = -1)) then begin SkipY := Item.DeltaY; Item.DeltaY := 0; {Sound(1000); Delay(10); NoSound;} end else SkipY := 0; if ((Longint(Longint(Item.DeltaX) * Longint(Item.DeltaX)) + Longint(Longint(Item.DeltaY) * Longint(Item.DeltaY))) >= SqrLength) then Item.Mode := modSlow else Item.Mode := modNormal; SetCurrentJumpItem(Data, Item); end; until not GetNextJumpItem(Data, Item); Count := JUMPSBEFORESLOWACTIVE; if GetLastJumpItem(Data, Item) then repeat if (Item.Mode = modSlow) then Count := JUMPSBEFORESLOWACTIVE else if ((Count > 0) and (Item.Mode = modNormal)) then begin Item.Mode := modSlow; SetCurrentJumpItem(Data, Item); Count := Count - 1; end else if (Item.Mode = modStop) then Count := 0; until not GetPrevJumpItem(Data, Item); end; function TSendData.IsFirst: Boolean; begin IsFirst := IsFirstJumpItem(Data); end; function TSendData.IsLast: Boolean; begin IsLast := IsLastJumpItem(Data); end; function TSendData.GetCurrent( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; var Item: TJumpRec; begin GetCurrent := GetCurrentJumpItem(Data, Item); AMode := Item.Mode; ADeltaX := Item.DeltaX; ADeltaY := Item.DeltaY; end; function TSendData.MoveToFirst: Boolean; begin MoveToFirst := MoveToFirstJumpItem(Data); end; function TSendData.MoveToLast: Boolean; begin MoveToLast := MoveToLastJumpItem(Data); end; function TSendData.MoveToNext: Boolean; begin MoveToNext := MoveToNextJumpItem(Data); end; function TSendData.MoveToPrev: Boolean; begin MoveToPrev := MoveToPrevJumpItem(Data); end; function TSendData.GetFirst( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; var Item: TJumpRec; begin GetFirst := GetFirstJumpItem(Data, Item); AMode := Item.Mode; ADeltaX := Item.DeltaX; ADeltaY := Item.DeltaY; end; function TSendData.GetLast( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; var Item: TJumpRec; begin GetLast := GetLastJumpItem(Data, Item); AMode := Item.Mode; ADeltaX := Item.DeltaX; ADeltaY := Item.DeltaY; end; function TSendData.GetNext( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; var Item: TJumpRec; begin GetNext := GetNextJumpItem(Data, Item); AMode := Item.Mode; ADeltaX := Item.DeltaX; ADeltaY := Item.DeltaY; end; function TSendData.GetPrev( var AMode: Byte; var ADeltaX, ADeltaY: Integer): Boolean; var Item: TJumpRec; begin GetPrev := GetPrevJumpItem(Data, Item); AMode := Item.Mode; ADeltaX := Item.DeltaX; ADeltaY := Item.DeltaY; end; function TSendData.GetBookMark: PBookMark; var BookMark: PBookMark; BookMarkInfo: TBookMarkInfo; begin if GetBookMarkInfo(Data, BookMarkInfo) then begin BookMark := New(PBookMark, Create); BookMark^.Info := BookMarkInfo; GetBookMark := BookMark; end else GetBookMark := nil; end; function TSendData.GetCurrentIndex: Longint; begin GetCurrentIndex := DataTypes.GetCurrentIndex(Data); end; function TSendData.GotoBookMark( ABookMark: PBookMark): Boolean; begin if (ABookMark <> nil) then GotoBookMark := DataTypes.GotoBookmark(Data, ABookMark^.Info) else GotoBookMark := False; end; function TSendData.GetNumCommands: Longint; begin GetNumCommands := Data.Size end; {*************************************************************} {* *} {* *} {*************************************************************} function TMachine.GetErrorFalgs: Word; var ErrorFlags: Word; Temp: Byte; TheKey: Char; Port1Value, Port2Value: Byte; begin ErrorFlags := $00; if LimitsErrorOcred then ErrorFlags := ErrorFlags or efREACHLIMIT; if ExternalBreakOcured then ErrorFlags := ErrorFlags or efEXTERNALSTOP else if UserBreakOcured then ErrorFlags := ErrorFlags or efUSERBREAK else if KeyPressed then begin TheKey := ReadKey; if TheKey = #27 then begin UserBreakOcured := True; ErrorFlags := (ErrorFlags or efUSERBREAK); end { just for simlation ..., it must be an external signal readen from I/O port ... } else if TheKey = ' ' then begin ExternalBreakOcured := True; ErrorFlags := (ErrorFlags or efEXTERNALSTOP); end; end; {Original test for error inputs ...} Port1Value := Port[prtTEST1]; Port2Value := Port[prtTEST2]; { Must to make test for currect bit, that bit whitch recive an external stop command .... if (((Port1Value and ... ) <> 0) or ((Port2Value and ... ) <> 0)) then ErrorFlags := (ErrorFlags or efEXTERNALSTOP);} {if (((Port1Value and $E0) <> 0) or ((Port2Value and $37) <> 0)) then ErrorFlags := (ErrorFlags or efUNKNOWN);} {if (((Port1Value and $E0) <> 0) or ((Port1Value and $37) <> 0)) then begin ErrorFlags := (ErrorFlags or Word((Port1Value and $E0) shr 5) shl 4); ErrorFlags := (ErrorFlags or Word((Port2Value and $3F) shl 3) shl 4); end;} { May be not complete } GetErrorFalgs := ErrorFlags; end; function TMachine.IsEngineWorks: Boolean; begin IsEngineWorks := ((LastCntrolOut and $01) = 0); end; function TMachine.SwitchEngineOn: Boolean; begin SwitchEngineOn := False; OutSwitchOnCommand; if WaitForNidleUp then begin if WaitForNidleDown then SwitchEngineOn := True else OutSwitchOffCommand; end else OutSwitchOffCommand; end; function TMachine.SwitchEngineOff: Boolean; begin SwitchEngineOff := WaitForNidleUp; OutSwitchOffCommand; Delay(1000); end; function TMachine.IsSlowMode: Boolean; begin IsSlowMode := ((LastCntrolOut and $02) <> 0); end; function TMachine.SwitchToNormalMode: Boolean; begin OutNormalModeCommand; SwitchToNormalMode := True; end; function TMachine.SwitchToSlowMode(AWaitForSlow: Boolean): Boolean; var I: Integer; begin if not IsSlowMode then begin OutSlowModeCommand; if IsEngineWorks then begin I := JUMPSBEFORESLOWACTIVE; if AWaitForSlow then repeat if not WaitForNidleUp then begin SwitchToSlowMode := False; Exit; end; if not WaitForNidleDown then begin SwitchToSlowMode := False; Exit; end; I := I - 1; until (I = 0); end; end; SwitchToSlowMode := True; end; function TMachine.GetLimitsState: Byte; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} GetLimitsState := 0; { Original function body ... GetLimitsState := (Port[prtTEST1] and (lmtLOX or lmtHIX or lmtLOY or lmtHIY)); } end; function TMachine.IsNidleUp: Boolean; const NidleUp: Boolean = True; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} if IsEngineWorks then begin IsNidleUp := NidleUp; NidleUp := not NidleUp; { Original body ... IsNidleUp := ((Port[prtTEST1] and $01) <> 0) } if IsSlowMode then Delay(100) else Delay(1); end else IsNidleUp := True; end; function TMachine.WaitForNidleUp: Boolean; var I: Longint; begin I := MAXWAITTESTS; while ((not IsNidleUp) and (I > 0)) do I := I - 1; if (I > 0) then WaitForNidleUp := True { Nidel is up ... Ok. } else WaitForNidleUp := False; { Time out state ... efor } end; function TMachine.WaitForNidleDown: Boolean; var I: Longint; begin I := MAXWAITTESTS; while (IsNidleUp and (I > 0)) do I := I - 1; if (I > 0) then WaitForNidleDown := True { Nidel is down ... Ok. } else WaitForNidleDown := False; { Time out state ... efor } end; procedure TMachine.OutInitializeCommands; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} {OutputPort^.OutTextXY(0,0,'Initialize '); Delay(2000);} Port[prtINIT1] := $92; Port[prtINIT2] := $30; Port[prtINIT2] := $70; LastCntrolOut := $03; Port[prtCONTR] := LastCntrolOut; OutMoveCommand(2,2); end; procedure TMachine.OutQuitCommands; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} {OutputPort^.OutTextXY(0,0,'Quit '); Delay(2000);} end; procedure TMachine.OutMoveCommand(AX, AY: Integer); var X,Y: Word; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} { Don`t forget to test limits switch and set that an efor ocured if there is any limit reached } if (AX > 0) then begin X := AX; LastCntrolOut := LastCntrolOut or $04; end else begin X := - AX; LastCntrolOut := LastCntrolOut and ($0F xor $04); end; if (AY > 0) then begin Y := AY; LastCntrolOut := LastCntrolOut or $08; end else begin Y := - AY; LastCntrolOut := LastCntrolOut and ($0F xor $08); end; { You can test nidle up state here before send move command } Port[prtCONTR] := LastCntrolOut; if (X > 1) then begin X := X - 1; Port[prtXMOVE] := Lo(X); Port[prtXMOVE] := Hi(X); end; if (Y > 1) then begin Y := Y - 1; Port[prtYMOVE] := Lo(Y); Port[prtYMOVE] := Hi(Y); end; end; procedure TMachine.OutSlowModeCommand; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} {OutputPort^.OutTextXY(0,0,'Slow '); Delay(2000);} LastCntrolOut := LastCntrolOut or $02; Port[prtCONTR] := LastCntrolOut; end; procedure TMachine.OutNormalModeCommand; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} {OutputPort^.OutTextXY(0,0,'Normal '); Delay(2000);} LastCntrolOut := LastCntrolOut and ($0F xor $02); Port[prtCONTR] := LastCntrolOut; end; procedure TMachine.OutSwitchOffCommand; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} {OutputPort^.OutTextXY(0,0,'Engine off '); Delay(2000);} LastCntrolOut := LastCntrolOut or $01; Port[prtCONTR] := LastCntrolOut; end; procedure TMachine.OutSwitchOnCommand; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} {OutputPort^.OutTextXY(0,0,'Engine on '); Delay(2000);} LastCntrolOut := LastCntrolOut and ($0F xor $01); Port[prtCONTR] := LastCntrolOut; end; constructor TMachine.Create( AMessagePort: PViewPort); begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} inherited Create; OutInitializeCommands; LimitsErrorOcred := False; UserBreakOcured := False; ExternalBreakOcured := False; LastCntrolOut := $00; end; destructor TMachine.Destroy; begin {***********************************} {* *} {* Virtual body of the methode *} {* *} {***********************************} OutQuitCommands; inherited Destroy; end; function TMachine.Jump(AX, AY: Integer; ALongJump: Boolean): Boolean; begin UserBreakOcured := False; ExternalBreakOcured := False; if ((GetErrorFalgs and efJUMPERRORMASK) = 0) then begin if not IsEngineWorks then if not SwitchEngineOn then begin { Engine not switched on, there is an efor } SwitchEngineOff; Jump := False; Exit; end; if ALongJump then begin if not IsSlowMode then if not SwitchToSlowMode(False{True}) { You can send slow command before some normal steps to make the actevity of slow mode now} then begin SwitchEngineOff; Jump := False; Exit; end; end else begin if IsSlowMode then if not SwitchToNormalMode then begin SwitchEngineOff; Jump := False; Exit; end; end; if not WaitForNidleUp then begin SwitchEngineOff; Jump := False; Exit; end; OutMoveCommand(AX, AY); if not WaitForNidleDown then begin SwitchEngineOff; Jump := False; Exit; end; if (GetLimitsState = 0) then Jump := True else begin SwitchEngineOff; LimitsErrorOcred := True; Jump := False; end; end else begin SwitchEngineOff; Jump := False; end; end; function TMachine.Move(AX, AY: Integer): Boolean; begin UserBreakOcured := False; ExternalBreakOcured := False; if ((GetErrorFalgs and efMOVEERRORMASK) = 0) then begin if IsEngineWorks then begin if not SwitchEngineOff then begin SwitchEngineOff; Move := False; Exit; end; end; OutMoveCommand(AX, AY); Move := (GetLimitsState = 0); end else begin SwitchEngineOff; Move := False; end; end; function TMachine.Stop: Boolean; begin Stop := SwitchEngineOff; end; function TMachine.ResetPos: Boolean; begin UserBreakOcured := False; ExternalBreakOcured := False; if ((GetErrorFalgs and efRESETPOSERRORMASK) = 0) then begin if IsEngineWorks then if not SwitchEngineOff then begin ResetPos := False; Exit; end; Delay(1000); { Original body of function ... while (((GetLimitsState and lmtLOX) = 0) and ((GetErrorFalgs and efRESETPOSERRORMASK) = 0)) do OutMoveCommand(-5, 0); while (((GetLimitsState and lmtLOX) <> 0) and ((GetErrorFalgs and efRESETPOSERRORMASK) = 0)) do OutMoveCommand(10, 0); while (((GetLimitsState and lmtLOY) = 0) and ((GetErrorFalgs and efRESETPOSERRORMASK) = 0)) do OutMoveCommand(0, -5); while (((GetLimitsState and lmtLOY) <> 0) and ((GetErrorFalgs and efRESETPOSERRORMASK) = 0)) do OutMoveCommand(0, 10); } LimitsErrorOcred := False; ResetPos := ((GetErrorFalgs and efRESETPOSERRORMASK) = 0); end else begin SwitchEngineOff; ResetPos := False; end; end; function TMachine.WaitNidleUpDown(ACount: Longint): Boolean; var I: Longint; begin I := ACount; if I > 0 then begin WaitNidleUpDown := False; if not IsEngineWorks then if not SwitchEngineOn then begin { Engine not switched on, there is an efor } SwitchEngineOff; Exit; end; repeat if not WaitForNidleUp then Exit; if not WaitForNidleDown then Exit; I := I - 1; until I = 0; end; WaitNidleUpDown := True; end; {*************************************************************} {* *} {* *} {*************************************************************} constructor TViewPort.Create(AX1, AY1, AX2, AY2, ABackColor, ATextColor: Integer); begin inherited Create; X1 := AX1; Y1 := AY1; X2 := AX2; Y2 := AY2; BackColor := ABackColor; TextColor := ATextColor; Zoom := 1; end; destructor TViewPort.Destroy; begin inherited Destroy; end; procedure TViewPort.SetZoom(AZoom: Integer); begin if (AZoom > 0) then Zoom := AZoom; end; procedure TViewPort.Activate; begin SetViewPort(X1, Y1, X2, Y2, False); SetColor(TextColor); ActiveViewPort := @Self; end; function TViewPort.GetWidth: Integer; begin GetWidth := X2 - X1; end; function TViewPort.GetHeight: Integer; begin GetHeight := Y2 - Y1; end; function TViewPort.GetOriginX: Integer; begin GetOriginX := X1; end; function TViewPort.GetOriginY: Integer; begin GetOriginY := Y1; end; procedure TViewPort.Clear; begin Activate; SetFillPattern(Solid, BackColor); Graph.Bar(0, 0, X2 - X1, Y2 - Y1); end; procedure TViewPort.SetTextColor(AColor: Integer); begin TextColor := AColor; if (ActiveViewPort = @Self) then Graph.SetColor( AColor) else Activate; end; function TViewPort.GetTextColor: Integer; begin GetTextColor := TextColor; end; procedure TViewPort.OutTextXY(AX,AY: Integer; AS: string; ATransparent: Boolean); begin if not (ActiveViewPort = @Self) then Activate; if not ATransparent then begin SetFillPattern(Solid, BackColor); Bar(AX, AY, TextWidth(AS) + AX, TextHeight(AS) + AY); end; Graph.OutTextXY(AX, AY, AS); end; procedure TViewPort.Line(AX1, AY1, AX2, AY2: Integer); begin if not (ActiveViewPort = @Self) then Activate; Graph.Line(AX1 div Zoom, AY1 div Zoom, AX2 div Zoom, AY2 div Zoom); {Graph.PutPixel(AX1 div Zoom, AY1 div Zoom, 15 + 128); Graph.PutPixel(AX2 div Zoom, AY2 div Zoom, 15 + 128);} end; procedure TViewPort.DrawJump(AX1, AY1, AX2, AY2: Integer); begin if not (ActiveViewPort = @Self) then Activate; Graph.Line(AX1 div Zoom, AY1 div Zoom, AX2 div Zoom, AY2 div Zoom); Graph.PutPixel(AX1 div Zoom, AY1 div Zoom, 15); Graph.PutPixel(AX2 div Zoom, AY2 div Zoom, 15); end; procedure TViewPort.Circle(AX, AY, ARadios: Integer); begin if not (ActiveViewPort = @Self) then Activate; Graph.Circle(AX div Zoom, AY div Zoom, ARadios div Zoom); end; procedure TViewPort.Bar(AX1, AY1, AX2, AY2: Integer); begin if not (ActiveViewPort = @Self) then Activate; Graph.Bar(AX1 div Zoom, AY1 div Zoom, AX2 div Zoom, AY2 div Zoom); end; procedure TViewPort.Rectangle(AX1, AY1, AX2, AY2: Integer); begin Graph.Rectangle(AX1 div Zoom, AY1 div Zoom, AX2 div Zoom, AY2 div Zoom); end; {*************************************************************} {* *} {* *} {*************************************************************} constructor TCanvas.Create; var Gd, Gm: Integer; begin inherited Create; Gd := Detect; InitGraph(Gd, Gm,'D:\BORLAND\BGI'); DrawnViewPort.Create(0, 0, GetMaxX - 20, GetMaxY - 45, 1, 7); SignalsViewPort.Create(GetMaxX - 19, 0, GetMaxX, GetMaxY - 45, 9,15); InfoViewPort.Create(0, GetMaxY - 44, GetMaxX, GetMaxY - 17, 9, 15); MessagesViewPort.Create(0, GetMaxY - 16, GetMaxX, GetMaxY, 7, 0); DrawnViewPort.SetZoom(1); end; destructor TCanvas.Destroy; begin DrawnViewPort.Destroy; MessagesViewPort.Destroy; InfoViewPort.Destroy; CloseGraph; inherited Destroy; end; procedure TCanvas.DrawFrame; begin DrawnViewPort.Clear; SignalsViewPort.Clear; InfoViewPort.Clear; MessagesViewPort.Clear; end; function TCanvas.GetOption(ATextColor, ABackColor: Integer; AOptions: string; ADefault: Integer): Integer; begin DrawnViewPort.GetHeight; GetOption := GAPI.GetOption(10, DrawnViewPort.GetHeight - 10,4,ATextColor, ABackColor,AOptions, ADefault); end; procedure TCanvas.OutMessage(AMessage: string); begin MessagesViewPort.Clear; MessagesViewPort.OutTextXY(5, 5, AMessage, False); end; function TCanvas.InputString(ATitle: string; var AStr: string; AMaxLength: Integer): Boolean; begin MessagesViewPort.OutTextXY(5,5,ATitle, False); InputString := GAPI.InputString(MessagesViewPort.GetOriginX + 6 + TextWidth(ATitle),MessagesViewPort.GetOriginY + 2, AMaxLength, AStr, True); MessagesViewPort.Clear; end; function TCanvas.InputInteger(ATitle: string; var AValue: Longint; Min, Max: Longint): Boolean; var S: string; Code: Integer; Value: Longint; label Rep; begin Str(AValue, S); MessagesViewPort.OutTextXY(5,5,ATitle, False); Rep : if GAPI.InputString( MessagesViewPort.GetOriginX + 6 + TextWidth(ATitle), MessagesViewPort.GetOriginY + 2, 10, S, True) then begin Val(S, Value, Code); if ((Code = 0) and (Value >= Min) and (Value <= Max)) then begin AValue := Value; InputInteger := True; end else goto Rep; end else InputInteger := False; MessagesViewPort.Clear; end; {*************************************************************} {* *} {* *} {*************************************************************} procedure TController.ProcessMachineError; var ErrorFlags: Word; procedure DisplayErrorFlags; var I: Integer; Mask: Word; S: string; begin Mask := efRESERVED1; Canvas.SignalsViewPort.Clear; SetFillPattern(Solid, 12); for I := 1 to 8 do begin if ((ErrorFlags and Mask ) = Mask) then Canvas.SignalsViewPort.Bar( 3, 3 + (I - 1) * 20, Canvas.SignalsViewPort.GetWidth - 4, 2 + I * 20 - 4); Mask := Mask shl 1; end; for I := 1 to 9 do begin Str(I, S); Canvas.SignalsViewPort.Rectangle( 2, 2 + (I - 1) * 20, Canvas.SignalsViewPort.GetWidth - 3, 2 + I * 20 - 3); Canvas.SignalsViewPort.OutTextXY( 4, 4 + (I - 1) * 20, S, True); end; end; begin ErrorFlags := Machine.GetErrorFalgs; if (ErrorFlags <> 0) then begin DisplayErrorFlags; if ((ErrorFlags and efEXTERNALSTOP) <> 0) then ErrorCode := errEXTERNALSTOP else if ((ErrorFlags and efRESERVEDMASK) <> 0) then ErrorCode := errUNKNOWN else if ((ErrorFlags and efSTRINGCUT) <> 0) then ErrorCode := errSTRINGCUT else if ((ErrorFlags and efREACHLIMIT) <> 0) then ErrorCode := errREACHLIMIT else if ((ErrorFlags and efUSERBREAK) <> 0) then ErrorCode := errUSERBREAK else ErrorCode := errUNKNOWN end else ErrorCode := errNONE; end; function TController.LoadDataFromFile( AFileName: string): Boolean; var FileStream: PFileStream; Zoom1, Zoom2: Real; Zoom: Longint; begin Data.Clear; if FileExists(AFilename) then begin Canvas.OutMessage('Loadind ...'); FileStream := New(PFileStream, Create(AFilename)); FileStream^.Seek(0); if Data.LoadDataFromStream( FileStream) then begin Data.ProcessDistanceJumps(FASTJUMPLIMIT); Zoom1 := Data.Width / Canvas.DrawnViewPort.GetWidth; Zoom2 := Data.Height / Canvas.DrawnViewPort.GetHeight; if Zoom1 < Zoom2 then Zoom1 := Zoom2; if (Trunc(Zoom1) < Zoom1) then Zoom := Trunc(Zoom1) + 1 else Zoom := Trunc(Zoom1); Canvas.DrawnViewPort.SetZoom(Zoom); Canvas.OutMessage('Ok.'); OkBeep; LoadDataFromFile := True; end else begin Canvas.DrawnViewPort.SetZoom(1); Canvas.OutMessage('Bad control data file.'); ErrorBeep; LoadDataFromFile := False; end; FileStream^.Free; UpdateInfoView; end else begin Canvas.OutMessage('Bad file name or file not exists.'); ErrorBeep; LoadDataFromFile := False; end; end; function TController.InitSendData: Boolean; begin Canvas.OutMessage('Initializing to send data to mochine ...'); InitSendData := False; if Data.MoveToFirst then begin Canvas.OutMessage('Reseting nidle pos ...'); if Machine.ResetPos then begin Canvas.OutMessage('Move nidle pos to drawn (0,0) pos ...'); if Machine.Move( Data.OffsetX, Data.OffsetY) then begin if ViewSendData then begin Canvas.DrawnViewPort.DrawJump(0, 0, Data.OffsetX, Data.OffsetY); CurrentX := Data.OffsetX; CurrentY := Data.OffsetY; end; InitSendData := Machine.WaitNidleUpDown(STARTUPDOWNCOUNT); end end; end; end; function TController.SendData: Boolean; var DeltaX, DeltaY: Integer; Mode: Byte; begin Canvas.OutMessage('Sending data to machine ...'); if Data.GetCurrent(Mode, DeltaX, DeltaY) then repeat case Mode of modNormal: if not Machine.Jump(DeltaX, DeltaY, False) then begin ProcessMachineError; SendData := False; Exit; end else if ViewSendData then begin Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + DeltaX, CurrentY + DeltaY); CurrentX := CurrentX + DeltaX; CurrentY := CurrentY + DeltaY; end; modSlow: if not Machine.Jump(DeltaX, DeltaY, True) then begin ProcessMachineError; SendData := False; Exit; end else if ViewSendData then begin Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + DeltaX, CurrentY + DeltaY); CurrentX := CurrentX + DeltaX; CurrentY := CurrentY + DeltaY; end; modStop: begin SendData := False; if not Machine.Stop then ProcessMachineError else if ViewSendData then begin end; Data.GetNext(Mode, DeltaX, DeltaY); SendData := False; Exit; end; modReset: {if not Machine.ResetPos then begin SendData := False; ProcessMachineError; Exit; end;} else end; until not Data.GetNext(Mode, DeltaX, DeltaY); Machine.SwitchEngineOff; SendData := True; end; function TController.MoveBack(ACount: Longint): Boolean; var DeltaX, DeltaY, JumpDistanceX, JumpDistanceY: Integer; Mode: Byte; I: Longint; begin if ACount < 1 then Exit; JumpDistanceX := 0; JumpDistanceY := 0; I := ACount; while I > 0 do if Data.GetPrev(Mode, DeltaX, DeltaY) then begin if ((Mode = modSlow) or (Mode = modNormal)) then begin JumpDistanceX := JumpDistanceX - DeltaX; JumpDistanceY := JumpDistanceY - DeltaY; end; I := I - 1; end else begin Data.MoveToFirst; Break; end; if Machine.Move(JumpDistanceX, JumpDistanceY) then begin Canvas.DrawnViewPort.SetTextColor(14); Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + JumpDistanceX, CurrentY + JumpDistanceY); CurrentX := CurrentX + JumpDistanceX; CurrentY := CurrentY + JumpDistanceY; MoveBack := True; end else MoveBack := False; end; function TController.MoveForward(ACount: Longint): Boolean; var DeltaX, DeltaY, JumpDistanceX, JumpDistanceY: Integer; Mode: Byte; I: Longint; begin if ACount < 1 then Exit; if not Data.GetCurrent(Mode, DeltaX, DeltaY) then Exit; JumpDistanceX := DeltaX; JumpDistanceY := DeltaY; I := ACount - 1; while I > 0 do if Data.GetNext(Mode, DeltaX, DeltaY) then begin if ((Mode = modSlow) or (Mode = modNormal)) then begin JumpDistanceX := JumpDistanceX + DeltaX; JumpDistanceY := JumpDistanceY + DeltaY; end; I := I - 1; end else Break; Data.GetNext(Mode, DeltaX, DeltaY); if Machine.Move(JumpDistanceX, JumpDistanceY) then begin Canvas.DrawnViewPort.SetTextColor(14); Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + JumpDistanceX, CurrentY + JumpDistanceY); CurrentX := CurrentX + JumpDistanceX; CurrentY := CurrentY + JumpDistanceY; MoveForward := True; end else MoveForward := False; end; procedure TController.DisplayDrawn; var DeltaX, DeltaY: Integer; Mode: Byte; begin Canvas.OutMessage('Drawing data ...'); Canvas.DrawnViewPort.Clear; Canvas.DrawnViewPort.SetTextColor(0); Canvas.DrawnViewPort.DrawJump(0, 0, Data.OffsetX, Data.OffsetY); CurrentX := Data.OffsetX; CurrentY := Data.OffsetY; Data.MoveToFirst; Canvas.DrawnViewPort.SetTextColor(7); if Data.GetCurrent(Mode, DeltaX, DeltaY) then repeat case Mode of modNormal: begin Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + DeltaX, CurrentY + DeltaY); CurrentX := CurrentX + DeltaX; CurrentY := CurrentY + DeltaY; end; modSlow: begin Canvas.DrawnViewPort.SetTextColor(12); Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + DeltaX, CurrentY + DeltaY); CurrentX := CurrentX + DeltaX; CurrentY := CurrentY + DeltaY; Canvas.DrawnViewPort.SetTextColor(7); end; modStop: begin Canvas.DrawnViewPort.SetTextColor(14); Canvas.DrawnViewPort.Circle(CurrentX, CurrentY, 5 * Canvas.DrawnViewPort.Zoom); Canvas.DrawnViewPort.SetTextColor(7); end; modReset: begin end; else end; until not Data.GetNext(Mode, DeltaX, DeltaY); Canvas.DrawnViewPort.SetTextColor(7); Canvas.OutMessage('Ok.'); OkBeep; end; procedure TController.DisplayUntilCurrentPos; var DeltaX, DeltaY: Integer; Mode: Byte; BookMark: PBookMark; Count: Longint; begin Canvas.OutMessage('Drawing data ...'); Canvas.DrawnViewPort.Clear; BookMark := Data.GetBookMark; Count := Data.GetCurrentIndex; if (Count > 1) then begin Canvas.DrawnViewPort.SetTextColor(0); Canvas.DrawnViewPort.DrawJump(0, 0, Data.OffsetX, Data.OffsetY); CurrentX := Data.OffsetX; CurrentY := Data.OffsetY; Data.MoveToFirst; Canvas.DrawnViewPort.SetTextColor(7); if Data.GetCurrent(Mode, DeltaX, DeltaY) then repeat case Mode of modNormal: begin Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + DeltaX, CurrentY + DeltaY); CurrentX := CurrentX + DeltaX; CurrentY := CurrentY + DeltaY; end; modSlow: begin Canvas.DrawnViewPort.SetTextColor(12); Canvas.DrawnViewPort.DrawJump(CurrentX, CurrentY, CurrentX + DeltaX, CurrentY + DeltaY); CurrentX := CurrentX + DeltaX; CurrentY := CurrentY + DeltaY; Canvas.DrawnViewPort.SetTextColor(7); end; modStop: begin Canvas.DrawnViewPort.SetTextColor(14); Canvas.DrawnViewPort.Circle(CurrentX, CurrentY, 5 * Canvas.DrawnViewPort.Zoom); Canvas.DrawnViewPort.SetTextColor(7); Canvas.DrawnViewPort.SetTextColor(7); end; modReset: begin end; else end; Count := Count - 1; until ((not Data.GetNext(Mode, DeltaX, DeltaY)) or (Count <= 1)); end; Data.GotoBookMark( BookMark); Canvas.DrawnViewPort.SetTextColor(7); Canvas.OutMessage('Ok.'); OkBeep; end; constructor TController.Create; begin inherited Create; Canvas.Create; Data.Create; Machine.Create( @Canvas.MessagesViewPort); ViewSendData := True; end; destructor TController.Destroy; begin Machine.Destroy; Data.Destroy; Canvas.Destroy; inherited Destroy; end; procedure TController.Run; var State: PState; NewState: PState; begin Canvas.DrawFrame; UpdateInfoView; NewState := New(PMainMenuState, Create(@Self)); repeat State := NewState; State^.Enter; State^.RunState; State^.Leave; NewState := State^.GetNextState; State^.Free; until (NewState = nil); end; function TController.GetErrorCode; begin GetErrorCode := ErrorCode; end; function TController.ShiftNidle(AOffsetX, AOffsetY: Integer): Boolean; begin ShiftNidle := Machine.Move( AOffsetX, AOffsetY); end; procedure TController.UpdateInfoView; var S: string; L: Longint; begin Str(MemAvail, S); S := 'Free memory : ' + S + ''; while Length(S) < 27 do S := S + ' '; Canvas.InfoViewPort.OutTextXY(5,15,S, False); Str(Data.GetNumCommands, S); S:= 'Commands count : ' + S; while Length(S) < 27 do S := S + ' '; Canvas.InfoViewPort.OutTextXY(5,5,S, False); L := Data.Width; Str(L, S); S:= 'Width : ' + S; while Length(S) < 27 do S := S + ' '; Canvas.InfoViewPort.OutTextXY(305,5,S, False); L := Data.Height; Str(L, S); S:= 'Height : ' + S; while Length(S) < 27 do S := S + ' '; Canvas.InfoViewPort.OutTextXY(305,15,S, False); end; {*************************************************************} {* *} {* *} {*************************************************************} procedure TState.RunState; begin end; function TState.GetNextState: PState; begin GetNextState := nil; end; function TState.Enter: Boolean; begin Enter := True; end; function TState.Leave: Boolean; begin Leave := True; end; {*************************************************************} {* *} {* *} {*************************************************************} constructor TControllerState.Create( AController: PController); begin inherited Create; Controller := AController; end; {*************************************************************} {* *} {* *} {*************************************************************} const MainMenuDefault: Integer = 1; procedure TMainMenuState.RunState; label Rep; begin Option := 0; Rep: MainMenuDefault := Controller^.Canvas.GetOption( 14, 8,'Load data file'#0'Display data'#0'Send data to machine'#0'Exit'#0, MainMenuDefault); case MainMenuDefault of 1 : Option := 1; 2 : Option := 2; 3 : Option := 3; 4 : Option := 0; else goto Rep; end; end; function TMainMenuState.GetNextState: PState; begin case Option of 1: GetNextState := New(PLoadDataState, Create(Controller)); 2: GetNextState := New(PViewDataState, Create(Controller)); 3: GetNextState := New(PSendDataState, Create(Controller)); else GetNextState := nil; end; end; {*************************************************************} {* *} {* *} {*************************************************************} const LoadedFileName: string = 'NONAME.ZCD'; procedure TLoadDataState.RunState; begin if Controller^.Canvas.InputString('Enter file name :', LoadedFileName, 50) then if LoadedFileName <> '' then Controller^.LoadDataFromFile(LoadedFileName); end; function TLoadDataState.GetNextState: PState; begin GetNextState := New(PMainMenuState, Create( Controller)); end; {*************************************************************} {* *} {* *} {*************************************************************} procedure TViewDataState.RunState; begin Controller^.DisplayDrawn; end; function TViewDataState.GetNextState: PState; begin GetNextState := New(PMainMenuState, Create( Controller)) end; {*************************************************************} {* *} {* *} {*************************************************************} procedure TSendDataState.RunState; begin Controller^.Canvas.DrawnViewPort.Clear; Controller^.Canvas.DrawnViewPort.SetTextColor(7); UserBreakAtInitialize := False; Delay(3000); if Controller^.InitSendData then SendResult := Controller^.SendData else begin SendResult := False; UserBreakAtInitialize := True; end; Controller^.ProcessMachineError; case Controller^.GetErrorCode of errNONE: begin if SendResult then Controller^.Canvas.OutMessage('Ok.') else Controller^.Canvas.OutMessage('Stop command.'); OkBeep; end; errSTRINGCUT: begin Controller^.Canvas.OutMessage('String cut error.'); ErrorBeep; end; errREACHLIMIT: begin Controller^.Canvas.OutMessage('Limits error.'); ErrorBeep; end; errUSERBREAK: begin Controller^.Canvas.OutMessage('User break'); ErrorBeep; end; errEXTERNALSTOP: begin Controller^.Canvas.OutMessage('User external break'); ErrorBeep; end; errCOMMANDBREAK: begin Controller^.Canvas.OutMessage('User break'); OkBeep; end; errUNKNOWN: begin Controller^.Canvas.OutMessage('Unknown error.'); ErrorBeep; end; end; end; function TSendDataState.Enter: Boolean; var Gd, Gm: Integer; begin Enter := True; end; function TSendDataState.Leave: Boolean; begin Leave := True; end; function TSendDataState.GetNextState: PState; begin {Controller^.ProcessMachineError;} case Controller^.GetErrorCode of errNONE: begin if SendResult then GetNextState := New(PMainMenuState, Create( Controller)) else GetNextState := New(PBreakState, Create( Controller)); end; errSTRINGCUT: begin GetNextState := New(PBreakState, Create( Controller)); end; errREACHLIMIT: begin GetNextState := New(PMainMenuState, Create( Controller)) end; errUSERBREAK: begin if UserBreakAtInitialize then GetNextState := New(PMainMenuState, Create( Controller)) else GetNextState := New(PBreakState, Create( Controller)); end; errEXTERNALSTOP: begin if UserBreakAtInitialize then GetNextState := New(PMainMenuState, Create( Controller)) else GetNextState := New(PExternalManipulationState, Create( Controller)); end; errCOMMANDBREAK: begin GetNextState := New(PBreakState, Create( Controller)); end; errUNKNOWN: begin GetNextState := New(PMainMenuState, Create( Controller)) end; else Halt(1); end; end; {*************************************************************} {* *} {* *} {*************************************************************} procedure TResumeSendDataState.RunState; begin Controller^.Canvas.DrawnViewPort.Activate; Controller^.Canvas.DrawnViewPort.SetTextColor(7); SendResult := Controller^.SendData; Controller^.ProcessMachineError; case Controller^.GetErrorCode of errNONE: begin if SendResult then Controller^.Canvas.OutMessage('Ok.') else Controller^.Canvas.OutMessage('Stop command.'); OkBeep; end; errSTRINGCUT: begin Controller^.Canvas.OutMessage('String cut error.'); ErrorBeep; end; errREACHLIMIT: begin Controller^.Canvas.OutMessage('Limits error.'); ErrorBeep; end; errUSERBREAK: begin Controller^.Canvas.OutMessage('User break'); ErrorBeep; end; errEXTERNALSTOP: begin Controller^.Canvas.OutMessage('User external break'); ErrorBeep; end; errCOMMANDBREAK: begin Controller^.Canvas.OutMessage('Command break'); OkBeep; end; errUNKNOWN: begin Controller^.Canvas.OutMessage('Unknown error.'); ErrorBeep; end; end; end; {*************************************************************} {* *} {* *} {*************************************************************} const BreakState: Integer = 1; procedure TBreakState.RunState; label Rep; var Key: Char; begin Controller^.DisplayUntilCurrentPos; Rep: BreakState := Controller^.Canvas.GetOption(14,3,'Manipulate pos'#0'Resume data sending'#0'Stop sending'#0, BreakState); case BreakState of 1 : UserCommand := 3; 2 : UserCommand := 1; 3,0 : begin WarningBeep; if Controller^.Canvas.GetOption(14,12,'No, don`t stop sending'#0'Yes, stop sending'#0, 1) = 2 then UserCommand := 2 else goto Rep; end; else goto Rep; end; end; function TBreakState.GetNextState: PState; var Gd, Gm: Integer; begin case UserCommand of 1: GetNextState := New(PResumeSendDataState, Create( Controller)); 2: GetNextState := New(PMainMenuState, Create( Controller)); 3: GetNextState := New(PJumpsManipulationState, Create( Controller)); else GetNextState := nil; end; end; {*************************************************************} {* *} {* *} {*************************************************************} const ManipulationCommand: Integer = 1; procedure TJumpsManipulationState.RunState; label Rep; var Jumps: Longint; begin ErrorOcured := False; Jumps := 10; Rep: {ManipulationCommand := Controller^.Canvas.GetOption(14,3, 'Move forward (1)'#0'Move backword (1)'#0'Move forward (N)'#0'Move backword (N)'#0'Return'#0, ManipulationCommand);} ManipulationCommand := Controller^.Canvas.GetOption(14,3, 'Move forward (1)'#0'Move backword (1)'#0'Move forward (N)'#0'Move backword (N)'#0 +'Shift up'#0'Shift down'#0'Shift left'#0'Shift right'#0'Return'#0, ManipulationCommand); case ManipulationCommand of 1: begin if Controller^.MoveForward(1) then goto Rep else ErrorOcured := True; end; 2: begin if Controller^.MoveBack(1) then goto Rep else ErrorOcured := True; end; 3: begin if Controller^.Canvas.InputInteger('Enter jumps count :',Jumps ,1, 1000) then begin if Controller^.MoveForward(Jumps) then goto Rep else ErrorOcured := True; end else goto Rep; end; 4: begin if Controller^.Canvas.InputInteger('Enter jumps count :',Jumps ,1, 1000) then begin if Controller^.MoveBack(Jumps) then goto Rep else ErrorOcured := True; end else goto Rep; end; 5: begin { Move up ... } Controller^.ShiftNidle(0,-10); goto Rep; end; 6: begin { Move down ... } Controller^.ShiftNidle(0,+10); goto Rep; end; 7: begin { Move left ... } Controller^.ShiftNidle(-10,0); goto Rep; end; 8: begin { Move right ... } Controller^.ShiftNidle(+10,0); goto Rep; end; else end; end; function TJumpsManipulationState.GetNextState: PState; begin if ErrorOcured then GetNextState := New(PMainMenuState, Create(Controller)) else GetNextState := New(PBreakState, Create(Controller)); end; {*************************************************************} {* *} {* *} {*************************************************************} procedure TExternalManipulationState.RunState; label Rep; var TheKey: Char; begin ErrorOcured := False; Rep: { Just for simulation ..., the command must be recived from I/O port not from key board ... from a bit of Port[prtTEST1] or Port[prtTEST2] } case TheKey of ' ': begin if Controller^.MoveBack(1) then goto Rep else ErrorOcured := True; end; #13: begin end else goto Rep; end; end; function TExternalManipulationState.GetNextState: PState; begin if ErrorOcured then GetNextState := New(PMainMenuState, Create( Controller)) else GetNextState := New(PResumeSendDataState, Create( Controller)); end; {*************************************************************} {* *} {* *} {*************************************************************} var Controller: TController; begin Controller.Create; Controller.Run; Controller.Destroy; end.
unit ufrmMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Objects, System.DateUtils, System.Math, System.Math.Vectors, System.IOUtils, FMX.Controls3D, FMX.Layers3D, FMX.Layouts; type TfrmMain = class(TForm) PaintBox1: TPaintBox; TrackBar1: TTrackBar; Timer1: TTimer; btnAnimate: TButton; lblBrand: TLabel; lblCaption: TLabel; Rectangle1: TRectangle; Layout1: TLayout; lblAttribution: TLabel; procedure TrackBar1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBox1Resize(Sender: TObject); procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas); procedure Timer1Timer(Sender: TObject); procedure btnAnimateClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FData: TArray<Single>; FbmpBackground: TBitmap; FStartDate: TDateTime; FMinTempValue: Single; procedure DrawBackground; procedure DrawTextOnCanvas(ACanvas: TCanvas; const AText: string; APoint: TPointF; AAngle: Single = 0.0); function GetFullRadius: Single; function GetTwoDegreeRadius(AFullRadius: Single): Single; procedure LoadData(const AFilename: string); public end; var frmMain: TfrmMain; implementation uses uClimateSpiralUtils; {$R *.fmx} // TfrmMain // ============================================================================ procedure TfrmMain.FormCreate(Sender: TObject); var LLastDate: TDateTime; begin FMinTempValue := -1.5; // Value at the centre of the chart FStartDate := EncodeDate(1850, 01, 01); FbmpBackground := TBitmap.Create; LoadData('HadCRUT.4.6.0.0.monthly_ns_avg.txt'); LLastDate := IncMonth(FStartDate, Length(FData)); lblCaption.Text := Format('Global temperature change (%s-%s)', [YearOf(FStartDate).ToString, YearOf(LLastDate).ToString]); end; // ---------------------------------------------------------------------------- procedure TfrmMain.FormDestroy(Sender: TObject); begin FbmpBackground.Free; end; // ---------------------------------------------------------------------------- procedure TfrmMain.PaintBox1Paint(Sender: TObject; Canvas: TCanvas); function GetDataPoint(AMonthNo: Integer; ARadius, AValue: Single): TPointF; var LTheta: Single; begin LTheta := Pi / 2 - (2 * Pi) * AMonthNo / 12; Result.X := Map(AValue, FMinTempValue, 2, 0, ARadius) * Cos(LTheta) + FbmpBackground.Width / 2; Result.Y := -1 * Map(AValue, FMinTempValue, 2, 0, ARadius) * Sin(LTheta) + FbmpBackground.Height / 2; end; var i: Integer; s: string; LMonthIndex: Integer; LMonth: TDateTime; LPoint: TPointF; LPrevPoint: TPointF; LFullRadius: Single; LTwoDegreeRadius: Single; begin DrawBackground; PaintBox1.Canvas.DrawBitmap(FbmpBackground, FbmpBackground.BoundsF, FbmpBackground.BoundsF, 1, True); LFullRadius := GetFullRadius; LTwoDegreeRadius := GetTwoDegreeRadius(LFullRadius); LMonthIndex := Round(TrackBar1.Value); LMonth := IncMonth(FStartDate, LMonthIndex); Canvas.Stroke.Kind := TBrushKind.Solid; Canvas.Stroke.Color := TAlphaColorRec.Red; Canvas.Fill.Color := TAlphaColorRec.Red; // LPrevPoint := GetDataPoint(1, LTwoDegreeRadius, FData[0]); for i := 1 to LMonthIndex do begin LPoint := GetDataPoint(i + 1, LTwoDegreeRadius, FData[i]); Canvas.Stroke.Color := GetViridisColor(Map(i, 0, Length(FData) - 1, 0, 100)); PaintBox1.Canvas.DrawLine(LPrevPoint, LPoint, 100); LPrevPoint := LPoint; end; Canvas.Font.Size := 26; // Canvas.Font.Style := [TFontStyle.fsBold]; Canvas.Fill.Color := FEdHawkinsWhite; s := FormatDateTime('yyyy', LMonth); DrawTextOnCanvas(Canvas, s, PointF(FbmpBackground.Canvas.Width / 2, FbmpBackground.Canvas.Height / 2)); end; // ---------------------------------------------------------------------------- procedure TfrmMain.PaintBox1Resize(Sender: TObject); begin if not Assigned(FbmpBackground) then Exit; DrawBackground; PaintBox1.Repaint; end; // ---------------------------------------------------------------------------- procedure TfrmMain.Timer1Timer(Sender: TObject); begin if TrackBar1.Value >= TrackBar1.Max then begin Timer1.Enabled := False; TrackBar1.Enabled := True; btnAnimate.Text := 'Animate'; btnAnimate.Enabled := True; end else TrackBar1.Value := Min(TrackBar1.Value + 3, TrackBar1.Max); end; // ---------------------------------------------------------------------------- procedure TfrmMain.TrackBar1Change(Sender: TObject); begin PaintBox1.Repaint; end; // ---------------------------------------------------------------------------- procedure TfrmMain.btnAnimateClick(Sender: TObject); begin Timer1.Enabled := True; TrackBar1.Enabled := False; btnAnimate.Enabled := False; btnAnimate.Text := 'Animating...'; end; // ---------------------------------------------------------------------------- procedure TfrmMain.DrawBackground; var i: Integer; s: string; LCenter: TPointF; LCircleRect: TRectF; LPoint: TPointF; LTheta: Single; LFullRadius: Single; LTwoDegreeRadius: Single; LOnePointFiveDegreeRadius: Single; LZeroDegreeRadius: Single; begin FbmpBackground.SetSize(Trunc(PaintBox1.Width), Trunc(PaintBox1.Height)); LCenter := PointF(FbmpBackground.Width / 2, FbmpBackground.Height / 2); LFullRadius := GetFullRadius; LTwoDegreeRadius := GetTwoDegreeRadius(LFullRadius); LOnePointFiveDegreeRadius := Map(1.5, FMinTempValue, 2, 0, LTwoDegreeRadius); LZeroDegreeRadius := Map(0, FMinTempValue, 2, 0, LTwoDegreeRadius); FbmpBackground.Clear(FEdHawkinsGrey); FbmpBackground.Canvas.BeginScene; try FbmpBackground.Canvas.Fill.Color := TAlphaColorRec.Black; LCircleRect := TRectF.Create(LCenter); InflateRect(LCircleRect, LFullRadius, LFullRadius); FbmpBackground.Canvas.FillEllipse(LCircleRect, 1); FbmpBackground.Canvas.Stroke.Thickness := 3; FbmpBackground.Canvas.Stroke.Color := TAlphaColorRec.Red; FbmpBackground.Canvas.DrawArc(LCenter, PointF(LTwoDegreeRadius, LTwoDegreeRadius), 278, 344, 1); FbmpBackground.Canvas.DrawArc(LCenter, PointF(LOnePointFiveDegreeRadius, LOnePointFiveDegreeRadius), 280, 340, 1); FbmpBackground.Canvas.Font.Size := 20; FbmpBackground.Canvas.Fill.Color := TAlphaColorRec.Red; DrawTextOnCanvas(FbmpBackground.Canvas, '2.0°C', LCenter - PointF(0, LTwoDegreeRadius)); DrawTextOnCanvas(FbmpBackground.Canvas, '1.5°C', LCenter - PointF(0, LOnePointFiveDegreeRadius)); FbmpBackground.Canvas.Fill.Color := FEdHawkinsWhite; FbmpBackground.Canvas.Stroke.Color := FEdHawkinsWhite; // FbmpBackground.Canvas.DrawArc(LCenter, PointF(LZeroDegreeRadius, LZeroDegreeRadius), 295, 310, 1); FbmpBackground.Canvas.DrawArc(LCenter, PointF(LZeroDegreeRadius, LZeroDegreeRadius), 294, 312, 1); DrawTextOnCanvas(FbmpBackground.Canvas, '0.0°C', LCenter - PointF(0, LZeroDegreeRadius - 5)); for i := 1 to 12 do begin LTheta := Pi / 2 - (2 * Pi) * i / 12; LPoint.X := (LFullRadius + 14) * Cos(LTheta) + FbmpBackground.Width / 2; LPoint.Y := -1 * (LFullRadius + 14) * Sin(LTheta) + FbmpBackground.Height / 2; s := FormatDateTime('mmm', EncodeDate(YearOf(Now), i, 1)); DrawTextOnCanvas(FbmpBackground.Canvas, s, LPoint, Pi / 2 - LTheta); end; finally FbmpBackground.Canvas.EndScene; end; end; // ---------------------------------------------------------------------------- procedure TfrmMain.DrawTextOnCanvas(ACanvas: TCanvas; const AText: string; APoint: TPointF; AAngle: Single); var LTextRect: TRectF; LMatrix: TMatrix; LOriginalMatrix: TMatrix; begin LTextRect.Create(APoint); InflateRect(LTextRect, 30, 15); if AAngle <> 0.0 then begin LOriginalMatrix := ACanvas.Matrix; LMatrix := LOriginalMatrix; LMatrix := LMatrix * TMatrix.CreateTranslation(-APoint.X, -APoint.Y); LMatrix := LMatrix * TMatrix.CreateRotation(AAngle); LMatrix := LMatrix * TMatrix.CreateTranslation(APoint.X, APoint.Y); ACanvas.SetMatrix(LMatrix); end; try ACanvas.FillText(LTextRect, AText, False, 100, [], TTextAlign.Center, TTextAlign.Center); finally if AAngle <> 0.0 then ACanvas.SetMatrix(LOriginalMatrix); end; end; // ---------------------------------------------------------------------------- function TfrmMain.GetFullRadius: Single; begin Result := Min(FbmpBackground.Width, FbmpBackground.Height) / 2 * 0.88; end; // ---------------------------------------------------------------------------- function TfrmMain.GetTwoDegreeRadius(AFullRadius: Single): Single; begin Result := AFullRadius * 0.9; end; // ---------------------------------------------------------------------------- procedure TfrmMain.LoadData(const AFilename: string); var i: Integer; LLines: TStringDynArray; LColumns: TStringList; begin FormatSettings.DecimalSeparator := '.'; // For regions that don't use a period as a decimal LLines := TFile.ReadAllLines(AFilename); SetLength(FData, Length(LLines)); LColumns := TStringList.Create; try for i := 0 to Length(LLines) - 1 do begin LColumns.CommaText := LLines[i]; FData[i] := LColumns[1].ToSingle; end; finally LColumns.Free; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.6 2/8/05 5:58:32 PM RLebeau Updated InitComponent() to call TIdReply.SetReply() instead of setting the Code and Text properties individually Rev 1.5 11/15/04 11:31:20 AM RLebeau Bug fix for OutboundConnect() assigning the IOHandler.ConnectTimeout property before the IOHandler has been assigned. Rev 1.4 11/14/04 11:39:24 AM RLebeau Updated OutboundConnect() to send the Greeting Rev 1.3 5/18/04 1:02:02 PM RLebeau Removed GetReplyClass() and GetRepliesClass() overrides. Rev 1.2 5/16/04 5:28:40 PM RLebeau Added GetReplyClass() and GetRepliesClass() overrides. Rev 1.1 2004.02.03 5:45:52 PM czhower Name changes Rev 1.0 2/2/2004 4:11:36 PM JPMugaas Recased to be consistant with IdPOP3 and IdPOP3Server. I also fixed several bugs that could cause AV's. Rev 1.0 2/1/2004 4:22:48 AM JPMugaas Components from IdMappedPort are now in their own units. } unit IdMappedPOP3; interface {$i IdCompilerDefines.inc} uses {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} Classes, {$ENDIF} IdAssignedNumbers, IdMappedPortTCP, IdMappedTelnet, IdReplyPOP3, IdTCPServer; type TIdMappedPOP3Context = class (TIdMappedTelnetContext) protected FErrorMsg: String; FGreeting: String; FUserName: String; procedure OutboundConnect; override; public property ErrorMsg: String read FErrorMsg; property Greeting: String read FGreeting; property UserName: String read FUsername write FUserName; end; TIdMappedPOP3 = class (TIdMappedTelnet) protected FReplyUnknownCommand: TIdReplyPOP3; FGreeting: TIdReplyPOP3; FUserHostDelimiter: String; procedure InitComponent; override; procedure SetGreeting(AValue: TIdReplyPOP3); procedure SetReplyUnknownCommand(const AValue: TIdReplyPOP3); public {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor Create(AOwner: TComponent); reintroduce; overload; {$ENDIF} destructor Destroy; override; published property Greeting : TIdReplyPOP3 read FGreeting write SetGreeting; property ReplyUnknownCommand: TIdReplyPOP3 read FReplyUnknownCommand write SetReplyUnknownCommand; property DefaultPort default IdPORT_POP3; property MappedPort default IdPORT_POP3; property UserHostDelimiter: String read FUserHostDelimiter write FUserHostDelimiter; end; implementation uses IdGlobal, IdException, IdIOHandlerSocket, IdResourceStringsProtocols, IdTCPClient, IdTCPConnection, SysUtils; { TIdMappedPOP3 } {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor TIdMappedPOP3.Create(AOwner: TComponent); begin inherited Create(AOwner); end; {$ENDIF} destructor TIdMappedPOP3.Destroy; begin FreeAndNil(FReplyUnknownCommand); FreeAndNil(FGreeting); inherited Destroy; end; procedure TIdMappedPOP3.InitComponent; Begin inherited InitComponent; FUserHostDelimiter := '#';//standard {Do not Localize} FGreeting := TIdReplyPOP3.Create(nil); FGreeting.SetReply('+OK', RSPop3ProxyGreeting); {Do not Localize} FReplyUnknownCommand := TIdReplyPOP3.Create(nil); FReplyUnknownCommand.SetReply('-ERR', RSPop3UnknownCommand); {Do not Localize} DefaultPort := IdPORT_POP3; MappedPort := IdPORT_POP3; FContextClass := TIdMappedPOP3Context; end; procedure TIdMappedPOP3.SetGreeting(AValue: TIdReplyPOP3); begin FGreeting.Assign(AValue); end; procedure TIdMappedPOP3.SetReplyUnknownCommand(const AValue: TIdReplyPOP3); begin FReplyUnknownCommand.Assign(AValue); end; { TIdMappedPOP3Context } procedure TIdMappedPOP3Context.OutboundConnect; var LHostPort, LPop3Cmd: String; LServer: TIdMappedPOP3; Begin //don`t call inherited, NEW behavior LServer := TIdMappedPOP3(Server); with LServer do begin Connection.IOHandler.Write(Greeting.FormattedReply); FOutboundClient := TIdTCPClient.Create(nil); with TIdTcpClient(FOutboundClient) do begin Port := MappedPort; Host := MappedHost; end;//with Self.FAllowedConnectAttempts := LServer.AllowedConnectAttempts; DoLocalClientConnect(Self); repeat if Self.FAllowedConnectAttempts > 0 then begin Dec(Self.FAllowedConnectAttempts); end; try // Greeting LHostPort := Trim(Connection.IOHandler.ReadLn);//USER username#host OR QUIT LPop3Cmd := Fetch(LHostPort, ' ', True); {Do not Localize} if TextIsSame(LPop3Cmd, 'QUIT') then {Do not Localize} begin Connection.IOHandler.WriteLn('+OK ' + RSPop3QuitMsg); {Do not Localize} Connection.Disconnect; Break; end else if TextIsSame(LPop3Cmd, 'USER') then {Do not Localize} begin FUserName := Fetch(LHostPort, FUserHostDelimiter, True, False);//?:CaseSensetive LHostPort := TrimLeft(LHostPort); //TrimRight above ExtractHostAndPortFromLine(Self, LHostPort); end else begin Connection.IOHandler.Write(ReplyUnknownCommand.FormattedReply); Continue; end;//if if Length(TIdTcpClient(FOutboundClient).Host) < 1 then begin raise EIdException.Create(RSEmptyHost); end; with TIdTcpClient(FOutboundClient) do begin ConnectTimeout := Self.FConnectTimeOut; Connect; end; //Read Pop3 Banner for OnOutboundClientConnect Self.FGreeting := FOutboundClient.IOHandler.ReadLn; FOutboundClient.IOHandler.WriteLn('USER ' + FUserName); {Do not Localize} except on E: Exception do // DONE: Handle connect failures begin FErrorMsg := '[' + E.ClassName + '] ' + E.Message; {Do not Localize} Self.DoException(E); Connection.IOHandler.WriteLn('-ERR ' + FErrorMsg); end; end;//trye until FOutboundClient.Connected or (Self.FAllowedConnectAttempts < 1); if FOutboundClient.Connected then begin DoOutboundClientConnect(Self); end else begin Connection.Disconnect; //prevent all next work end; end;//with end; end.
program Divide; {$mode objfpc}{$H+} uses SysUtils,Classes; type TDivide = class private numerator,denominator,result,remainder:integer; procedure calculate; procedure displayresult; end; procedure TDivide.calculate; begin result:=(numerator div denominator); remainder:=(numerator mod denominator); end; procedure TDivide.displayresult; begin WriteLn('result = ' + IntToStr(result)); WriteLn('remainder = ' + IntToStr(remainder)); end; var Divide1 : TDivide; begin { Add your program code here } Divide1 := TDivide.create; Divide1.numerator := 76; Divide1.denominator := 8; Divide1.calculate; Divide1.displayresult; Divide1.Free; end.
unit uGUI; interface uses Windows, Graphics, Classes, SysUtils, Types, Messages, // Own units uResFont, UCommon; type TGUI = class(THODObject) MainBG, BarBG, GreenBar, BlueBar, RedBar, GoldBar, Slot, MSlot, RSlot, BSlot, MiniMap, DMark, UMark, MMark: TBitmap; procedure MakeMiniMap; procedure ShowLog; //** Конструктор. constructor Create; destructor Destroy; override; procedure MakePC; end; var GUI: TGUI; GameFont: TResFont; Viz: Boolean = False; ShowJournal: Boolean = False; implementation uses uSCR, uMain, uMap, uVars, uAlerts, uInvBox, uBox, uUtils, uGUIBorder, PCImage, uMsg, uSkillBox, Affixes, uColors, uScript, uItemBonus, uAdvStr, uSaveLoad, uTileMask, uGraph, uSceneStat, uScene, uEffects, uIni, uTest; { TGUI } constructor TGUI.Create; begin // Font GameFont := TResFont.Create; GameFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName); // Scr with SCR do begin // Фон для полос MiniMap := TBitMap.Create; BarBG := TBitMap.Create; BarBG.LoadFromFile(Path + 'Data\Images\GUI\BarBG.bmp'); // Основной фон MainBG := TBitMap.Create; MainBG.LoadFromFile(Path + 'Data\Images\GUI\BG.bmp'); MainBG.Width := 800; MainBG.Canvas.Draw(400, 0, MainBG); // Красная полоса RedBar := TBitMap.Create; RedBar.LoadFromFile(Path + 'Data\Images\GUI\BarRed.bmp'); // Синяя полоса BlueBar := TBitMap.Create; BlueBar.LoadFromFile(Path + 'Data\Images\GUI\BarBlue.bmp'); // Зеленая полоса GreenBar := TBitMap.Create; GreenBar.LoadFromFile(Path + 'Data\Images\GUI\BarGreen.bmp'); // Золотая полоса GoldBar := TBitMap.Create; GoldBar.LoadFromFile(Path + 'Data\Images\GUI\BarGold.bmp'); // Маркеры на миникарте DMark := TBitMap.Create; DMark.LoadFromFile(Path + 'Data\Images\GUI\DMark.bmp'); DMark.Transparent := True; // UMark := TBitMap.Create; UMark.LoadFromFile(Path + 'Data\Images\GUI\UMark.bmp'); UMark.Transparent := True; // MMark := TBitMap.Create; MMark.LoadFromFile(Path + 'Data\Images\GUI\MMark.bmp'); MMark.Transparent := True; // Slot := TBitMap.Create; Slot.LoadFromFile(Path + 'Data\Images\GUI\Slot.bmp'); // MSlot := TBitMap.Create; MSlot.LoadFromFile(Path + 'Data\Images\GUI\MSlot.bmp'); MSlot.Transparent := True; // RSlot := TBitMap.Create; RSlot.LoadFromFile(Path + 'Data\Images\GUI\RSlot.bmp'); RSlot.Transparent := True; // BSlot := TBitMap.Create; BSlot.LoadFromFile(Path + 'Data\Images\GUI\BSlot.bmp'); BSlot.Transparent := True; end; end; destructor TGUI.Destroy; begin MiniMap.Free; // BB.Free; BarBG.Free; GreenBar.Free; RedBar.Free; GoldBar.Free; MSlot.Free; RSlot.Free; BSlot.Free; Slot.Free; MainBG.Free; DMark.Free; UMark.Free; MMark.Free; inherited; end; procedure TGUI.MakeMiniMap; var x, y: Word; begin for y := 0 to Map.Height do for x := 0 to Map.Width do Map.MapViz[x, y] := False; // GUI.MiniMap.LoadFromFile(Path + 'Data\Images\GUI\HoD.bmp'); // GUIBorder.Make(GUI.MiniMap); // GUI.MiniMap.SaveToFile(Path + 'Data\Images\GUI\HoD.bmp'); with GUI.MiniMap do begin Width := Map.Width; Height := Map.Height; with Canvas do begin Brush.Color := clBlack; FillRect(Canvas.ClipRect); end; end; end; function GetRaceDownItemID(): Byte; var Gender, Race: Byte; begin Result := 0; Race := VM.GetInt('Hero.Race'); Gender := VM.GetInt('Hero.Gender'); case Race of 0: case Gender of 0: Result := 28; 1: Result := 7; end; 1: case Gender of 0: Result := 10; 1: Result := 3; end; 2: case Gender of 0: Result := 27; 1: Result := 6; end; 3: case Gender of 0: Result := 11; 1: Result := 8; end; 4: case Gender of 0: Result := 25; 1: Result := 5; end; 5: case Gender of 0: Result := 12; 1: Result := 4; end; 6: case Gender of 0: Result := 9; 1: Result := 15; end; 7: case Gender of 0: Result := 19; 1: Result := 22; end; end; end; procedure TGUI.MakePC; var A: THRec; I: Integer; H: array[0..9] of Integer; K: string; AntiLeakBmp: TBitMap; begin ClearCXIRec(A); for I := 0 to High(H) do if InvBox.Doll.IsEmptyItem(i) then H[i] := 0 else H[i] := InvBox.Doll.InvItems[i].BaseItemID; // Раса A[0] := (VM.GetInt('Hero.Race') * 2) + VM.GetInt('Hero.Gender'); // Прическа A[1] := VM.GetInt('Hero.Hair'); // Плащ A[2] := InvBox.InvItems[H[2]].DollID; // Штаны A[3] := GetRaceDownItemID(); // Головной убор A[4] := InvBox.InvItems[H[0]].DollID; // Обувь A[5] := InvBox.InvItems[H[5]].DollID; // Рукавицы A[6] := InvBox.InvItems[H[6]].DollID; // Туника A[7] := InvBox.InvItems[H[3]].DollID; // Правая рука A[8] := InvBox.InvItems[H[8]].DollID; // Левая рука A[9] := InvBox.InvItems[H[9]].DollID; // for i := 0 to High(H) do if (A[I] < 0) then A[I] := 0; // with Map.HeroImage do begin Width := 32; Height := 32; Transparent := True; TransparentColor := clFuchsia; AntiLeakBmp := MakePCImage(A); Canvas.Draw(0, 0, AntiLeakBmp); AntiLeakBmp.Free; TransparentColor := Canvas.Pixels[0, 0]; end; end; procedure TGUI.ShowLog; var i, M: Byte; fntAddSize: Integer; begin case ShowLogLevel of 0: Exit; 1: M := MsgMin; else M := MsgMax; end; //fntAddSize := 0; fntAddSize := VM.GetInt('Font.LogFontSizeShift'); //fntAddSize := 3; with SCR.BG.Canvas do begin Font.Name := GameFont.FontName; Brush.Style := bsClear; Font.Style := []; Font.Size := 14; for i := 0 to M do begin case i of 0: Font.Color := $006CB1C5; 1..MsgMin: Font.Color := $006089A2; end; Font.Size := Font.Size + fntAddSize; TextOut(8, 535 - (i * 16), Msg.MsgList[i]); end; end; end; initialization GUI := TGUI.Create; finalization GUI.Free; end.
unit Play_MV; interface uses Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, scStyledForm, scControls, scGPControls, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, PasLibVlcPlayerUnit, PasLibVlcUnit, FullScreen; const MAX_ARGS = 255; type TFm_MV = class(TForm) SF_MV: TscStyledForm; Trc_MV_Video: TscGPTrackBar; PN_MV: TscGPPanel; PN_Ctrl: TscGPPanel; Trc_MV_Voice: TscGPTrackBar; BTN_Play_Pause: TscGPButton; BTN_Stop: TscGPButton; PLVP_MV: TPasLibVlcPlayer; PN_Top: TscGPPanel; BTN_Close: TscGPButton; LB_Caption: TscGPLabel; BTN_Max_Min: TscGPButton; BTN_Type: TscGPButton; procedure BTN_Play_PauseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Trc_MV_VoiceChange(Sender: TObject); procedure PLVP_MVMediaPlayerLengthChanged(Sender: TObject; time: Int64); procedure PLVP_MVMediaPlayerTimeChanged(Sender: TObject; time: Int64); procedure Trc_MV_VideoChange(Sender: TObject); procedure BTN_CloseClick(Sender: TObject); procedure BTN_Max_MinClick(Sender: TObject); procedure BTN_StopClick(Sender: TObject); procedure Trc_MV_VideoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Trc_MV_VideoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Fm_MV: TFm_MV; p_li: libvlc_instance_t_ptr; p_mi: libvlc_media_player_t_ptr; implementation {$R *.dfm} uses Main; { TFm_MV } procedure TFm_MV.BTN_CloseClick(Sender: TObject); begin PLVP_MV.Pause(); Fm_MV.Hide; //close; end; procedure TFm_MV.BTN_Max_MinClick(Sender: TObject); var oldL, oldT, oldW, oldH: Integer; oldA: TAlign; begin oldL := PLVP_MV.Left; oldT := PLVP_MV.Top; oldW := PLVP_MV.Width; oldH := PLVP_MV.Height; oldA := PLVP_MV.Align; if BTN_Max_Min.ImageIndex = 29 then begin if (oldA <> alNone) then PLVP_MV.Align := alNone; Fm_FullScreen.SetBounds(Monitor.Left, Monitor.Top, Monitor.Width, Monitor.Height); // PLVP_MV.Parent := Fm_FullScreen; Windows.SetParent(PLVP_MV.Handle, Fm_FullScreen.Handle); // PLVP_MV.Align := alClient; PLVP_MV.SetBounds(0, 0, Fm_FullScreen.Width, Fm_FullScreen.Height); BTN_Max_Min.ImageIndex := 30; Fm_FullScreen.Show; // Fm_FullScreen.Free; // BTN_Max_Min.ImageIndex := 29; // PLVP_MV.SetBounds(oldL, oldT, oldW, oldH); // Windows.SetParent(PLVP_MV.Handle, SELF.Handle); // if (oldA <> alNone) then // PLVP_MV.Align := oldA; end else begin // Fm_FullScreen.Close; // Fm_FullScreen.Free; BTN_Max_Min.ImageIndex := 29; Windows.SetParent(PLVP_MV.Handle, SELF.Handle); PLVP_MV.SetBounds(oldL, oldT, oldW, oldH); // PLVP_MV.Parent := Self.PN_MV; // Fm_FullScreen.Close; Fm_FullScreen.Close; // aFullScreenForm.Free; if (oldA <> alNone) then PLVP_MV.Align := oldA; end; end; procedure TFm_MV.BTN_Play_PauseClick(Sender: TObject); begin if BTN_Play_Pause.ImageIndex = 26 then begin PLVP_MV.Resume(); Trc_MV_Video.OnChange := NIL; BTN_Play_Pause.ImageIndex := 27; end else begin PLVP_MV.Pause(); Trc_MV_Video.OnChange := Trc_MV_VideoChange; BTN_Play_Pause.ImageIndex := 26; end; end; procedure TFm_MV.BTN_StopClick(Sender: TObject); begin PLVP_MV.Stop; end; procedure TFm_MV.FormClose(Sender: TObject; var Action: TCloseAction); begin PLVP_MV.Stop; end; procedure TFm_MV.FormShow(Sender: TObject); begin(*初始化插件位置并载入*) libvlc_dynamic_dll_init_with_path(ExtractFileDir(ParamStr(0))); libvlc_dynamic_dll_init(); if (libvlc_dynamic_dll_error <> '') then begin MessageDlg(libvlc_dynamic_dll_error, mtError, [mbOK], 0); Close; exit; end; with TArgcArgs.Create([libvlc_dynamic_dll_path, '--intf=dummy', '--ignore-config', '--quiet', '--no-video-title-show', '--no-video-on-top']) do begin p_li := libvlc_new(ARGC, ARGS); Free; end; if (p_li <> NIL) then begin p_mi := libvlc_media_player_new(p_li); end; end; procedure TFm_MV.PLVP_MVMediaPlayerLengthChanged(Sender: TObject; time: Int64); begin Trc_MV_Video.MaxValue := time; end; procedure TFm_MV.PLVP_MVMediaPlayerTimeChanged(Sender: TObject; time: Int64); var oldOnChange: TNotifyEvent; begin // ProgLabel1.Caption := time2str(time, 'hh:mm:ss.ms'); oldOnChange := Trc_MV_Video.OnChange; Trc_MV_Video.OnChange := NIL; Trc_MV_Video.Value := time; Trc_MV_Video.OnChange := oldOnChange; end; procedure TFm_MV.Trc_MV_VideoChange(Sender: TObject); begin if PLVP_MV.CanSeek() then begin PLVP_MV.SetVideoPosInMs(Trc_MV_Video.Value); end; end; procedure TFm_MV.Trc_MV_VideoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Trc_MV_Video.OnChange := Trc_MV_VideoChange; end; procedure TFm_MV.Trc_MV_VideoMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Trc_MV_Video.OnChange := NIL; end; procedure TFm_MV.Trc_MV_VoiceChange(Sender: TObject); begin if Trc_MV_Voice.Value > 0 then PLVP_MV.SetAudioVolume(Trc_MV_Voice.Value); end; end.
unit main; {$mode objfpc}{$H+} interface uses windows, Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls, IniFiles; type TInstallStage= (STAGE_INIT, STAGE_INTEGRITY, STAGE_PACKING, STAGE_PACKING_SUCCESS, STAGE_SELECT_DIR, STAGE_SELECT_GAME_DIR, STAGE_INSTALL, STAGE_CONFIG, STAGE_OK, STAGE_BAD); StringsArr = array of string; TCopyThreadData = record lock_install:TRTLCriticalSection; cmd_in_stop:boolean; progress_out:double; started:boolean; completed_out:boolean; error_out:string; end; { TMainForm } TMainForm = class(TForm) btn_elipsis: TButton; btn_next: TButton; check_update: TCheckBox; edit_path: TEdit; Image1: TImage; lbl_hint: TLabel; lbl_checkupdate: TLabel; progress: TProgressBar; SelectDirectoryDialog1: TSelectDirectoryDialog; Timer1: TTimer; procedure btn_elipsisClick(Sender: TObject); procedure btn_nextClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HideControls(); procedure Timer1Timer(Sender: TObject); private _bundle:file; _stage:TInstallStage; _cfg:TIniFile; _mod_dir:string; _game_dir:string; _bad_msg:string; _copydata:TCopyThreadData; _th_handle:THandle; procedure SwitchToStage(s:TInstallStage); function GetUpdaterPath():string; public end; var MainForm: TMainForm; implementation uses FastCrc, Localizer, registry, LazUTF8, userltxdumper, packer; {$R *.lfm} const MAIN_SECTION:string='main'; FILES_COUNT_PARAM:string='files_count'; BUILD_ID_PARAM:string='build_id'; FILE_SECT_PREFIX:string='file_'; FILE_KEY_PATH:string='path'; FILE_KEY_OFFSET:string='offset'; FILE_KEY_SIZE:string='size'; FILE_KEY_CRC32:string='crc32'; UNINSTALL_DATA_PATH:string='uninstall.dat'; USERDATA_PATH:string = 'userdata\'; USERLTX_PATH:string = 'userdata\user.ltx'; FSGAME_PATH:string='fsgame.ltx'; type TFileBytes = array of char; function GetMainConfigFromBundle(var bundle:file):TIniFile; var cfg_offset:int64; fsz:int64; cfg:TMemoryStream; c:char; begin result:=nil; cfg:=nil; cfg_offset:=0; try // The last 8 bytes are the offset of the config fsz:=FileSize(bundle); if fsz<=sizeof(cfg_offset) then exit; Seek(bundle, fsz-sizeof(cfg_offset)); BlockRead(bundle, cfg_offset, sizeof(cfg_offset)); if cfg_offset = 0 then exit; Seek(bundle, cfg_offset); cfg:=TMemoryStream.Create(); c:=chr(0); repeat BlockRead(bundle, c, sizeof(c)); if c<>chr(0) then cfg.Write(c, sizeof(c)); until ((c = chr(0)) or eof(bundle)); cfg.Seek(0, soBeginning); result:=TIniFile.Create(cfg); FreeAndNil(cfg); except FreeAndNil(cfg); FreeAndNil(result); end; end; class function TryHexToInt(hex: string; var out_val: cardinal): boolean; var i: integer; //err code r: Int64; //result begin val('$'+trim(hex),r, i); if i<>0 then begin result := false; end else begin result := true; out_val:=cardinal(r); end; end; function ReadFromBundle(var bundle:file; offset:int64; size:int64; var arr:TFileBytes):boolean; var arrsz:integer; begin result:=false; try if offset+size >= FileSize(bundle) then exit; arrsz:=length(arr); if int64(arrsz) < size then exit; Seek(bundle, offset); BlockRead(bundle, arr[0], size); result:=true; except result:=false; end; end; function ReadFileFromBundle(var bundle:file; cfg:TIniFile; index:cardinal):TFileBytes; var offset, size:int64; intsz:integer; sect:string; begin setlength(result, 0); sect:=FILE_SECT_PREFIX+inttostr(index); if not cfg.SectionExists(sect) then exit; offset:=cfg.ReadInt64(sect, FILE_KEY_OFFSET, -1); size:=cfg.ReadInt64(sect, FILE_KEY_SIZE, -1); if (offset < 0) or (size < 0) or (size >= $8FFFFFFF) then exit; intsz:=integer(size); setlength(result, intsz); if not ReadFromBundle(bundle, offset, size, result) then begin setlength(result, 0); end; end; function GetFilesCount(var {%H-}bundle:file; cfg:TIniFile):integer; begin result:=cfg.ReadInteger(MAIN_SECTION, FILES_COUNT_PARAM, 0); end; function ValidateBundle(var bundle:file; cfg:TIniFile):boolean; var i, cnt:integer; crc32, crc_ref:cardinal; sect, crcstr:string; ctx:TCRC32Context; arr:TFileBytes; begin result:=false; setlength(arr, 0); try cnt:=GetFilesCount(bundle, cfg); if cnt <= 0 then exit; for i:=0 to cnt-1 do begin Application.ProcessMessages(); sect:=FILE_SECT_PREFIX+inttostr(i); if not cfg.SectionExists(sect) then exit; if cfg.ReadString(sect, FILE_KEY_PATH, '') = '' then exit; crcstr:=cfg.ReadString(sect, FILE_KEY_CRC32, ''); if crcstr='' then exit; crc_ref:=0; if not TryHexToInt(crcstr, crc_ref) then exit; arr:=ReadFileFromBundle(bundle, cfg, i); if length(arr) = 0 then exit; Application.ProcessMessages(); ctx:=CRC32Start(); crc32:=CRC32End(ctx, @arr[0], length(arr)); if crc_ref <> crc32 then exit; setlength(arr, 0); end; result:=true; except result:=false; setlength(arr, 0); end; end; function SelectGuessedGameInstallDir():string; const REG_PATH:string = 'SOFTWARE\GSC Game World\STALKER-COP'; REG_PARAM:string = 'InstallPath'; var reg:TRegistry; begin try Reg:=TRegistry.Create(KEY_READ); Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey(REG_PATH,false); result:=Reg.ReadString(REG_PARAM); Reg.Free; except result:=''; end; result:=WinCPToUTF8(trim(result)); end; function CreateFsgame(parent_root:string):boolean; var f:textfile; begin result:=false; assignfile(f, FSGAME_PATH); try rewrite(f); parent_root:= '$game_root$ = false| false| '+ UTF8ToWinCP(parent_root); writeln(f, parent_root); {$IFDEF CHANGES_LOCKED} writeln(f, '$app_data_root$ = false | false | $fs_root$| userdata\'); writeln(f, '$game_data$ = false| true| $fs_root$| gamedata\'); writeln(f, '$game_ai$ = true| false| $game_data$| ai\'); writeln(f, '$game_spawn$ = true| false| $game_data$| spawns\'); writeln(f, '$game_levels$ = true| false| $game_data$| levels\'); writeln(f, '$game_meshes$ = true| true| $game_data$| meshes\'); writeln(f, '$game_anims$ = true| true| $game_data$| anims\'); writeln(f, '$game_dm$ = true| true| $game_data$| meshes\'); writeln(f, '$game_shaders$ = true| true| $game_data$| shaders\'); writeln(f, '$game_sounds$ = true| true| $game_data$| sounds\'); writeln(f, '$game_textures$ = true| true| $game_data$| textures\'); writeln(f, '$game_config$ = true| false| $game_data$| configs\'); writeln(f, '$game_weathers$ = true| false| $game_config$| environment\weathers'); writeln(f, '$game_weather_effects$ = true| false| $game_config$| environment\weather_effects'); writeln(f, '$textures$ = true| true| $game_data$| textures\'); writeln(f, '$level$ = false| false| $game_levels$'); writeln(f, '$game_scripts$ = true| false| $game_data$| scripts\'); writeln(f, '$arch_dir$ = false| false| $game_root$'); writeln(f, '$arch_dir_levels$ = false| false| $game_root$| levels\'); writeln(f, '$arch_dir_resources$ = false| false| $game_root$| resources\'); writeln(f, '$arch_dir_localization$ = false| false| $game_root$| localization\'); writeln(f, '$arch_dir_patches$ = false| true| $fs_root$| patches\'); writeln(f, '$game_arch_mp$ = false| false| $game_root$| mp\'); writeln(f, '$logs$ = true| false| $app_data_root$| logs\'); writeln(f, '$screenshots$ = true| false| $app_data_root$| screenshots\'); writeln(f, '$game_saves$ = true| false| $app_data_root$| savedgames\'); writeln(f, '$downloads$ = false| false| $app_data_root$'); {$ELSE} writeln(f, '$app_data_root$ = false | false | $fs_root$| userdata\'); writeln(f, '$arch_dir$ = false| false| $game_root$'); writeln(f, '$arch_dir_levels$ = false| false| $game_root$| levels\'); writeln(f, '$arch_dir_resources$ = false| false| $game_root$| resources\'); writeln(f, '$arch_dir_localization$ = false| false| $game_root$| localization\'); writeln(f, '$arch_dir_patches$ = false| true| $fs_root$| patches\'); writeln(f, '$game_arch_mp$ = false| false| $game_root$| mp\'); writeln(f, '$game_data$ = false| true| $fs_root$| gamedata\'); writeln(f, '$game_ai$ = true| false| $game_data$| ai\'); writeln(f, '$game_spawn$ = true| false| $game_data$| spawns\'); writeln(f, '$game_levels$ = true| false| $game_data$| levels\'); writeln(f, '$game_meshes$ = true| true| $game_data$| meshes\'); writeln(f, '$game_anims$ = true| true| $game_data$| anims\'); writeln(f, '$game_dm$ = true| true| $game_data$| meshes\'); writeln(f, '$game_shaders$ = true| true| $game_data$| shaders\'); writeln(f, '$game_sounds$ = true| true| $game_data$| sounds\'); writeln(f, '$game_textures$ = true| true| $game_data$| textures\'); writeln(f, '$game_config$ = true| false| $game_data$| configs\'); writeln(f, '$game_weathers$ = true| false| $game_config$| environment\weathers'); writeln(f, '$game_weather_effects$ = true| false| $game_config$| environment\weather_effects'); writeln(f, '$textures$ = true| true| $game_data$| textures\'); writeln(f, '$level$ = false| false| $game_levels$'); writeln(f, '$game_scripts$ = true| false| $game_data$| scripts\'); writeln(f, '$logs$ = true| false| $app_data_root$| logs\'); writeln(f, '$screenshots$ = true| false| $app_data_root$| screenshots\'); writeln(f, '$game_saves$ = true| false| $app_data_root$| savedgames\'); writeln(f, '$downloads$ = false| false| $app_data_root$'); {$ENDIF} closefile(f); result:=true; except result:=false; end; end; function CheckAndCorrectUserltx():boolean; var f:textfile; begin result:=FileExists(USERLTX_PATH); if not result then begin ForceDirectories(USERDATA_PATH); assignfile(f, USERLTX_PATH); try rewrite(f); DumpUserLtx(f, screen.Width, screen.Height, true); closefile(f); result:=true; except result:=false; end; end; end; procedure PushToArray(var a:StringsArr; s:string); var i:integer; begin i:=length(a); setlength(a, i+1); a[i]:=s; end; function AddTerminalSlash(path:string):string; begin if (length(path)>0) and (path[length(path)]<>'\') and (path[length(path)]<>'/') then begin path:=path+'\'; end; result:=path; end; function IsGameInstalledInDir(dir:string):boolean; var files:StringsArr; i:integer; filename:string; begin result:=false; setlength(files, 0); PushToArray(files, 'resources\configs.db'); PushToArray(files, 'resources\resources.db0'); PushToArray(files, 'resources\resources.db1'); PushToArray(files, 'resources\resources.db2'); PushToArray(files, 'resources\resources.db3'); PushToArray(files, 'resources\resources.db4'); PushToArray(files, 'levels\levels.db0'); PushToArray(files, 'levels\levels.db1'); dir:=AddTerminalSlash(dir); for i:=0 to length(files)-1 do begin filename:=dir+files[i]; if not FileExists(filename) then begin exit; end; end; result:=true; end; function PreparePathForFile(filepath:string):boolean; begin result:=false; while (length(filepath)>0) and (filepath[length(filepath)]<>'\') and (filepath[length(filepath)]<>'/') do begin filepath:=leftstr(filepath, length(filepath)-1); end; if length(filepath)<=0 then begin result:=true; exit; end; result:=ForceDirectories(filepath); end; function DirectoryIsEmpty(Directory:string): boolean; var sr: TSearchRec; i: Integer; begin Result := false; FindFirst( IncludeTrailingPathDelimiter( Directory ) + '*', faAnyFile, sr ); for i := 1 to 2 do if ( sr.Name = '.' ) or ( sr.Name = '..' ) then Result := FindNext( sr ) <> 0; FindClose( sr ); end; procedure KillFileAndEmptyDir(filepath:string); begin DeleteFile(filepath); while (length(filepath)>0) and (filepath[length(filepath)]<>'\') and (filepath[length(filepath)]<>'/') do begin filepath:=leftstr(filepath, length(filepath)-1); end; if (length(filepath)>0) and DirectoryExists(filepath) and DirectoryIsEmpty(filepath) then begin RemoveDir(filepath); end; end; function RevertChanges(changes_cfg:string):boolean; var install_log:textfile; filepath:string; begin result:=false; assignfile(install_log, changes_cfg); try reset(install_log); while not eof(install_log) do begin readln(install_log, filepath); KillFileAndEmptyDir(filepath); end; KillFileAndEmptyDir(USERLTX_PATH); KillFileAndEmptyDir(FSGAME_PATH); CloseFile(install_log); KillFileAndEmptyDir(changes_cfg) except result:=false; end; end; function ConfirmDirForInstall(var dir:string; var gamedir:string; skip_unexist:boolean):boolean; var res:integer; begin result:=true; if IsGameInstalledInDir(dir) then begin dir:=AddTerminalSlash(dir); gamedir:=dir; dir:=dir+'GUNSLINGER_Mod\'; result:=ConfirmDirForInstall(dir, gamedir, true); end else if not skip_unexist and not DirectoryExists(dir) then begin res:=Application.MessageBox(PAnsiChar(LocalizeString('confirm_dir_unexist')), PAnsiChar(LocalizeString('msg_confirm')), MB_YESNO or MB_ICONQUESTION); result:= res=IDYES; end else if DirectoryExists(dir) and not DirectoryIsEmpty(dir) then begin res:=Application.MessageBox(PAnsiChar(LocalizeString('confirm_dir_nonempty')), PAnsiChar(LocalizeString('msg_confirm')), MB_YESNO or MB_ICONQUESTION); result:= res=IDYES; end; end; function ConfirmGameDir(dir:string):boolean; var res:integer; begin result:=true; if not IsGameInstalledInDir(dir) then begin res:=Application.MessageBox(PAnsiChar(LocalizeString('msg_no_game_in_dir')), PAnsiChar(LocalizeString('msg_confirm')), MB_YESNO or MB_ICONQUESTION); result:= res=IDYES; end; end; { TMainForm } procedure TMainForm.FormCreate(Sender: TObject); begin _stage:=STAGE_INIT; _copydata.started:=false; InitializeCriticalSection(_copydata.lock_install); HideControls(); self.Image1.Top:=0; self.Image1.Left:=0; self.Image1.Width:=self.Image1.Picture.Width; self.Image1.Height:=self.Image1.Picture.Height; self.Width:=self.Image1.Width; self.Height:=self.Image1.Height; edit_path.Left:=30; edit_path.Width:=self.Width-100; edit_path.Top:=(self.Height) div 2; progress.Left:=edit_path.Left; progress.Width:=edit_path.Width; progress.Top:=edit_path.Top; lbl_hint.Left:=edit_path.Left; lbl_hint.Top:=edit_path.Top - lbl_hint.Height - 2; btn_elipsis.Top:=edit_path.Top-1; btn_elipsis.Left:=edit_path.Left+edit_path.Width+5; btn_next.Top:=edit_path.Top+edit_path.Height+20; btn_next.Left:=edit_path.Left + ((edit_path.Width - btn_next.Width) div 2); _cfg:=nil; SwitchToStage(STAGE_INTEGRITY); timer1.Interval:=200; timer1.Enabled:=true; end; procedure TMainForm.btn_elipsisClick(Sender: TObject); begin SelectDirectoryDialog1.FileName:=''; SelectDirectoryDialog1.InitialDir:=edit_path.Text; if SelectDirectoryDialog1.Execute() then begin edit_path.Text:=SelectDirectoryDialog1.FileName; end; end; procedure TMainForm.btn_nextClick(Sender: TObject); var gamedir, updater_path:string; pi:TPROCESSINFORMATION; si:TSTARTUPINFO; begin edit_path.Text:=AddTerminalSlash(edit_path.Text); if (_stage = STAGE_SELECT_DIR) then begin gamedir:=''; _mod_dir:=edit_path.Text; if ConfirmDirForInstall(_mod_dir, gamedir, false) then begin if length(gamedir)=0 then begin SwitchToStage(STAGE_SELECT_GAME_DIR); end else begin _game_dir:=gamedir; SwitchToStage(STAGE_INSTALL); end; end; end else if (_stage = STAGE_SELECT_GAME_DIR) and (ConfirmGameDir(edit_path.Text)) then begin _game_dir:=edit_path.Text; SwitchToStage(STAGE_INSTALL); end else if (_stage = STAGE_BAD) or (_stage=STAGE_OK) or (_stage=STAGE_PACKING_SUCCESS) then begin if (_stage=STAGE_OK) and check_update.Checked then begin updater_path:=GetUpdaterPath(); FillMemory(@si, sizeof(si),0); FillMemory(@pi, sizeof(pi),0); si.cb:=sizeof(si); CreateProcess(PAnsiChar(updater_path), PAnsiChar(updater_path), nil, nil, false, 0, nil, nil, si, pi); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); end; Application.Terminate(); end else if (_stage = STAGE_PACKING) then begin if BundleToInstaller(edit_path.Text, Application.ExeName) then begin SwitchToStage(STAGE_PACKING_SUCCESS); end else begin _bad_msg:='err_unk'; SwitchToStage(STAGE_BAD); end; end; end; procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); var res:integer; dis_tmr:boolean; begin if (_stage=STAGE_OK) or (_stage=STAGE_BAD) or (_stage=STAGE_PACKING_SUCCESS) then begin exit; end; CloseAction:=caNone; dis_tmr:=false; if Timer1.Enabled then begin dis_tmr:=true; timer1.Enabled:=false; end; res:=Application.MessageBox(PAnsiChar(LocalizeString('confirm_close')), PAnsiChar(LocalizeString('msg_confirm')), MB_YESNO or MB_ICONQUESTION); if res = IDYES then begin _bad_msg:=LocalizeString('user_cancelled'); SwitchToStage(STAGE_BAD); end; if dis_tmr then begin timer1.Enabled:=true; end; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FreeAndNil(_cfg); DeleteCriticalSection(_copydata.lock_install); end; procedure TMainForm.HideControls(); begin edit_path.Text:=''; edit_path.Hide; lbl_hint.Caption:=''; lbl_hint.Hide; btn_elipsis.Hide; btn_next.Hide; progress.Hide; lbl_checkupdate.Hide; check_update.Hide; check_update.Checked:=false; end; procedure CopierThread(frm:TMainForm); stdcall; var bundle:file; cfg:TIniFile; badmsg:string; install_log:textfile; i, total:integer; arr:TFileBytes; fname:string; outf:file; begin EnterCriticalSection(frm._copydata.lock_install); try frm._copydata.started:=true; frm._copydata.completed_out:=false; frm._copydata.progress_out:=0; frm._copydata.error_out:=''; bundle:=frm._bundle; cfg:=frm._cfg; finally LeaveCriticalSection(frm._copydata.lock_install); end; badmsg:=''; setlength(arr, 0); //Start magic assignfile(install_log, UNINSTALL_DATA_PATH); try rewrite(install_log); total:=GetFilesCount(bundle, cfg); for i:=0 to total-1 do begin EnterCriticalSection(frm._copydata.lock_install); try //Check for stop cmd frm._copydata.progress_out:= (i+1) / total; if frm._copydata.cmd_in_stop then begin; badmsg:='user_cancelled'; end; finally LeaveCriticalSection(frm._copydata.lock_install); end; if badmsg<>'' then break; //------------- arr:=ReadFileFromBundle(bundle, cfg, i); if length(arr) = 0 then begin badmsg:='err_cant_read_bundle_content'; break; end; fname:=cfg.ReadString(FILE_SECT_PREFIX+inttostr(i), FILE_KEY_PATH, ''); writeln(install_log, fname); if not PreparePathForFile(fname) then begin badmsg:='err_cant_create_dir'; end else begin assignfile(outf, fname); try rewrite(outf, 1); BlockWrite(outf, arr[0], length(arr)); closefile(outf); except badmsg:='err_writing_file'; end; end; if badmsg<>'' then break; end; except badmsg:='err_unk'; end; try // Guarantee file closing - need for further revert closefile(install_log); except end; setlength(arr, 0); // Finish EnterCriticalSection(frm._copydata.lock_install); try frm._copydata.completed_out:=true; frm._copydata.error_out:=badmsg; frm._copydata.progress_out:=1; finally LeaveCriticalSection(frm._copydata.lock_install); end; end; procedure TMainForm.Timer1Timer(Sender: TObject); var valid_bundle:boolean; cfg:TIniFile; build_id:string; tid:cardinal; begin if (_stage = STAGE_INTEGRITY) and (_cfg = nil) then begin timer1.Enabled:=false; assignfile(_bundle, Application.ExeName); valid_bundle:=false; cfg:=nil; try FileMode:=fmOpenRead; reset(_bundle, 1); cfg:=GetMainConfigFromBundle(_bundle); if cfg <> nil then begin build_id:=cfg.ReadString(MAIN_SECTION, BUILD_ID_PARAM, ''); if length(build_id) > 0 then begin self.Caption:=self.Caption+' ('+build_id+')'; end; valid_bundle:=ValidateBundle(_bundle, cfg); end else begin valid_bundle:=false; end; except valid_bundle:=false; end; if valid_bundle then begin _cfg:=cfg; SwitchToStage(STAGE_SELECT_DIR); end else if (cfg=nil) then begin FreeAndNil(cfg); CloseFile(_bundle); SwitchToStage(STAGE_PACKING); end else begin Application.MessageBox(PAnsiChar(LocalizeString('err_bundle_corrupt')),PAnsiChar(LocalizeString('err_caption')), MB_OK); FreeAndNil(cfg); CloseFile(_bundle); SwitchToStage(STAGE_BAD); _bad_msg:='err_cant_read_bundle_content'; end; timer1.Enabled:=true; end else if _stage = STAGE_INSTALL then begin timer1.Enabled:=false; _bad_msg:=''; EnterCriticalSection(_copydata.lock_install); try if _copydata.progress_out < 0 then begin _copydata.progress_out:=0; _copydata.completed_out:=false; _copydata.cmd_in_stop:=false; _copydata.error_out:=''; _copydata.started:=true;; if not ForceDirectories(_mod_dir) or not SetCurrentDir(_mod_dir) then begin _bad_msg:='err_cant_create_dir'; SwitchToStage(STAGE_BAD); end else begin _mod_dir:='./'; tid:=0; _th_handle:=CreateThread(nil, 0, @CopierThread, self, 0, tid); if _th_handle = 0 then begin _copydata.started:=false; end; CloseHandle(_th_handle); end; end else if _copydata.completed_out then begin; if length(_copydata.error_out) > 0 then begin _bad_msg:=_copydata.error_out; SwitchToStage(STAGE_BAD); end else begin SwitchToStage(STAGE_CONFIG); end; end; progress.Position:=progress.Min+round((progress.Max-progress.Min)*_copydata.progress_out); finally LeaveCriticalSection(_copydata.lock_install); end; timer1.Enabled:=true; end else if _stage = STAGE_CONFIG then begin timer1.Enabled:=false; if not CreateFsgame(_game_dir) or not CheckAndCorrectUserltx() then begin _bad_msg:='err_writing_file'; SwitchToStage(STAGE_BAD); end else begin SwitchToStage(STAGE_OK); end; timer1.Enabled:=true; end else if _stage = STAGE_BAD then begin timer1.Enabled:=false; EnterCriticalSection(_copydata.lock_install); try if _copydata.started and not _copydata.completed_out then begin _copydata.cmd_in_stop:=true; end else if _copydata.started then begin RevertChanges(UNINSTALL_DATA_PATH); _copydata.started:=false; end else begin lbl_hint.Caption:=LocalizeString(_bad_msg); btn_next.Enabled:=true; end; finally LeaveCriticalSection(_copydata.lock_install); end; timer1.Enabled:=true; end; end; procedure TMainForm.SwitchToStage(s: TInstallStage); var dir:string; begin HideControls(); case s of STAGE_INTEGRITY: begin assert(_stage = STAGE_INIT); lbl_hint.Caption:=LocalizeString('stage_integrity_check'); lbl_hint.Show; end; STAGE_PACKING: begin assert(_stage = STAGE_INIT); lbl_hint.Caption:=LocalizeString('stage_packing_select'); lbl_hint.Show; btn_next.Caption:=LocalizeString('btn_next'); btn_next.Show(); edit_path.Text:=GetCurrentDir(); edit_path.Show; btn_elipsis.Show(); end; STAGE_PACKING_SUCCESS: begin btn_next.Caption:=LocalizeString('exit_installer'); btn_next.Show(); lbl_hint.Caption:=LocalizeString('packing_completed'); lbl_hint.Show(); end; STAGE_SELECT_DIR: begin assert(_stage = STAGE_INTEGRITY); btn_next.Caption:=LocalizeString('btn_next'); btn_next.Show(); dir:=GetCurrentDir(); dir:=AddTerminalSlash(dir); edit_path.Text:=dir+'GUNSLINGER_Mod\'; edit_path.Show; lbl_hint.Caption:=LocalizeString('hint_select_install_dir'); lbl_hint.Show(); btn_elipsis.Show(); end; STAGE_SELECT_GAME_DIR: begin assert(_stage = STAGE_SELECT_DIR); btn_next.Caption:=LocalizeString('btn_next'); btn_next.Show(); edit_path.Text:=SelectGuessedGameInstallDir(); edit_path.Show; lbl_hint.Caption:=LocalizeString('hint_select_game_dir'); lbl_hint.Show(); btn_elipsis.Show(); end; STAGE_INSTALL: begin assert(_stage = STAGE_SELECT_GAME_DIR); lbl_hint.Caption:=LocalizeString('installing'); lbl_hint.Show(); progress.Max:=100; progress.Min:=0; progress.Position:=0; progress.Show(); _copydata.progress_out:=-1; _copydata.started:=false; end; STAGE_CONFIG: begin assert(_stage = STAGE_INSTALL); lbl_hint.Caption:=LocalizeString('stage_finalizing'); lbl_hint.Show(); end; STAGE_OK: begin btn_next.Caption:=LocalizeString('exit_installer'); btn_next.Show(); lbl_hint.Caption:=LocalizeString('success_install'); lbl_hint.Show(); if length(GetUpdaterPath())>0 then begin lbl_checkupdate.Caption:=LocalizeString('run_updater'); lbl_checkupdate.Show(); check_update.Checked:=true; check_update.Show(); end; end; STAGE_BAD: begin btn_next.Caption:=LocalizeString('exit_installer'); btn_next.Show(); lbl_hint.Caption:=LocalizeString('reverting_changes'); lbl_hint.Show(); btn_next.Enabled:=false; end; end; _stage:=s; end; function TMainForm.GetUpdaterPath(): string; begin result:=''; if length(_mod_dir)> 0 then begin result:=_mod_dir+'CheckUpdates.exe'; if not FileExists(result) then begin result:=''; end; end; end; end.
unit StationaryStocksFRM; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.UITypes, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, StockController, VirtualTrees, System.Actions, Vcl.ActnList; type TfrmStationaryStocks = class(TForm) Panel1: TPanel; StocksTree: TVirtualStringTree; ActionList: TActionList; FilterAction: TAction; ResetFilterAction: TAction; AddAction: TAction; EditAction: TAction; DeleteAction: TAction; CancelAction: TAction; PrintAction: TAction; DesignAction: TAction; FindPatientAction: TAction; ClearPatientAction: TAction; PreviewAction: TAction; btnAdd: TButton; btnEdit: TButton; btnDelete: TButton; btnClose: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure StocksTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure StocksTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure StocksTreeDblClick(Sender: TObject); private FStockController: TStockController; procedure StockControllerListChanged(ASender: TObject); function ShowAddNewStock: boolean; { Private declarations } public { Public declarations } end; implementation uses StockDetailsFRM; {$R *.dfm} procedure TfrmStationaryStocks.FormCreate(Sender: TObject); begin FStockController := TStockController.Create; FStockController.OnListChanged := StockControllerListChanged; StocksTree.NodeDataSize := SizeOf(TStock); FStockController.LoadStocks; end; procedure TfrmStationaryStocks.FormDestroy(Sender: TObject); begin FStockController.Free; end; procedure TfrmStationaryStocks.FormShow(Sender: TObject); begin if StocksTree.CanFocus then StocksTree.SetFocus; end; procedure TfrmStationaryStocks.btnAddClick(Sender: TObject); begin if ShowAddNewStock then FStockController.LoadStocks; end; procedure TfrmStationaryStocks.btnEditClick(Sender: TObject); var LStockDetailsFRM: TfrmStockDetails; LStock: TStock; begin if not Assigned(StocksTree.FocusedNode) then Exit; LStock := StocksTree.FocusedNode.GetData<TStock>; LStockDetailsFRM := TfrmStockDetails.Create(nil); try LStockDetailsFRM.Stock := LStock; if LStockDetailsFRM.ShowModal = mrOK then begin FStockController.EditStock(LStock); FStockController.LoadStocks; end; finally LStockDetailsFRM.Free; end; end; procedure TfrmStationaryStocks.btnDeleteClick(Sender: TObject); var LNode: PVirtualNode; LStock: TStock; begin LNode := StocksTree.FocusedNode; if Assigned(LNode) then begin LStock := LNode.GetData<TStock>; if MessageDlg('Are you sure to delete the Stock for StockId ' + IntToStr(LStock.StockId) + '?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin FStockController.DeleteStock(LStock); end; end; end; procedure TfrmStationaryStocks.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmStationaryStocks.StocksTreeInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin Node.SetData<TStock>(FStockController.StockList[Node.Index]); end; procedure TfrmStationaryStocks.StocksTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var LStock: TStock; begin LStock := Node.GetData<TStock>; case Column of 0: CellText := IntToStr(LStock.StockId); 1: CellText := LStock.ItemName; 2: CellText := IntToStr(LStock.Quantity); 3: CellText := FloatToStr(LStock.UnitPrice); end; end; procedure TfrmStationaryStocks.StocksTreeDblClick(Sender: TObject); begin btnEditClick(Sender); end; procedure TfrmStationaryStocks.StockControllerListChanged(ASender: TObject); begin StocksTree.RootNodeCount := FStockController.StockList.Count; StocksTree.ReinitNode(nil, True); end; function TfrmStationaryStocks.ShowAddNewStock: boolean; var LStockDetailsFRM: TfrmStockDetails; LStock: TStock; begin result := false; LStockDetailsFRM := TfrmStockDetails.Create(nil); LStockDetailsFRM.StockMode := smNew; try LStock := TStock.Create; LStockDetailsFRM.Stock := LStock; if LStockDetailsFRM.ShowModal = mrOK then begin // LStock := TStock.Create; // LStock.ItemId := StrToInt(LStockDetailsFRM.edtItemId.Text); // LStock.ItemName := LStockDetailsFRM.edtItemName.Text; // LStock.ItemDescription := LStockDetailsFRM.edtItemId.Text; // LStock.Updated_Date := now; // LStock.Quantity := StrToInt(LStockDetailsFRM.edtQuantity.Text); // LStock.UnitPrice := StrToFloat(LStockDetailsFRM.edtPrice.Text); // LStock.Comments := LStockDetailsFRM.mmStockComments.Text; FStockController.AddStock(LStock); result := True; end; finally LStockDetailsFRM.Free; end; end; end.
unit frmCustomer; interface uses module, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm3 = class(TForm) Panel1: TPanel; Label2: TLabel; Label1: TLabel; txtCode: TEdit; txtName: TEdit; txtCpf: TEdit; Label5: TLabel; txtTel: TEdit; Label6: TLabel; txtEmail: TEdit; Label7: TLabel; Panel3: TPanel; txtCity: TEdit; Label8: TLabel; Label9: TLabel; txtAddress: TEdit; txtComplement: TEdit; Label10: TLabel; txtPostCode: TEdit; Label3: TLabel; cbState: TComboBox; Label4: TLabel; txtDistrict: TEdit; Label11: TLabel; panelFooter: TPanel; btnRemove: TButton; btnSave: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnSaveClick(Sender: TObject); function validates(): boolean; procedure txtPostCodeChange(Sender: TObject); procedure btnRemoveClick(Sender: TObject); private { Private declarations } public { Public declarations } newRecord: Boolean; procedure loadCustomer(codigo: String); end; var Form3: TForm3; dt: TDm; codCity: string; isLoading: boolean; implementation {$R *.dfm} function TForm3.validates(): boolean; begin validates := false; if Length(txtCode.Text) = 0 then begin ShowMessage('Por favor, preencha o código do cliente para continuar!'); txtCode.SetFocus; exit; end else if newRecord then begin dt.sqlCity.SQL.Clear; dt.sqlCity.SQL.Add('SELECT COUNT(*) AS qtd FROM clientes WHERE codigo_cliente = ' + QuotedStr(txtCode.Text)); dt.sqlCity.Open; if dt.sqlCity.FieldByName('qtd').Value > 0 then begin ShowMessage('O código do cliente deve ser único!'); txtCode.SetFocus; exit; end; end; if Length(txtName.Text) = 0 then begin ShowMessage('Por favor, preencha o nome do cliente para continuar!'); txtName.SetFocus; exit; end; if Length(txtCity.Text) = 0 then begin ShowMessage('Por favor, certifique-se de que o cep está preenchido corretamente e que exista uma cidade com esse cep cadastrado no sistema!'); txtPostCode.SetFocus; exit; end; validates := true; end; procedure TForm3.btnRemoveClick(Sender: TObject); begin if MessageDlg('Deseja mesmo remover esse cliente?', mtConfirmation,[mbYes, mbNo], 0) = mrNo then exit; try dt.sqlCity.Close; dt.sqlCity.SQL.Clear; dt.sqlCity.SQL.Add('DELETE FROM clientes WHERE codigo_cliente = ' + txtCode.Text ); dt.sqlCity.ExecSQL(); finally ShowMessage('Cliente removido com sucesso!'); Self.Hide; end; end; procedure TForm3.btnSaveClick(Sender: TObject); begin if not validates() then exit; try dt.sqlCity.Close; dt.sqlCity.SQL.Clear; if newRecord then dt.sqlCity.SQL.Add('INSERT INTO clientes (codigo_cliente, nome, CGC_CPF_Cliente, Telefone, Endereco, Bairro, Complemento, E_mail, codigo_cidade, cep) VALUES ('+ QuotedStr(txtCode.Text) + ', ' + QuotedStr(txtName.Text) + ', ' + QuotedStr(txtCpf.Text) + ', ' + QuotedStr(txtTel.Text) + ',' + QuotedStr(txtAddress.Text) + ',' + QuotedStr(txtDistrict.Text) + ', ' + QuotedStr(txtComplement.Text) + ', ' + QuotedStr(txtEmail.Text) + ', ' + QuotedStr(codCity) + ', ' + QuotedStr(txtPostCode.Text) + ')' ) else dt.sqlCity.SQL.Add('UPDATE clientes SET nome = ' + QuotedStr(txtName.Text) + ', CGC_CPF_Cliente = ' + QuotedStr(txtCpf.Text) + ', Telefone = ' + QuotedStr(txtTel.Text) + ', Endereco = ' + QuotedStr(txtAddress.Text) + ', Bairro = ' + QuotedStr(txtDistrict.Text) + ', Complemento = ' + QuotedStr(txtComplement.Text) + ', E_mail = ' + QuotedStr(txtEmail.Text) + ', codigo_cidade = ' + QuotedStr(codCity) + ', cep = ' + QuotedStr(txtPostCode.Text) + ' WHERE codigo_cliente = ' + QuotedStr(txtCode.Text)); dt.sqlCity.ExecSQL(); finally if newRecord then begin ShowMessage('Cliente cadastrado com sucesso!'); btnRemove.Enabled := true; end else ShowMessage('Cliente alterado com sucesso!'); end; end; procedure TForm3.loadCustomer(codigo: String); begin dt.sqlCity.Close; dt.sqlCity.SQL.Clear; if newRecord then begin dt.sqlCity.SQL.Add('SELECT ISNULL(MAX(codigo_cliente) + 1, 1) AS newCode FROM clientes'); dt.sqlCity.Open; txtCode.Text := dt.sqlCity.FieldByName('newCode').Value; exit; end; isLoading := true; dt.sqlCity.SQL.Add('SELECT clientes.*, cidades.codigo_cidade AS codigocidade, cidades.nome AS cidade, cidades.estado FROM clientes LEFT JOIN cidades ON cidades.codigo_cidade = clientes.codigo_cidade WHERE codigo_cliente = ' + QuotedStr(codigo)); dt.sqlCity.Open; if dt.sqlCity.Eof then begin ShowMessage('Não foi possível encontrar o cliente selecionado, por favor, tente novamente!'); exit; end else begin txtCode.Text := dt.sqlCity.FieldByName('codigo_cliente').Value; txtName.Text := dt.sqlCity.FieldByName('nome').Value; txtCpf.Text := dt.sqlCity.FieldByName('CGC_CPF_Cliente').Value; txtTel.Text := dt.sqlCity.FieldByName('telefone').Value; txtEmail.Text := dt.sqlCity.FieldByName('e_mail').Value; txtPostCode.Text := dt.sqlCity.FieldByName('cep').Value; txtCity.Text := dt.sqlCity.FieldByName('cidade').Value; cbState.ItemIndex := cbState.Items.IndexOf(dt.sqlCity.FieldByName('estado').Value); txtDistrict.Text := dt.sqlCity.FieldByName('bairro').Value; txtAddress.Text := dt.sqlCity.FieldByName('endereco').Value; txtComplement.Text := dt.sqlCity.FieldByName('complemento').Value; codCity := dt.sqlCity.FieldByName('codigocidade').Value; end; isLoading:=false; end; procedure TForm3.FormCreate(Sender: TObject); begin dt := TDm.Create(Self); end; procedure TForm3.FormShow(Sender: TObject); begin txtName.SetFocus; end; procedure TForm3.txtPostCodeChange(Sender: TObject); begin if isLoading then exit; if Length(txtPostCode.Text) = 8 then begin try dt.sqlCity.Close; dt.sqlCity.SQL.Clear; dt.sqlCity.SQL.Add('SELECT codigo_cidade, nome, estado FROM cidades WHERE ' + QuotedStr(txtPostCode.Text) + ' BETWEEN cep_inicial AND cep_final'); dt.sqlCity.Open; finally if not dt.sqlCity.Eof then begin txtCity.Text := dt.sqlCity.FieldByName('nome').Value; cbState.ItemIndex := cbState.Items.IndexOf(dt.sqlCity.FieldByName('estado').Value); codCity := dt.sqlCity.FieldByName('codigo_cidade').Value; end; end; end else begin txtCity.Text := ''; cbState.ItemIndex := -1; codCity := ''; end; end; end.
unit ZMDirectory; // ZMDirectory.pas - Represents the readable Directory of a Zip file (* *************************************************************************** TZipMaster VCL originally by Chris Vleghert, Eric W. Engler. Present Maintainers and Authors Roger Aelbrecht and Russell Peters. Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler Copyright (C) 1992-2008 Eric W. Engler Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht The MIT License (MIT) Copyright (c) 2014, 2015 delphizip 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. contact: problems AT delphizip DOT org updates: http://www.delphizip.org *************************************************************************** *) // modified 2015-05-05 {$INCLUDE '.\ZipVers.inc'} interface uses {$IFDEF VERDXE2up} // Delphi XE2 or newer System.Classes, {WinApi.Windows,} System.Contnrs, {$ELSE} Classes, {Windows,} Contnrs, {$ENDIF} ZipMstr, ZMBody, ZMEOC, ZMStructs, ZMHashTable, ZMCentral; type TZMEntryBase = class; TZMDirectory = class(TZMEOC) private FArgsList: TZMSelectArgs; FEntries: TZMHashedCentralList; FOnChange: TZCChangeEvent; FOpenRet: Integer; FSelCount: Integer; FSFXOfs: Cardinal; FSOCOfs: Int64; FStub: TMemoryStream; FUseSFX: Boolean; function GetCount: Integer; function GetFirstSelected: TZMEntryBase; function GetHashTable: TZMHashTable; function GetItems(Index: Integer): TZMEntryBase; procedure SetStub(const Value: TMemoryStream); protected procedure ClearEntries; procedure InferNumbering; procedure MarkDirty; procedure RemoveEntry(Entry: TZMEntryBase); function SelectEntry(Rec: TZMEntryBase; How: TZMSelects): Boolean; property Entries: TZMHashedCentralList read FEntries; public function Add(Rec: TZMEntryBase): Integer; function AddSelectArgs(Args: TZMSelectArgs): TZMSelectArgs; procedure AfterConstruction; override; procedure AssignStub(From: TZMDirectory); procedure BeforeDestruction; override; procedure ClearArgsList; procedure ClearCachedNames; procedure ClearSelection; function FindName(const Name: string; const NotMe: TZMEntryBase = nil) : TZMEntryBase; procedure FreeSelectArgs(Args: TZMSelectArgs); function HasDupName(const Rec: TZMEntryBase): TZMEntryBase; // 1 Mark as Contents Invalid procedure Invalidate; function NextSelected(CurRec: TZMEntryBase): TZMEntryBase; function SearchName(const Pattern: string; IsWild: Boolean; After: Integer) : TZMEntryBase; function SearchNameEx(const Pattern: string; IsWild: Boolean; After: TZMEntryBase): TZMEntryBase; function Select(const Pattern: string; How: TZMSelects): Integer; function SelectFile(const Pattern, Reject: string; How: TZMSelects) : Integer; function SelectFiles(const Want, Reject: TStrings): Integer; function SelectRec(const Pattern, Reject: string; How: TZMSelects; SelArgs: TZMSelectArgs): Integer; property ArgsList: TZMSelectArgs read FArgsList; property Count: Integer read GetCount; property FirstSelected: TZMEntryBase read GetFirstSelected; property HashTable: TZMHashTable read GetHashTable; property Items[Index: Integer]: TZMEntryBase read GetItems; default; property OpenRet: Integer read FOpenRet write FOpenRet; property SelCount: Integer read FSelCount write FSelCount; property SFXOfs: Cardinal read FSFXOfs write FSFXOfs; property SOCOfs: Int64 read FSOCOfs write FSOCOfs; property Stub: TMemoryStream read FStub write SetStub; property UseSFX: Boolean read FUseSFX write FUseSFX; property OnChange: TZCChangeEvent read FOnChange write FOnChange; end; TZMEntryBase = class(TZMCentralItem) private FBody: TZMBody; FMyFile: TZMDirectory; FXName: string; function GetXName: string; function VerifyLocalName(const LocalHeader: TZipLocalHeader; const HName: TZMRawBytes): Integer; protected function GetMaster: TCustomZipMaster; function IsZip64: Boolean; procedure MarkDirty; property Master: TCustomZipMaster read GetMaster; public constructor Create(TheOwner: TZMDirectory); procedure AssignFrom(const Zr: TZMCentralItem); override; function SeekLocalData(var LocalHeader: TZipLocalHeader; const HName: TZMRawBytes): Integer; property Body: TZMBody read FBody; property MyFile: TZMDirectory read FMyFile write FMyFile; property XName: string read GetXName write FXName; end; implementation uses {$IFDEF VERDXE2up} // Delphi XE2 or newer System.SysUtils, WinApi.Windows, {$ELSE} SysUtils, Windows, {$IFNDEF UNICODE}ZMCompat, {$ENDIF} {$ENDIF} ZMCore, ZMFileIO, ZMMsg, ZMXcpt, ZMUtils, ZMNameUtils, ZMWinFuncsU, ZMWinFuncsA, ZMDiags; const __UNIT__ = 16; const _U_ = (__UNIT__ shl ZERR_LINE_SHIFTS); const HTChainsMax = 65537; HTChainsMin = 61; const AllSpec: string = '*.*'; AnySpec: string = '*'; // returns index function TZMDirectory.Add(Rec: TZMEntryBase): Integer; begin Result := Entries.Add(Rec); if Result >= 0 then Rec.ExtIndex := Result; end; function TZMDirectory.AddSelectArgs(Args: TZMSelectArgs): TZMSelectArgs; begin Result := Args; if Args = nil then Exit; Args.Next := FArgsList; FArgsList := Args; // chain it end; procedure TZMDirectory.AfterConstruction; begin inherited; FEntries := TZMHashedCentralList.Create; FEntries.OwnsEntries := True; end; procedure TZMDirectory.AssignStub(From: TZMDirectory); begin FreeAndNil(FStub); FStub := From.Stub; From.FStub := nil; end; procedure TZMDirectory.BeforeDestruction; begin ClearEntries; ClearArgsList; FEntries.Free; FreeAndNil(FStub); inherited; end; procedure TZMDirectory.ClearArgsList; var I: Integer; Tmp: TZMSelectArgs; begin // remove references for I := 0 to Count - 1 do if Entries[I] <> nil then FEntries[I].SelectArgs := nil; // delete list while FArgsList <> nil do begin Tmp := FArgsList; FArgsList := Tmp.Next; Tmp.Free; end; end; procedure TZMDirectory.ClearCachedNames; var I: Integer; begin HashTable.Clear; for I := 0 to Count - 1 do if Entries[I] <> nil then FEntries[I].ClearCachedName; end; procedure TZMDirectory.ClearEntries; begin HashTable.Clear; Entries.Clear; FSelCount := 0; end; procedure TZMDirectory.ClearSelection; var I: Integer; begin for I := 0 to Count - 1 do Items[I].Selected := False; FSelCount := 0; end; function TZMDirectory.FindName(const Name: string; const NotMe: TZMEntryBase = nil): TZMEntryBase; begin Result := TZMEntryBase(Entries.FindName(Name, NotMe)); end; procedure TZMDirectory.FreeSelectArgs(Args: TZMSelectArgs); var Arg: TZMSelectArgs; begin if Args = nil then Exit; Arg := ArgsList; if Arg = Args then begin // first entry FArgsList := Arg.Next; // remove from list Arg.Free; end else begin // find it while (Arg <> nil) and (Arg.Next <> Args) do Arg := Arg.Next; if Arg <> nil then begin // found Arg.Next := Args.Next; // remove from list Arg.Free; end; end; end; function TZMDirectory.GetCount: Integer; begin Result := Entries.Count; end; function TZMDirectory.GetFirstSelected: TZMEntryBase; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if Items[I].StatusBit[ZsbSkipped or ZsbSelected] = ZsbSelected then begin Result := Items[I]; Break; end; end; end; function TZMDirectory.GetHashTable: TZMHashTable; begin Result := FEntries.HashTable; end; function TZMDirectory.GetItems(Index: Integer): TZMEntryBase; begin Result := TZMEntryBase(Entries[Index]); end; // searches for record with same Name function TZMDirectory.HasDupName(const Rec: TZMEntryBase): TZMEntryBase; //move begin Result := TZMEntryBase(Entries.HasDupName(Rec)); end; // Use after EOC found and FileName is last part // if removable has proper numbered volume name we assume it is numbered volume procedure TZMDirectory.InferNumbering; var Fname: string; Num: Integer; NumStr: string; begin if IsExtStream then Numbering := ZnsNone else if (Numbering = ZnsNone) and (TotalDisks > 1) then begin // only if unknown WorkDrive.DriveStr := ArchiveName; if WorkDrive.DriveIsFloppy and SameText(WorkDrive.DiskName, VolName(DiskNr)) then Numbering := ZnsVolume else begin NumStr := ''; Fname := ExtractNameOfFile(ArchiveName); Numbering := ZnsExt; if Length(Fname) > 3 then begin NumStr := Copy(Fname, Length(Fname) - 2, 3); Num := StrToIntDef(NumStr, -1); if Num = (DiskNr + 1) then begin // ambiguous conflict if not HasSpanSig(ExtractFilePath(ArchiveName) + Fname + '.z01') then Numbering := ZnsName; end; end; end; end; end; procedure TZMDirectory.Invalidate; begin Info := Info or Zfi_Invalid; end; procedure TZMDirectory.MarkDirty; begin Info := Info or Zfi_Dirty; end; // return BadIndex when no more function TZMDirectory.NextSelected(CurRec: TZMEntryBase): TZMEntryBase; var I: Integer; begin Result := nil; I := Entries.IndexOf(CurRec); if I >= 0 then begin while I < Count - 1 do begin Inc(I); if Items[I].StatusBit[ZsbSkipped or ZsbSelected] = ZsbSelected then begin Result := Items[I]; break; end; end; end; end; procedure TZMDirectory.RemoveEntry(Entry: TZMEntryBase); begin Entries.RemoveEntry(Entry); end; function TZMDirectory.SearchName(const Pattern: string; IsWild: Boolean; After: Integer): TZMEntryBase; begin Result := TZMEntryBase(Entries.SearchName(Pattern, IsWild, After)); end; function TZMDirectory.SearchNameEx(const Pattern: string; IsWild: Boolean; After: TZMEntryBase): TZMEntryBase; begin Result := TZMEntryBase(Entries.SearchNameEx(Pattern, IsWild, After)); end; // select entries matching external Pattern - return number of selected entries function TZMDirectory.Select(const Pattern: string; How: TZMSelects): Integer; var ARec: TZMEntryBase; I: integer; Srch: Integer; Wild: Boolean; begin Result := 0; // if it wild or multiple we must try to match - else only if same hash Wild := not CanHash(Pattern); if (Pattern = '') or (Wild and ((Pattern = AllSpec) or (Pattern = AnySpec))) then begin for I := 0 to Count - 1 do if SelectEntry(Items[I], How) then Inc(Result); end else begin // select specific Pattern Srch := 1; ARec := nil; // from beginning while Srch <> 0 do begin ARec := SearchNameEx(Pattern, Wild, ARec); if ARec = nil then Break; if SelectEntry(ARec, How) then Inc(Result); if Srch > 0 then begin if Wild then Srch := -1 // search all else Srch := 0; // done end; end; end; end; function TZMDirectory.SelectEntry(Rec: TZMEntryBase; How: TZMSelects): Boolean; begin Result := Rec.Select(How); if Result then Inc(FSelCount) else Dec(FSelCount); end; // SelectFile entries matching external Pattern function TZMDirectory.SelectFile(const Pattern, Reject: string; How: TZMSelects): Integer; var ARec: TZMEntryBase; Exc: string; I: Integer; Ptn: string; Wild: Boolean; begin Result := 0; Exc := Reject; // default excludes Ptn := Pattern; // need to remove switches // split Pattern into Pattern and switches // if it wild or multiple we must try to match - else only if same hash Wild := not CanHash(Ptn); if (Ptn = '') or (Wild and ((Ptn = AllSpec) or (Ptn = AnySpec))) then begin // do all for I := 0 to Count - 1 do begin ARec := Items[I]; if (Exc = '') or not FileNameMatch(Exc, ARec.FileName) then begin SelectEntry(ARec, How); Inc(Result); end; end; end else begin // SelectFile specific Pattern ARec := nil; // from beginning while True do begin ARec := SearchNameEx(Ptn, Wild, ARec); if ARec = nil then Break; // no matches if (Exc = '') or not FileNameMatch(Exc, ARec.FileName) then begin SelectEntry(ARec, How); Inc(Result); end; if not Wild then Break; // old find first end; end; end; function TZMDirectory.SelectFiles(const Want, Reject: TStrings): Integer; var A: Integer; Excludes: string; I: Integer; MissedSpecs: string; NoSelected: Integer; Spec: string; begin Result := 0; ClearSelection; // clear all if (Want.Count < 1) or (Count < 1) then Exit; MissedSpecs := ''; Excludes := ''; // combine rejects into a string if (Reject <> nil) and (Reject.Count > 0) then begin Excludes := Reject[0]; for I := 1 to Reject.Count - 1 do Excludes := Excludes + ZSwitchFollows + Reject[I]; end; // attempt to select each wanted spec for A := 0 to Want.Count - 1 do begin Spec := Want[A]; NoSelected := SelectFile(Spec, Excludes, ZzsSet); if NoSelected < 1 then begin // none found if MissedSpecs <> '' then MissedSpecs := MissedSpecs + '|'; MissedSpecs := MissedSpecs + Spec; if IsTrace then DiagStr(DFQuote + ZI_SkippedFileSpec, Spec, _U_ + 538); if Body.Skipping(Spec, StNotFound, ZE_NoneSelected) then begin Result := -1; Break; // error end; end; if NoSelected > 0 then Result := Result + NoSelected; if NoSelected >= Count then Break; // all have been done end; if Result <= 0 then begin if Excludes <> '' then MissedSpecs := MissedSpecs + ' /E:' + Excludes; Result := Body.PrepareErrMsg(ZE_NoneSelected, [MissedSpecs], _U_ + 554); end; end; // Func returns True to accept file function TZMDirectory.SelectRec(const Pattern, Reject: string; How: TZMSelects; SelArgs: TZMSelectArgs): Integer; var ARec: TZMEntryBase; Exc: string; I: Integer; IsSelected: Boolean; Ptn: string; Wild: Boolean; begin Assert(Assigned(SelArgs), 'SelArgs not set'); Result := 0; Exc := Reject; // default excludes Ptn := Pattern; // need to remove switches // split Pattern into Pattern and switches // if it wild or multiple we must try to match - else only if same hash Wild := not CanHash(Ptn); if (Ptn = '') or (Wild and ((Ptn = AllSpec) or (Ptn = AnySpec))) then begin // do all for I := 0 to Count - 1 do begin ARec := Items[I]; if (Exc = '') or not FileNameMatch(Exc, ARec.FileName) then begin // do extra checking or processing if (How <> ZzsSet) or SelArgs.Accept(ARec) then begin IsSelected := SelectEntry(ARec, How); if IsSelected then ARec.SelectArgs := SelArgs else ARec.SelectArgs := nil; Inc(Result); end; end; end; end else begin // Select specific Pattern ARec := nil; // from beginning while True do begin ARec := SearchNameEx(Ptn, Wild, ARec); if ARec = nil then Break; // no matches if (Exc = '') or not FileNameMatch(Exc, ARec.FileName) then begin // do extra checking or processing if (How <> ZzsSet) or SelArgs.Accept(ARec) then begin IsSelected := SelectEntry(ARec, How); if IsSelected then ARec.SelectArgs := SelArgs else ARec.SelectArgs := nil; Inc(Result); end; end; if not Wild then Break; // old find first end; end; end; procedure TZMDirectory.SetStub(const Value: TMemoryStream); begin if FStub <> Value then begin if Assigned(FStub) then FStub.Free; FStub := Value; end; end; { TZMEntryBase } constructor TZMEntryBase.Create(TheOwner: TZMDirectory); begin inherited Create; FMyFile := TheOwner; FBody := TheOwner.Body; end; procedure TZMEntryBase.AssignFrom(const Zr: TZMCentralItem); begin if (Zr <> Self) and (Zr is TZMEntryBase) then FMyFile := TZMEntryBase(Zr).MyFile; inherited; end; function TZMEntryBase.GetMaster: TCustomZipMaster; begin Result := FBody.Master; end; function TZMEntryBase.GetXName: string; begin Result := FXName; if Result = '' then Result := FileName; end; function TZMEntryBase.IsZip64: Boolean; begin Result := (UncompressedSize >= MAX_UNSIGNED) or (CompressedSize >= MAX_UNSIGNED) or (RelOffLocalHdr >= MAX_UNSIGNED) or (StartOnDisk >= MAX_WORD); end; procedure TZMEntryBase.MarkDirty; begin SetStatusBit(ZsbDirty); end; // returns the new value function TZMEntryBase.SeekLocalData(var LocalHeader: TZipLocalHeader; const HName: TZMRawBytes): Integer; var Did: Int64; begin ASSERT(Assigned(MyFile), 'no MyFile'); if Body.Verbosity >= ZvTrace then Body.DiagFmt(ZT_SeekingLocalHeader, [FileName, StartOnDisk, IntToStr(RelOffLocalHdr)], _U_ + 683); if not MyFile.IsOpen then begin Result := Body.PrepareErrMsg(ZE_FileOpen, [MyFile.ArchiveName], _U_ + 686); Exit; end; Result := ZMError(ZE_LOHBadRead, _U_ + 689); try MyFile.SeekDisk(StartOnDisk, False); MyFile.Position := RelOffLocalHdr; Did := MyFile.Read(LocalHeader, SizeOf(DWORD)); if (Did = SizeOf(DWORD)) and (LocalHeader.HeaderSig = LocalFileHeaderSig) then begin // was local header Did := MyFile.Read(LocalHeader.VersionNeeded, (SizeOf(TZipLocalHeader) - SizeOf(DWORD))); if Did = (SizeOf(TZipLocalHeader) - SizeOf(DWORD)) then Result := VerifyLocalName(LocalHeader, HName); end; if AbsErr(Result) = ZE_LOHBadRead then Body.DiagStr(DFQuote + ZI_CouldNotReadLocalHeader, FileName, _U_ + 703); if AbsErr(Result) = ZE_LOHWrongName then Body.DiagFmt(ZI_LocalHeaderNameDifferent, [FileName, HName], _U_ + 705); except on E: EZipMaster do begin Result := E.ExtErr; Exit; end; on E: EZMAbort do raise; on E: Exception do //TODO: catches too much begin Result := ZMError(ZE_UnknownError, _U_ + 716); Exit; end; end; end; // read and verify local header (including extra data) function TZMEntryBase.VerifyLocalName(const LocalHeader: TZipLocalHeader; const HName: TZMRawBytes): Integer; var Did: Int64; I: Integer; T: Integer; V: TZMRawBytes; begin if LocalHeader.FileNameLen = Length(HName) then begin T := LocalHeader.FileNameLen + LocalHeader.ExtraLen; SetLength(V, T); Did := MyFile.Read(V[1], T); if (Did = T) then begin Result := 0; for I := 1 to LocalHeader.FileNameLen do begin if V[I] <> HName[I] then begin Result := ZE_LOHWrongName; Break; end; end; end else Result := ZE_LOHBadRead; end else Result := ZE_LOHWrongName; if Result <> 0 then Result := ZMError(Result, _U_ + 754); end; end.
unit TokyoScript.Parser; { TokyoScript (c)2018 Execute SARL http://www.execute.Fr } interface uses System.SysUtils, TokyoScript.Chars, TokyoScript.Keywords; type TDefine = class Value: string; Next : TDefine; end; TAppType = ( APPTYPE_GUI, // default APPTYPE_CONSOLE ); ESourceError = class(Exception) Row: Integer; Col: Integer; constructor Create(const Msg: string; ARow, ACol: Integer); end; TParser = record private FDefines: TDefine; FSource : string; FIndex : Integer; FRow : Integer; FLine : Integer; FStart : Integer; FAppType: TAppType; FLiteral: string; function GetCol: Integer; procedure Blanks; function NextChar: Char; function ReadChar: Char; function GetString(var At: Integer): string; procedure Comment1; function Comment2: Boolean; function LineComment: Boolean; procedure Directive(Start: Integer); function IsDirective(Start: Integer; const AName: string): Boolean; function GetAppType(Start: Integer): TAppType; function AddChar(AChar: Char): Boolean; procedure AddChars(CharTypes: TCharTypes); function Match(AChar: Char; AType: TCharType): Boolean; procedure ParseIdent; procedure ParseNumber; function GetChar(Start, Base: Integer): Char; procedure ParseChar; procedure ParseHexa; procedure ParseString; public CharType: TCharType; Keyword: TKeyword; function Token: string; procedure Init(const Str: string); procedure Error(const Msg: string); procedure Next(); procedure Define(const Value: string); procedure Undef(const Value: string); function IsDef(const Value: string): Boolean; function SkipChar(AChar: Char): Boolean; procedure DropChar(AChar: Char); procedure DropCharType(ACharType: TCharType); function SkipKeyword(AKeyword: TKeyword): Boolean; procedure DropKeyword(AKeyword: TKeyword); function SkipKeywords(AKeywords: TKeywords): TKeyword; function GetIdent: string; procedure SemiColon; inline; procedure Clear; property Position: Integer read FStart; property Row: Integer read FRow; property Col: Integer read GetCol; property Literal: string read FLiteral; property AppType: TAppType read FAppType; end; implementation { TParser } procedure TParser.Clear; var Define: TDefine; begin if FSource = '' then begin FDefines := nil; end else begin FSource := ''; while FDefines <> nil do begin Define := FDefines; FDefines := Define.Next; Define.Free; end; end; end; procedure TParser.Comment1; var Start: Integer; begin Inc(FIndex); Start := FIndex; repeat until ReadChar = '}'; if FSource[Start] = '$' then Directive(Start); end; function TParser.Comment2: Boolean; var Start: Integer; begin Result := FSource[FIndex + 1] = '*'; if Result then begin Inc(FIndex, 2); Start := FIndex; repeat until (ReadChar = '*') and (NextChar = ')'); if FSource[Start] = '$' then Directive(Start); Inc(FIndex); end; end; procedure TParser.Define(const Value: string); var Def: TDefine; begin if not IsDef(Value) then begin Def := TDefine.Create; Def.Value := Value; Def.Next := FDefines; FDefines := Def; end; end; procedure TParser.Directive(Start: Integer); begin if IsDirective(Start, 'APPTYPE') then FAppType := GetAppType(Start) else Error('Todo ' + Copy(FSource, Start, FIndex - Start - 1)); end; function TParser.IsDirective(Start: Integer; const AName: string): Boolean; var Index: Integer; begin Result := False; for Index := 1 to Length(AName) do begin Inc(Start); if FSource[Start] <> AName[Index] then Exit; end; Result := FSource[Start + 1] = ' '; end; function TParser.GetAppType(Start: Integer): TAppType; var Str: string; Up : string; begin Inc(Start, 8); // 'APPTYPE ' Str := GetString(Start); Up := UpperCase(Str); if Up = 'GUI' then Exit(APPTYPE_GUI); if Up = 'CONSOLE' then Exit(APPTYPE_CONSOLE); Error('Unknown APPTYPE "' + Str + '"'); end; function TParser.GetChar(Start, Base: Integer): Char; var Digit: Integer; Value: Integer; begin Value := 0; while Start < FIndex do begin Digit := Ord(FSource[Start]); Inc(Start); case Chr(Digit) of '0'..'9': Dec(Digit, Ord('0')); 'a'..'f': Dec(Digit, Ord('a')); 'A'..'F': Dec(Digit, Ord('A')); end; Value := Base * Value + Digit; if Value > $FFFF then Error('Char overflow'); end; Result := Char(Value); end; function TParser.GetCol: Integer; begin Result := FStart - FLine + 1; end; function TParser.SkipChar(AChar: Char): Boolean; begin Result := (FSource[FStart] = AChar) and (FIndex = FStart + 1); if Result then Next(); end; procedure TParser.DropChar(AChar: Char); begin if not SkipChar(AChar) then Error('Expected "' + AChar + '", found, "' + Token +'"'); end; procedure TParser.DropCharType(ACharType: TCharType); begin if CharType <> ACharType then Error('Unexpacted token "' + Token + '"'); Next(); end; function TParser.SkipKeyword(AKeyword: TKeyword): Boolean; begin Result := Keyword = AKeyword; if Result then Next(); end; procedure TParser.DropKeyword(AKeyword: TKeyword); begin if not SkipKeyword(AKeyword) then Error('Keyword expected "' + KEYWORDS[AKeyword] + '", found "' + Token + '"'); end; procedure TParser.Error(const Msg: string); begin raise ESourceError.Create(Msg, FRow, Col); end; function TParser.GetIdent: string; begin Result := Token; if CharType <> ctIdent then Error('Ident expected, found "' + Result + '"'); Next(); end; procedure TParser.Init(const Str: string); begin Clear; FSource := Str; FIndex := 1; FRow := 1; FLine := 0; Next(); end; function TParser.IsDef(const Value: string): Boolean; var Def: TDefine; begin Def := FDefines; while Def <> nil do begin if Def.Value = Value then Exit(True); Def := Def.Next; end; Result := False; end; function TParser.LineComment: Boolean; begin Result := FSource[FIndex + 1] = '/'; if Result then begin Inc(FIndex, 2); repeat until GetCharType(ReadChar) in [ctLineFeed, ctReturn]; end; end; function TParser.Match(AChar: Char; AType: TCharType): Boolean; begin Result := AddChar(AChar); if Result then CharType := AType; end; function TParser.AddChar(AChar: Char): Boolean; begin Result := NextChar = AChar; if Result then Inc(FIndex); end; procedure TParser.AddChars(CharTypes: TCharTypes); var C: Char; begin C := NextChar; while GetCharType(C) in CharTypes do begin Inc(FIndex); C := NextChar; end; end; procedure TParser.Blanks; begin repeat case GetCharType(NextChar) of ctPadding : Inc(FIndex); ctLineFeed : // LF begin Inc(FRow); Inc(FIndex); FLine := FIndex; end; ctReturn: // CR/LF begin Inc(FRow); Inc(FIndex); if NextChar = #10 then Inc(FIndex); FLine := FIndex; end; ctLBrace : Comment1; // { ctLParent: if not Comment2 then Exit; // (* ctSlash : if not LineComment then Exit; // // else Exit; end; until False; end; procedure TParser.Next; begin FLiteral := ''; Blanks; // <SPACE> <TAB> <CR> <LF> { comment1 } (* comment 2 *) // line comment FStart := FIndex; CharType := GetCharType(ReadChar); Keyword := kw_None; case CharType of ctAlpha : ParseIdent; ctDigit : ParseNumber; ctColon : Match('=', ctAssign); ctGT : Match('=', ctGE); ctLT : if not Match('=', ctLE) then Match('>', ctNE); ctDot : Match('.', ctRange); ctSharp : ParseChar; ctDollar : ParseHexa; ctSimpleQuote: ParseString; end; end; function TParser.NextChar: Char; begin if FIndex <= Length(FSource) then Result := FSource[FIndex] else Result := #0; end; procedure TParser.ParseChar; var Start: Integer; begin if NextChar = '$' then begin Inc(FIndex); Start := FIndex; ParseHexa; if FIndex = Start then Error('Expected hexadecimal value'); FLiteral := FLiteral + GetChar(Start, 16); end else begin Start := FIndex; AddChars([ctDigit]); if FIndex = Start then Error('Expected number'); FLiteral := FLiteral + GetChar(Start, 10); end; if NextChar = '''' then begin Inc(FIndex); ParseString; end else begin CharType := ctChar; end; end; procedure TParser.ParseHexa; begin while NextChar in ['0'..'9', 'a'..'f', 'A'..'F'] do Inc(FIndex); CharType := ctHexa; end; procedure TParser.ParseIdent; begin AddChars([ctAlpha, ctDigit]); CharType := ctIdent; Keyword := GetKeyword(Token); if Keyword <> kw_None then CharType := ctKeyword; end; procedure TParser.ParseNumber; begin AddChars([ctDigit]); // 123 CharType := ctNumber; if NextChar = '.' then // 123.4 begin CharType := ctReal; Inc(FIndex); AddChars([ctDigit]); end; if NextChar in ['e', 'E'] then // 123e10, 123.4e10 begin CharType := ctReal; Inc(FIndex); if NextChar in ['+', '-'] then // 123e+10 Inc(FIndex); AddChars([ctDigit]); end; end; procedure TParser.ParseString; var Start: Integer; begin Start := FIndex; while True do begin while NextChar <> '''' do begin Inc(FIndex); end; Inc(FIndex); if NextChar = '''' then begin FLiteral := FLiteral + Copy(FSource, Start, FIndex - Start); Inc(FIndex); Start := FIndex; end else begin Break; end; end; FLiteral := FLiteral + Copy(FSource, Start, FIndex - Start - 1); if NextChar = '#' then begin Inc(FIndex); ParseChar; end; CharType := ctString; end; function TParser.ReadChar: Char; begin Result := NextChar; if Result = #0 then raise Exception.Create('End of File'); Inc(FIndex); end; function TParser.GetString(var At: Integer): string; var Start: Integer; begin while (At < FIndex) and (GetCharType(FSource[At]) = ctPadding) do Inc(At); Start := At; while (At < FIndex) and (GetCharType(FSource[At]) in [ctAlpha, ctDigit]) do Inc(At); Result := Copy(FSource, Start, At - Start); end; procedure TParser.SemiColon; begin DropChar(';'); end; function TParser.SkipKeywords(AKeywords: TKeywords): TKeyword; begin if Keyword in AKeywords then begin Result := Keyword; Next(); end else begin Result := kw_None; end; end; function TParser.Token: string; begin SetString(Result, PChar(@FSource[FStart]), FIndex - FStart); end; procedure TParser.Undef(const Value: string); var Def: TDefine; Tmp: TDefine; begin if FDefines = nil then Exit; Def := FDefines; if Def.Value = Value then begin FDefines := Def.Next; Def.Free; end else begin Tmp := Def.Next; while Tmp <> nil do begin if Tmp.Value = Value then begin Def.Next := Tmp.Next; Tmp.Free; Exit; end; Def := Tmp; Tmp := Def.Next; end; end; end; { ESourceError } constructor ESourceError.Create(const Msg: string; ARow, ACol: Integer); begin inherited Create(Msg + ' at [' + IntToStr(ACol) + ',' + IntToStr(ARow) + ']'); Row := ARow; Col := ACol; end; end.
{ Invokable interface ITest } unit SoapIntf; interface uses InvokeRegistry, Types, XSBuiltIns; type { Invokable interfaces must derive from IInvokable } IWSYXDSVR = interface(IInvokable) ['{2FEFD041-C424-4673-8B86-42106004CCE4}'] function HelloWorld:String; { Methods of Invokable interface must not use the default } { calling convention; stdcall is recommended } end; implementation initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(IWSYXDSVR)); end.
unit ssVCLUtil; interface uses Controls, Graphics, Windows, Types; const PaletteMask = $02000000; type TFillDirection = (fdTopToBottom, fdBottomToTop, fdLeftToRight, fdRightToLeft); procedure GradientFillRect(Canvas: TCanvas; ARect: TRect; StartColor, EndColor: TColor; Direction: TFillDirection; Colors: Byte); function Max(A, B: Longint): Longint; function Min(A, B: Longint): Longint; function CreateDisabledBitmapEx(FOriginal: Graphics.TBitmap; OutlineColor, BackColor, HighlightColor, ShadowColor: TColor; DrawHighlight: Boolean): Graphics.TBitmap; procedure DrawBitmapTransparent(Dest: TCanvas; DstX, DstY: Integer; Bitmap: Graphics.TBitmap; TransparentColor: TColor); procedure StretchBltTransparent(DstDC: HDC; DstX, DstY, DstW, DstH: Integer; SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; Palette: HPalette; TransparentColor: TColorRef); function PaletteColor(Color: TColor): Longint; procedure ImageListDrawDisabled(Images: TImageList; Canvas: TCanvas; X, Y, Index: Integer; HighlightColor, GrayColor: TColor; DrawHighlight: Boolean); procedure AssignBitmapCell(Source: TGraphic; Dest: Graphics.TBitmap; Cols, Rows, Index: Integer); function CreateRealSizeIcon(Icon: TIcon): HIcon; procedure GetIconSize(Icon: HIcon; var W, H: Integer); implementation uses Classes, CommCtrl, SysUtils; const ROP_DSPDxax = $00E20746; procedure GetIconSize(Icon: HICON; var W, H: Integer); begin W := GetSystemMetrics(SM_CXICON); H := GetSystemMetrics(SM_CYICON); end; procedure OutOfResources; near; begin raise EOutOfResources.Create('out of resources'); end; function PaletteColor(Color: TColor): Longint; begin Result := ColorToRGB(Color) or PaletteMask; end; function HeightOf(R: TRect): Integer; begin Result := R.Bottom - R.Top; end; function WidthOf(R: TRect): Integer; begin Result := R.Right - R.Left; end; function WidthBytes(I: Longint): Longint; begin Result := ((I + 31) div 32) * 4; end; function GetDInColors(BitCount: Word): Integer; begin case BitCount of 1, 4, 8: Result := 1 shl BitCount; else Result := 0; end; end; function DupBits(Src: HBITMAP; Size: TPoint; Mono: Boolean): HBITMAP; var DC, Mem1, Mem2: HDC; Old1, Old2: HBITMAP; Bitmap: Windows.TBitmap; begin Mem1 := CreateCompatibleDC(0); Mem2 := CreateCompatibleDC(0); GetObject(Src, SizeOf(Bitmap), @Bitmap); if Mono then Result := CreateBitmap(Size.X, Size.Y, 1, 1, nil) else begin DC := GetDC(0); if DC = 0 then OutOfResources; try Result := CreateCompatibleBitmap(DC, Size.X, Size.Y); if Result = 0 then OutOfResources; finally ReleaseDC(0, DC); end; end; if Result <> 0 then begin Old1 := SelectObject(Mem1, Src); Old2 := SelectObject(Mem2, Result); StretchBlt(Mem2, 0, 0, Size.X, Size.Y, Mem1, 0, 0, Bitmap.bmWidth, Bitmap.bmHeight, SrcCopy); if Old1 <> 0 then SelectObject(Mem1, Old1); if Old2 <> 0 then SelectObject(Mem2, Old2); end; DeleteDC(Mem1); DeleteDC(Mem2); end; procedure TwoBitsFromDIB(var BI: TBitmapInfoHeader; var XorBits, AndBits: HBITMAP); type PLongArray = ^TLongArray; TLongArray = array[0..1] of Longint; var Temp: HBITMAP; NumColors: Integer; DC: HDC; Bits: Pointer; Colors: PLongArray; IconSize: TPoint; BM: Windows.TBitmap; begin IconSize.X := GetSystemMetrics(SM_CXICON); IconSize.Y := GetSystemMetrics(SM_CYICON); with BI do begin biHeight := biHeight shr 1; { Size in record is doubled } biSizeImage := WidthBytes(Longint(biWidth) * biBitCount) * biHeight; NumColors := GetDInColors(biBitCount); end; DC := GetDC(0); if DC = 0 then OutOfResources; try Bits := Pointer(Longint(@BI) + SizeOf(BI) + NumColors * SizeOf(TRGBQuad)); Temp := CreateDIBitmap(DC, BI, CBM_INIT, Bits, PBitmapInfo(@BI)^, DIB_RGB_COLORS); if Temp = 0 then OutOfResources; try GetObject(Temp, SizeOf(BM), @BM); IconSize.X := BM.bmWidth; IconSize.Y := BM.bmHeight; XorBits := DupBits(Temp, IconSize, False); finally DeleteObject(Temp); end; with BI do begin Inc(Longint(Bits), biSizeImage); biBitCount := 1; biSizeImage := WidthBytes(Longint(biWidth) * biBitCount) * biHeight; biClrUsed := 2; biClrImportant := 2; end; Colors := Pointer(Longint(@BI) + SizeOf(BI)); Colors^[0] := 0; Colors^[1] := $FFFFFF; Temp := CreateDIBitmap(DC, BI, CBM_INIT, Bits, PBitmapInfo(@BI)^, DIB_RGB_COLORS); if Temp = 0 then OutOfResources; try AndBits := DupBits(Temp, IconSize, True); finally DeleteObject(Temp); end; finally ReleaseDC(0, DC); end; end; procedure ReadIcon(Stream: TStream; var Icon: HICON; ImageCount: Integer; StartOffset: Integer); type PIconRecArray = ^TIconRecArray; TIconRecArray = array[0..300] of TIconRec; var List: PIconRecArray; HeaderLen, Length: Integer; Colors, BitsPerPixel: Word; C1, C2, N, Index: Integer; IconSize: TPoint; DC: HDC; BI: PBitmapInfoHeader; ResData: Pointer; XorBits, AndBits: HBITMAP; XorInfo, AndInfo: Windows.TBitmap; XorMem, AndMem: Pointer; XorLen, AndLen: Integer; begin HeaderLen := SizeOf(TIconRec) * ImageCount; List := AllocMem(HeaderLen); try Stream.Read(List^, HeaderLen); IconSize.X := GetSystemMetrics(SM_CXICON); IconSize.Y := GetSystemMetrics(SM_CYICON); DC := GetDC(0); if DC = 0 then OutOfResources; try BitsPerPixel := GetDeviceCaps(DC, PLANES) * GetDeviceCaps(DC, BITSPIXEL); if BitsPerPixel = 24 then Colors := 0 else Colors := 1 shl BitsPerPixel; finally ReleaseDC(0, DC); end; Index := -1; { the following code determines which image most closely matches the current device. It is not meant to absolutely match Windows (known broken) algorithm } C2 := 0; for N := 0 to ImageCount - 1 do begin C1 := List^[N].Colors; if C1 = Colors then begin Index := N; Break; end else if Index = -1 then begin if C1 <= Colors then begin Index := N; C2 := List^[N].Colors; end; end else if C1 > C2 then Index := N; end; if Index = -1 then Index := 0; with List^[Index] do begin BI := AllocMem(DIBSize); try Stream.Seek(DIBOffset - (HeaderLen + StartOffset), 1); Stream.Read(BI^, DIBSize); TwoBitsFromDIB(BI^, XorBits, AndBits); GetObject(AndBits, SizeOf(Windows.TBitmap), @AndInfo); GetObject(XorBits, SizeOf(Windows.TBitmap), @XorInfo); IconSize.X := AndInfo.bmWidth; IconSize.Y := AndInfo.bmHeight; with AndInfo do AndLen := bmWidthBytes * bmHeight * bmPlanes; with XorInfo do XorLen := bmWidthBytes * bmHeight * bmPlanes; Length := AndLen + XorLen; ResData := AllocMem(Length); try AndMem := ResData; with AndInfo do XorMem := Pointer(Longint(ResData) + AndLen); GetBitmapBits(AndBits, AndLen, AndMem); GetBitmapBits(XorBits, XorLen, XorMem); DeleteObject(XorBits); DeleteObject(AndBits); Icon := CreateIcon(HInstance, IconSize.X, IconSize.Y, XorInfo.bmPlanes, XorInfo.bmBitsPixel, AndMem, XorMem); if Icon = 0 then OutOfResources; finally FreeMem(ResData, Length); end; finally FreeMem(BI, DIBSize); end; end; finally FreeMem(List, HeaderLen); end; end; function CreateRealSizeIcon(Icon: TIcon): HIcon; var Mem: TMemoryStream; CI: TCursorOrIcon; begin Result := 0; Mem := TMemoryStream.Create; try Icon.SaveToStream(Mem); Mem.Position := 0; Mem.ReadBuffer(CI, SizeOf(CI)); case CI.wType of RC3_STOCKICON: Result := LoadIcon(0, IDI_APPLICATION); RC3_ICON: ReadIcon(Mem, Result, CI.Count, SizeOf(CI)); else Result := CopyIcon(Icon.Handle); end; finally Mem.Free; end; end; procedure AssignBitmapCell(Source: TGraphic; Dest: Graphics.TBitmap; Cols, Rows, Index: Integer); var CellWidth, CellHeight: Integer; begin if (Source <> nil) and (Dest <> nil) then begin if Cols <= 0 then Cols := 1; if Rows <= 0 then Rows := 1; if Index < 0 then Index := 0; CellWidth := Source.Width div Cols; CellHeight := Source.Height div Rows; with Dest do begin Width := CellWidth; Height := CellHeight; end; if Source is Graphics.TBitmap then begin Dest.Canvas.CopyRect(Bounds(0, 0, CellWidth, CellHeight), Graphics.TBitmap(Source).Canvas, Bounds((Index mod Cols) * CellWidth, (Index div Cols) * CellHeight, CellWidth, CellHeight)); Dest.TransparentColor := Graphics.TBitmap(Source).TransparentColor; end else begin Dest.Canvas.Brush.Color := clSilver; Dest.Canvas.FillRect(Bounds(0, 0, CellWidth, CellHeight)); Dest.Canvas.Draw(-(Index mod Cols) * CellWidth, -(Index div Cols) * CellHeight, Source); end; Dest.Transparent := Source.Transparent; end; end; procedure ImageListDrawDisabled(Images: TImageList; Canvas: TCanvas; X, Y, Index: Integer; HighlightColor, GrayColor: TColor; DrawHighlight: Boolean); var Bmp: Graphics.TBitmap; SaveColor: TColor; begin SaveColor := Canvas.Brush.Color; Bmp := Graphics.TBitmap.Create; try Bmp.Width := Images.Width; Bmp.Height := Images.Height; with Bmp.Canvas do begin Brush.Color := clWhite; FillRect(Rect(0, 0, Images.Width, Images.Height)); ImageList_Draw(Images.Handle, Index, Handle, 0, 0, ILD_MASK); end; Bmp.Monochrome := True; if DrawHighlight then begin Canvas.Brush.Color := HighlightColor; SetTextColor(Canvas.Handle, clWhite); SetBkColor(Canvas.Handle, clBlack); BitBlt(Canvas.Handle, X + 1, Y + 1, Images.Width, Images.Height, Bmp.Canvas.Handle, 0, 0, ROP_DSPDxax); end; Canvas.Brush.Color := GrayColor; SetTextColor(Canvas.Handle, clWhite); SetBkColor(Canvas.Handle, clBlack); BitBlt(Canvas.Handle, X, Y, Images.Width, Images.Height, Bmp.Canvas.Handle, 0, 0, ROP_DSPDxax); finally Bmp.Free; Canvas.Brush.Color := SaveColor; end; end; procedure StretchBltTransparent(DstDC: HDC; DstX, DstY, DstW, DstH: Integer; SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; Palette: HPalette; TransparentColor: TColorRef); var Color: TColorRef; bmAndBack, bmAndObject, bmAndMem, bmSave: HBitmap; bmBackOld, bmObjectOld, bmMemOld, bmSaveOld: HBitmap; MemDC, BackDC, ObjectDC, SaveDC: HDC; palDst, palMem, palSave, palObj: HPalette; begin { Create some DCs to hold temporary data } BackDC := CreateCompatibleDC(DstDC); ObjectDC := CreateCompatibleDC(DstDC); MemDC := CreateCompatibleDC(DstDC); SaveDC := CreateCompatibleDC(DstDC); { Create a bitmap for each DC } bmAndObject := CreateBitmap(SrcW, SrcH, 1, 1, nil); bmAndBack := CreateBitmap(SrcW, SrcH, 1, 1, nil); bmAndMem := CreateCompatibleBitmap(DstDC, DstW, DstH); bmSave := CreateCompatibleBitmap(DstDC, SrcW, SrcH); { Each DC must select a bitmap object to store pixel data } bmBackOld := SelectObject(BackDC, bmAndBack); bmObjectOld := SelectObject(ObjectDC, bmAndObject); bmMemOld := SelectObject(MemDC, bmAndMem); bmSaveOld := SelectObject(SaveDC, bmSave); { Select palette } palDst := 0; palMem := 0; palSave := 0; palObj := 0; if Palette <> 0 then begin palDst := SelectPalette(DstDC, Palette, True); RealizePalette(DstDC); palSave := SelectPalette(SaveDC, Palette, False); RealizePalette(SaveDC); palObj := SelectPalette(ObjectDC, Palette, False); RealizePalette(ObjectDC); palMem := SelectPalette(MemDC, Palette, True); RealizePalette(MemDC); end; { Set proper mapping mode } SetMapMode(SrcDC, GetMapMode(DstDC)); SetMapMode(SaveDC, GetMapMode(DstDC)); { Save the bitmap sent here } BitBlt(SaveDC, 0, 0, SrcW, SrcH, SrcDC, SrcX, SrcY, SRCCOPY); { Set the background color of the source DC to the color, } { contained in the parts of the bitmap that should be transparent } Color := SetBkColor(SaveDC, PaletteColor(TransparentColor)); { Create the object mask for the bitmap by performing a BitBlt() } { from the source bitmap to a monochrome bitmap } BitBlt(ObjectDC, 0, 0, SrcW, SrcH, SaveDC, 0, 0, SRCCOPY); { Set the background color of the source DC back to the original } SetBkColor(SaveDC, Color); { Create the inverse of the object mask } BitBlt(BackDC, 0, 0, SrcW, SrcH, ObjectDC, 0, 0, NOTSRCCOPY); { Copy the background of the main DC to the destination } BitBlt(MemDC, 0, 0, DstW, DstH, DstDC, DstX, DstY, SRCCOPY); { Mask out the places where the bitmap will be placed } StretchBlt(MemDC, 0, 0, DstW, DstH, ObjectDC, 0, 0, SrcW, SrcH, SRCAND); { Mask out the transparent colored pixels on the bitmap } BitBlt(SaveDC, 0, 0, SrcW, SrcH, BackDC, 0, 0, SRCAND); { XOR the bitmap with the background on the destination DC } StretchBlt(MemDC, 0, 0, DstW, DstH, SaveDC, 0, 0, SrcW, SrcH, SRCPAINT); { Copy the destination to the screen } BitBlt(DstDC, DstX, DstY, DstW, DstH, MemDC, 0, 0, SRCCOPY); { Restore palette } if Palette <> 0 then begin SelectPalette(MemDC, palMem, False); SelectPalette(ObjectDC, palObj, False); SelectPalette(SaveDC, palSave, False); SelectPalette(DstDC, palDst, True); end; { Delete the memory bitmaps } DeleteObject(SelectObject(BackDC, bmBackOld)); DeleteObject(SelectObject(ObjectDC, bmObjectOld)); DeleteObject(SelectObject(MemDC, bmMemOld)); DeleteObject(SelectObject(SaveDC, bmSaveOld)); { Delete the memory DCs } DeleteDC(MemDC); DeleteDC(BackDC); DeleteDC(ObjectDC); DeleteDC(SaveDC); end; procedure StretchBitmapTransparent(Dest: TCanvas; Bitmap: Graphics.TBitmap; TransparentColor: TColor; DstX, DstY, DstW, DstH, SrcX, SrcY, SrcW, SrcH: Integer); var CanvasChanging: TNotifyEvent; begin if DstW <= 0 then DstW := Bitmap.Width; if DstH <= 0 then DstH := Bitmap.Height; if (SrcW <= 0) or (SrcH <= 0) then begin SrcX := 0; SrcY := 0; SrcW := Bitmap.Width; SrcH := Bitmap.Height; end; if not Bitmap.Monochrome then SetStretchBltMode(Dest.Handle, STRETCH_DELETESCANS); CanvasChanging := Bitmap.Canvas.OnChanging; Bitmap.Canvas.Lock; try Bitmap.Canvas.OnChanging := nil; if TransparentColor = clNone then begin StretchBlt(Dest.Handle, DstX, DstY, DstW, DstH, Bitmap.Canvas.Handle, SrcX, SrcY, SrcW, SrcH, Dest.CopyMode); end else begin if TransparentColor = clDefault then TransparentColor := Bitmap.Canvas.Pixels[0, Bitmap.Height - 1]; if Bitmap.Monochrome then TransparentColor := clWhite else TransparentColor := ColorToRGB(TransparentColor); StretchBltTransparent(Dest.Handle, DstX, DstY, DstW, DstH, Bitmap.Canvas.Handle, SrcX, SrcY, SrcW, SrcH, Bitmap.Palette, TransparentColor); end; finally Bitmap.Canvas.OnChanging := CanvasChanging; Bitmap.Canvas.Unlock; end; end; procedure DrawBitmapTransparent(Dest: TCanvas; DstX, DstY: Integer; Bitmap: Graphics.TBitmap; TransparentColor: TColor); begin StretchBitmapTransparent(Dest, Bitmap, TransparentColor, DstX, DstY, Bitmap.Width, Bitmap.Height, 0, 0, Bitmap.Width, Bitmap.Height); end; function CreateDisabledBitmapEx(FOriginal: Graphics.TBitmap; OutlineColor, BackColor, HighlightColor, ShadowColor: TColor; DrawHighlight: Boolean): Graphics.TBitmap; var MonoBmp: Graphics.TBitmap; IRect: TRect; begin IRect := Rect(0, 0, FOriginal.Width, FOriginal.Height); Result := Graphics.TBitmap.Create; try Result.Width := FOriginal.Width; Result.Height := FOriginal.Height; MonoBmp := Graphics.TBitmap.Create; try with MonoBmp do begin Width := FOriginal.Width; Height := FOriginal.Height; Canvas.CopyRect(IRect, FOriginal.Canvas, IRect); HandleType := bmDDB; Canvas.Brush.Color := OutlineColor; if Monochrome then begin Canvas.Font.Color := clWhite; Monochrome := False; Canvas.Brush.Color := clWhite; end; Monochrome := True; end; with Result.Canvas do begin Brush.Color := BackColor; FillRect(IRect); if DrawHighlight then begin Brush.Color := HighlightColor; SetTextColor(Handle, clBlack); SetBkColor(Handle, clWhite); BitBlt(Handle, 1, 1, IRect.Right-IRect.Left, IRect.Bottom-IRect.Top, MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); end; Brush.Color := ShadowColor; SetTextColor(Handle, clBlack); SetBkColor(Handle, clWhite); BitBlt(Handle, 0, 0, WidthOf(IRect), HeightOf(IRect), MonoBmp.Canvas.Handle, 0, 0, ROP_DSPDxax); end; finally MonoBmp.Free; end; except Result.Free; raise; end; end; function Max(A, B: Longint): Longint; begin if A > B then Result := A else Result := B; end; function Min(A, B: Longint): Longint; begin if A < B then Result := A else Result := B; end; procedure GradientFillRect(Canvas: TCanvas; ARect: TRect; StartColor, EndColor: TColor; Direction: TFillDirection; Colors: Byte); var StartRGB: array[0..2] of Byte; { Start RGB values } RGBDelta: array[0..2] of Integer; { Difference between start and end RGB values } ColorBand: TRect; { Color band rectangular coordinates } I, Delta: Integer; Brush: HBrush; begin if IsRectEmpty(ARect) then Exit; if Colors < 2 then begin Brush := CreateSolidBrush(ColorToRGB(StartColor)); FillRect(Canvas.Handle, ARect, Brush); DeleteObject(Brush); Exit; end; StartColor := ColorToRGB(StartColor); EndColor := ColorToRGB(EndColor); case Direction of fdTopToBottom, fdLeftToRight: begin { Set the Red, Green and Blue colors } StartRGB[0] := GetRValue(StartColor); StartRGB[1] := GetGValue(StartColor); StartRGB[2] := GetBValue(StartColor); { Calculate the difference between begin and end RGB values } RGBDelta[0] := GetRValue(EndColor) - StartRGB[0]; RGBDelta[1] := GetGValue(EndColor) - StartRGB[1]; RGBDelta[2] := GetBValue(EndColor) - StartRGB[2]; end; fdBottomToTop, fdRightToLeft: begin { Set the Red, Green and Blue colors } { Reverse of TopToBottom and LeftToRight directions } StartRGB[0] := GetRValue(EndColor); StartRGB[1] := GetGValue(EndColor); StartRGB[2] := GetBValue(EndColor); { Calculate the difference between begin and end RGB values } { Reverse of TopToBottom and LeftToRight directions } RGBDelta[0] := GetRValue(StartColor) - StartRGB[0]; RGBDelta[1] := GetGValue(StartColor) - StartRGB[1]; RGBDelta[2] := GetBValue(StartColor) - StartRGB[2]; end; end; {case} { Calculate the color band's coordinates } ColorBand := ARect; if Direction in [fdTopToBottom, fdBottomToTop] then begin Colors := Max(2, Min(Colors, HeightOf(ARect))); Delta := HeightOf(ARect) div Colors; end else begin Colors := Max(2, Min(Colors, WidthOf(ARect))); Delta := WidthOf(ARect) div Colors; end; with Canvas.Pen do begin { Set the pen style and mode } Style := psSolid; Mode := pmCopy; end; { Perform the fill } if Delta > 0 then begin for I := 0 to Colors do begin case Direction of { Calculate the color band's top and bottom coordinates } fdTopToBottom, fdBottomToTop: begin ColorBand.Top := ARect.Top + I * Delta; ColorBand.Bottom := ColorBand.Top + Delta; end; { Calculate the color band's left and right coordinates } fdLeftToRight, fdRightToLeft: begin ColorBand.Left := ARect.Left + I * Delta; ColorBand.Right := ColorBand.Left + Delta; end; end; {case} { Calculate the color band's color } Brush := CreateSolidBrush(RGB( StartRGB[0] + MulDiv(I, RGBDelta[0], Colors - 1), StartRGB[1] + MulDiv(I, RGBDelta[1], Colors - 1), StartRGB[2] + MulDiv(I, RGBDelta[2], Colors - 1))); FillRect(Canvas.Handle, ColorBand, Brush); DeleteObject(Brush); end; end; if Direction in [fdTopToBottom, fdBottomToTop] then Delta := HeightOf(ARect) mod Colors else Delta := WidthOf(ARect) mod Colors; if Delta > 0 then begin case Direction of { Calculate the color band's top and bottom coordinates } fdTopToBottom, fdBottomToTop: begin ColorBand.Top := ARect.Bottom - Delta; ColorBand.Bottom := ColorBand.Top + Delta; end; { Calculate the color band's left and right coordinates } fdLeftToRight, fdRightToLeft: begin ColorBand.Left := ARect.Right - Delta; ColorBand.Right := ColorBand.Left + Delta; end; end; {case} case Direction of fdTopToBottom, fdLeftToRight: Brush := CreateSolidBrush(EndColor); else {fdBottomToTop, fdRightToLeft } Brush := CreateSolidBrush(StartColor); end; FillRect(Canvas.Handle, ColorBand, Brush); DeleteObject(Brush); end; end; end.
unit UpdateUserUnit; interface uses SysUtils, BaseExampleUnit, UserParametersUnit; type TUpdateUser = class(TBaseExample) public procedure Execute(Parameters: TUserParameters); end; implementation procedure TUpdateUser.Execute(Parameters: TUserParameters); var ErrorString: String; begin Route4MeManager.User.Update(Parameters, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('User updated successfully'); WriteLn(''); end else WriteLn(Format('UpdateUser error: "%s"', [ErrorString])); end; end.
// ------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. // ------------------------------------------------------------------------------------------------------- {$IFNDEF CHAKRA_CORE_VERSION_H} {$DEFINE CHAKRA_CORE_VERSION_H} // NOTE: When changing this file, you may need to update the GUID in ByteCodeCacheReleaseFileVersion.h // Please update the GUID when: // * CHAKRA_CORE_VERSION_RELEASE is changed to 1 // * CHAKRA_CORE_VERSION_RELEASE is currently set to 1 and the bytecode changes // See notes below about ReleaseVersioningScheme. // -------------- // VERSION NUMBER // -------------- // ChakraCore version number definitions (used in ChakraCore binary metadata) const CHAKRA_CORE_MAJOR_VERSION = 1; CHAKRA_CORE_MINOR_VERSION = 8; CHAKRA_CORE_PATCH_VERSION = 2; CHAKRA_CORE_VERSION_RELEASE_QFE = 0; // Redundant with PATCH_VERSION. Keep this value set to 0. // ------------- // RELEASE FLAGS // ------------- // NOTE: CHAKRA_CORE_VERSION_PRERELEASE can only be set to 1 when // CHAKRA_CORE_VERSION_RELEASE is set to 1, or there is no effect. // Here are the meanings of the various combinations: // // RELEASE** PRERELEASE // DEVELOPMENT 0 0 // <INVALID> 0 1 # INVALID but identical to DEVELOPMENT // RELEASE** 1 0 # // PRERELEASE 1 1 // ** Release flags are not related to build type (e.g. x64_release) // // Unless otherwise noted, the code affected by these flags lies mostly in bin/CoreCommon.ver // // DEVELOPMENT: // * Uses EngineeringVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp) // * Sets file flag VS_FF_PRIVATEBUILD // * Adds "Private" to the file description // // RELEASE** and PRERELEASE (i.e. controlled by CHAKRA_CORE_VERSION_RELEASE flag): // * Uses ReleaseVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp) // // PRERELEASE (preparing for release but not yet ready to release): // * Sets file flag VS_FF_PRERELEASE // * Adds "Pre-release" to the file description // // RELEASE** (code is ready to release) // * Sets neither of the file flags noted above // * Does not add anything to the file description // ChakraCore RELEASE and PRERELEASE flags CHAKRA_CORE_VERSION_RELEASE = 1; CHAKRA_CORE_VERSION_PRERELEASE = 0; // Chakra RELEASE flag // Mostly redundant with CHAKRA_CORE_VERSION_RELEASE, // but semantically refers to Chakra rather than ChakraCore. CHAKRA_VERSION_RELEASE = 1; {$ENDIF} (* CHAKRA_CORE_VERSION_H *)
unit ZMOprMerge; // ZMMergeOpr.pas - MergeZipped operation (* *************************************************************************** TZipMaster VCL originally by Chris Vleghert, Eric W. Engler. Present Maintainers and Authors Roger Aelbrecht and Russell Peters. Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler Copyright (C) 1992-2008 Eric W. Engler Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht The MIT License (MIT) Copyright (c) 2014, 2015 delphizip 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. contact: problems AT delphizip DOT org updates: http://www.delphizip.org *************************************************************************** *) // modified 2015-05-07 {$I '.\ZipVers.inc'} interface uses {$IFDEF VERDXE2up} System.Classes, {$ELSE} Classes, {$ENDIF} ZMHandler, ZipMstr; type TZMOpMerge = class(TZMOperationRoot) private FOpts: TZMMergeOpts; public constructor Create(Opts: TZMMergeOpts); function Changes: TZMOperRes; override; function Execute(TheBody: TZMHandler): Integer; override; function Name: string; override; function Needs: TZMOperRes; override; end; implementation uses {$IFDEF VERDXE2up} WinApi.Windows, System.SysUtils, VCL.Graphics, VCL.Dialogs, VCL.Controls, {$ELSE} Windows, SysUtils, Graphics, Dialogs, Controls, {$IFNDEF VERD7up}ZMCompat, {$ENDIF} {$ENDIF} ZMLister, ZMBody, ZMMisc, ZMArgSplit, ZMFileIO, ZMReader, ZMWriter, ZMDirectory, ZMUnzipOpr, ZMXcpt, ZMStructs, ZMUtils, ZMDlg, ZMCtx, ZMMsg, ZMDrv, ZMMultiIO, ZMCore, ZMCentral, ZMDiags, ZMEntryWriter; const __UNIT__ = 45; const _U_ = (__UNIT__ shl ZERR_LINE_SHIFTS); type TSFXOps = (SfoNew, SfoZip, SfoExe); type TMOArgOptions = record Arg: string; Excludes: string; NFlag: Boolean; XArg: string; end; type // provides support for auto-open of source zips TZMMerger = class(TZMCopier) private FLastOpened: TZMFileIO; procedure SetLastOpened(const Value: TZMFileIO); protected function CommitRec(Rec: TZMEntryWriter): Int64; override; property LastOpened: TZMFileIO read FLastOpened write SetLastOpened; public procedure AfterConstruction; override; end; TZMEntryMerger = class(TZMEntryCopier) private FKeep: Boolean; protected function GetTitle: string; override; public procedure AfterConstruction; override; function Process: Int64; override; property Keep: Boolean read FKeep write FKeep; end; type TZMMergeOpr = class(TZMUnzipOpr) private procedure AssignArgOptions(var Locals: TMOArgOptions; const Args: TMOArgOptions); procedure ClearAppend; function CommitAppend: Integer; function ExtractChildZip(ParentIndex: Integer; const MyName: string): Integer; function FlattenExcludes(Excludes: TStrings): string; function IncludeAZip(const SourceName: string): Integer; function MergeAnotherZip(const SourceName: string): Integer; function MergeAnotherZip1(const SourceName: string): Integer; function MergeAnotherZipInZip(const SourceName: string): Integer; function MergeIntermediate(SelectedCount: Integer; const Opts: TZMMergeOpts): Integer; function MergeIntermedZip(RefZip: TZMReader; ZipIndex: Integer; Opts: TZMMergeOpts): Integer; function MergePrepareName(var ZName: string; ZRec: TZMEntryBase): Integer; function MergeResolveConflict(RefRec, NRec: TZMEntryCopier; const Opts: TZMMergeOpts): Integer; function MergeSafeName(ZipIndex: Integer; const Name: string): string; function Prepare(MustExist: Boolean; SafePart: Boolean = False) : TZMReader; function PrepareAppend: Boolean; function ProcessInclude(SrcZip: TZMReader; const Args: TMOArgOptions): Integer; function ProcessIncludeList(var SelectCount: Integer): Integer; function ResolveConfirm(const ExistName: string; ExistRec: TZMEntryBase; const ConflictName: string; ConflictRec: TZMEntryBase; const NewName: string): TZMResolutions; procedure SetArgsOptionsFromSplitter(var Args: TMOArgOptions; const ParentExcludes: string); procedure SetupAppendRecs(Allow: Boolean); protected FOutZip: TZMCopier; FSkippedFiles: TStringList; FSplitter: TZMArgSplitter; FZipList: TZMZipList; procedure CreateInterimZip; override; function MergeWrite: Integer; public procedure AfterConstruction; override; procedure BeforeDestruction; override; function CleanZipName(const FileName: string): string; function MergeZippedFiles(Opts: TZMMergeOpts; TheDest: TZMWriter): Integer; end; type TZMMergeArgs = class(TZMSelectArgs) private FFromDate: Cardinal; Flist: TStrings; FNFlag: Boolean; FXArg: string; FZipName: string; public function Accept(Rec: TZMCentralItem): Boolean; override; procedure AfterConstruction; override; procedure Assign(Other: TZMSelectArgs); override; property FromDate: Cardinal read FFromDate write FFromDate; property List: TStrings read Flist write Flist; property NFlag: Boolean read FNFlag write FNFlag; property XArg: string read FXArg write FXArg; property ZipName: string read FZipName write FZipName; end; const DeleteIncludeListThreshold = 20; MergeIncludeListThreshold = 10; PrepareAppendThreshold = 10; procedure TZMMergeOpr.AfterConstruction; begin inherited; FSkippedFiles := nil; FZipList := TZMZipList.Create; FSkippedFiles := TStringList.Create; FSplitter := TZMArgSplitter.Create; end; procedure TZMMergeOpr.AssignArgOptions(var Locals: TMOArgOptions; const Args: TMOArgOptions); begin Locals.Arg := Args.Arg; Locals.Excludes := Args.Excludes; Locals.NFlag := Args.NFlag; Locals.XArg := Args.XArg; end; procedure TZMMergeOpr.BeforeDestruction; begin FSkippedFiles.Free; FZipList.Free; FSplitter.Free; inherited; end; // rebuild file name without spaces function TZMMergeOpr.CleanZipName(const FileName: string): string; var Ancestors: string; Done: Boolean; Generation: string; begin Result := ''; Ancestors := FileName; repeat SplitQualifiedName(Ancestors, Ancestors, Generation); Done := Generation = ''; if Done then Generation := Ancestors; if Result <> '' then Result := Generation + ZFILE_SEPARATOR + Result else Result := Generation; until Done; end; procedure TZMMergeOpr.ClearAppend; begin SetupAppendRecs(False); // clear flags end; function TZMMergeOpr.CommitAppend: Integer; var DstZip: TZMReader; begin DstZip := FZipList[0]; DstZip.File_Close; // don't aquire handle FOutZip.Stream := DstZip.ReleaseStream; FOutZip.ArchiveName := DstZip.ArchiveName; Result := FOutZip.File_Reopen(FmOpenReadWrite); if Result >= 0 then Result := FOutZip.Commit(ZwoZipTime in WriteOptions); end; // does not create a temperary file procedure TZMMergeOpr.CreateInterimZip; begin InterimZip := TZMMerger.Create(Lister); end; // Extract MyName from FZipList[ParentIndex] and add to FZipList if successful function TZMMergeOpr.ExtractChildZip(ParentIndex: Integer; const MyName: string): Integer; var Entry: TZMEntryBase; Idx: Integer; MyFile: TZMReader; Parent: TZMReader; ParentName: string; TheZip: TZMReader; begin // be safe if (ParentIndex <= 0) or (MyName = '') then begin Result := ZMError(ZE_NoInFile, _U_ + 275); Exit; end; Parent := FZipList[ParentIndex]; ParentName := Parent.ArchiveName; if ParentName = '' then begin Result := ZMError(ZE_NoInFile, _U_ + 282); Exit; end; TheZip := TZMReader.Create(Lister); try TheZip.ArchiveName := ParentName; Diag(ZT_LoadingParentZip, _U_ + 288); Result := TheZip.OpenZip(False, False); if Result >= 0 then begin // loaded ok - see if file exists Idx := -1; Entry := TheZip.SearchName(MyName, True, Idx); // find first matching pattern if Entry <> nil then begin // create a temporary file MyFile := TZMReader.Create(Lister); try MyFile.Alias := QualifiedName(FZipList[ParentIndex].Name(False), MyName); MyFile.File_CreateTemp('Zcy', ''); Result := UnzipAStream(MyFile.Stream, Entry); if Result = 0 then begin // good MyFile.File_Close; Result := MyFile.OpenZip(False, False); MyFile.File_Close; if Result >= 0 then begin Result := FZipList.Add(MyFile); // add to list and return Index MyFile.File_Close; if Result > 0 then MyFile := nil; // do not free end; end else begin // extracting zip failed MyFile.Position := 0; MyFile.SetEndOfFile; MyFile.File_Close; Result := ZMError(ZE_NoWrite, _U_ + 325); // error does not matter end; finally MyFile.Free; end; end; end; finally TheZip.Free; end; end; function TZMMergeOpr.FlattenExcludes(Excludes: TStrings): string; var I: Integer; begin Result := ''; // flatten the list for I := 0 to Excludes.Count - 1 do begin if Excludes[I] = '' then Continue; if Result <> '' then Result := Result + SPEC_SEP;; Result := Result + Excludes[I]; end; end; function TZMMergeOpr.IncludeAZip(const SourceName: string): Integer; var Skip: TZMSkipTypes; begin Result := FZipList.Find(SourceName); // already in list? if Result = 0 then begin Result := ZMError(ZE_SourceIsDest, _U_ + 361); Exit; end; if Result < 0 then begin // have not opened file yet _ not in list Result := MergeAnotherZip(SourceName); if AbsErr(Result) = ZE_SameAsSource then Exit; if Result = 0 then begin Result := ZMError(ZE_SourceIsDest, _U_ + 372); Exit; end; if Result < 0 then begin // file does not exist or could not be opened DiagFmt(ZI_SkippedMissingOrBadZip, [AbsErr(Result), SourceName], _U_ + 379); case AbsErr(Result) of ZE_NoInFile: Skip := StNotFound; ZE_FileOpen: Skip := StNoOpen; else Skip := StReadError; end; if not Body.Skipping(SourceName, Skip, Result) then Result := 0; // we can ignore it end; end; end; // opens a zip file for merging and adds to FZipList // return <0 _ error, >= 0 _ Index in FZipList function TZMMergeOpr.MergeAnotherZip(const SourceName: string): Integer; begin if Pos(ZFILE_SEPARATOR, SourceName) > 0 then Result := MergeAnotherZipInZip(SourceName) // handle Zip in Zip else Result := MergeAnotherZip1(SourceName); end; // opens a zip file for merging and adds to FZipList // return <0 _ error, >= 0 _ Index in FZipList function TZMMergeOpr.MergeAnotherZip1(const SourceName: string): Integer; var Dzip: TZMReader; SrcZip: TZMReader; begin // have not opened file yet SrcZip := TZMReader.Create(Lister); try begin SrcZip.ArchiveName := SourceName; Result := SrcZip.OpenZip(False, False); if Result >= 0 then begin Dzip := FZipList[0]; if (SrcZip.WorkDrive.DriveLetter = Dzip.WorkDrive.DriveLetter) and (not Dzip.WorkDrive.DriveIsFixed) and (Dzip.MultiDisk or SrcZip.MultiDisk or (ZwoDiskSpan in WriteOptions)) then Result := ZMError(ZE_SameAsSource, _U_ + 424) else begin Result := FZipList.Add(SrcZip); // add to list and return Index SrcZip.File_Close; if Result > 0 then SrcZip := nil; // accepted so do not free end; end; end; finally SrcZip.Free; end; end; // handle Zip in Zip function TZMMergeOpr.MergeAnotherZipInZip(const SourceName: string): Integer; var MyName: string; MyOwner: string; begin SplitQualifiedName(SourceName, MyOwner, MyName); // find MyOwner Result := FZipList.Find(MyOwner); if Result < 0 then begin // not found _ maybe MyOwner not added yet Result := MergeAnotherZip(MyOwner); // recursively add parents end; if Result > 0 then begin // we have owner in FZipList // open MyOwner and extract MyName to temporary Result := ExtractChildZip(Result, MyName); end; end; // create the intermediate from DstZip and selected entries function TZMMergeOpr.MergeIntermediate(SelectedCount: Integer; const Opts: TZMMergeOpts): Integer; var MaxCount: Integer; RefZip: TZMReader; RefZipIndex: Integer; SelCount: Integer; begin Result := 0; PrepareInterimZip; FOutZip := InterimZip as TZMMerger; // replicate all records and settings FOutZip.Select('*', ZzsSet); // want all (initially) Progress.NewXtraItem(ZxMerging, FZipList.Count); // add the possibly altered selected entries // [0] is 'DstZip' MaxCount := 0; for RefZipIndex := 0 to FZipList.Count - 1 do MaxCount := MaxCount + FZipList[RefZipIndex].SelCount; FOutZip.HashTable.AutoSize(MaxCount); for RefZipIndex := 0 to FZipList.Count - 1 do begin Progress.AdvanceXtra(1); CheckCancel; RefZip := FZipList[RefZipIndex]; SelCount := RefZip.SelCount; DiagFmt(ZT_ProcessingFiles, [SelCount, RefZip.Name], _U_ + 489); if SelCount < 1 then Continue; Result := MergeIntermedZip(RefZip, RefZipIndex, Opts); end; end; // Merge selected entries from RefZip into FOutZip function TZMMergeOpr.MergeIntermedZip(RefZip: TZMReader; ZipIndex: Integer; Opts: TZMMergeOpts): Integer; var Cnt: Integer; NewRec: TZMEntryMerger; Rec: TZMEntryBase; RefRec: TZMEntryCopier; Skp: TZMSkipTypes; ZName: string; ZRec: TZMEntryBase; begin Result := 0; // keep compiler happy // process each selected entry Rec := RefZip.FirstSelected; Cnt := 0; while (Rec <> nil) do begin Inc(Cnt); if (Cnt and 63) = 0 then CheckCancel; Result := 0; ZRec := Rec; Rec := RefZip.NextSelected(Rec); ZName := ZRec.FileName; if ZipIndex > 0 then begin Result := MergePrepareName(ZName, ZRec); if Result < 0 then Break; // error if ZName = '' then Continue; // entry ignored by user end; // make new CopyRec NewRec := TZMEntryMerger.Create(FOutZip); // make a entry NewRec.AssignFrom(ZRec); NewRec.Link := ZRec; // link to original if Result = 1 then begin NewRec.SetStatusBit(ZsbRenamed); Result := NewRec.ChangeName(ZName); if Result < 0 then begin NewRec.Free; // stop leak DiagFmt(ZI_FailedRename, [-Result, ZRec.FileName, ZName], _U_ + 540); Skp := StUser; case AbsErr(Result) of ZE_BadFileName: Skp := StBadName; ZE_DuplFileName: Skp := StDupName; end; if Skp = StUser then Break; // unknown error - fatal if Body.Skipping(QualifiedName(RefZip.Name, ZName), Skp, Result) then Break; // fatal Continue; // ignore end; DiagFmt(ZI_RenamedTo, [ZRec.FileName, NewRec.FileName], _U_ + 554); end; // does it exist RefRec := TZMEntryCopier(FOutZip.FindName(ZName, nil)); Result := 0; if RefRec <> nil then begin // duplicate found - resolve it Result := MergeResolveConflict(RefRec, NewRec, Opts); end; if Result = 0 then begin Result := FOutZip.Add(NewRec); // use NewRec FOutZip.HashTable.Add(NewRec, False); end else NewRec.Free; // stop leak if Result < 0 then Break; end; end; // returns <0 = error, 0 = no change, 1 = changed, 2 = ignored by user function TZMMergeOpr.MergePrepareName(var ZName: string; ZRec: TZMEntryBase): Integer; var Args: TZMMergeArgs; Changed: Boolean; FileName: string; Old: string; Sep: Integer; Subst: string; TmpOnSetAddName: TZMSetAddNameEvent; ZipName: string; begin Result := 0; ZName := ZRec.FileName; Args := TZMMergeArgs(ZRec.SelectArgs); ZipName := ZRec.MyFile.Name; if (Args = nil) or not Args.NFlag then begin TmpOnSetAddName := Master.OnSetAddName; if Assigned(TmpOnSetAddName) then begin Changed := False; FileName := ZName; TmpOnSetAddName(Master, FileName, QualifiedName(ZipName, FileName), Changed); if Changed then begin Result := 1; // changed // verify valid if FileName = '' then begin Result := ZMError(ZE_EntryCancelled, _U_ + 609); if not Body.Skipping(QualifiedName(ZipName, ZRec.FileName), StUser, Result) then Result := 2; // ignore entry ZName := FileName; Exit; end; FileName := SetSlash(FileName, PsdExternal); ZName := FileName; end; end; end; if (Args <> nil) and (Args.XArg <> '') then begin Old := Args.XArg; Sep := Pos('::', Old); Subst := Copy(Old, Sep + 2, 2048); Old := Copy(Old, 1, Sep - 1); if Old = '' then FileName := Subst + ZName else begin Old := SetSlash(Old, PsdExternal); if Pos(Old, ZName) <= 0 then begin // no change Result := 0; Exit; end; FileName := StringReplace(ZName, Old, Subst, [RfReplaceAll, RfIgnoreCase]); end; FileName := SetSlash(FileName, PsdExternal); Result := 1; // changed // verify valid ZName := FileName; end; end; // return <0 = error, 0 = use NRec, 1 = discard NRec function TZMMergeOpr.MergeResolveConflict(RefRec, NRec: TZMEntryCopier; const Opts: TZMMergeOpts): Integer; var ConflictZipName: string; NewName: string; RefZipName: string; Resolve: TZMResolutions; begin RefZipName := RefRec.Link.MyFile.Name; ConflictZipName := NRec.Link.MyFile.Name; if Verbosity >= ZvTrace then DiagFmt(ZT_FoundConflictForIn, [QualifiedName(RefZipName, RefRec.FileName), ConflictZipName], _U_ + 661); Resolve := ZmrConflicting; NewName := MergeSafeName(1, RefRec.FileName); case Opts of ZmoConfirm: Resolve := ResolveConfirm(RefZipName, RefRec, ConflictZipName, NRec, NewName); ZmoAlways: ; ZmoNewer: if RefRec.ModifDateTime >= NRec.ModifDateTime then Resolve := ZmrExisting; ZmoOlder: if RefRec.ModifDateTime <= NRec.ModifDateTime then Resolve := ZmrExisting; ZmoNever: Resolve := ZmrExisting; ZmoRename: Resolve := ZmrRename; end; Result := 0; case Resolve of ZmrExisting: begin Result := Body.PrepareErrMsg(ZE_Existing, [NRec.FileName], _U_ + 685); if not Body.Skipping(QualifiedName(ConflictZipName, NRec.FileName), StFileExists, Result) then begin NRec.Selected := False; NRec.SetStatusBit(ZsbDiscard); Result := 1; // discard NRec end; end; ZmrConflicting: begin Result := Body.PrepareErrMsg(ZE_Existing, [RefRec.FileName], _U_ + 696); if not Body.Skipping(QualifiedName(RefZipName, RefRec.FileName), StFileExists, Result) then begin RefRec.Selected := False; RefRec.SetStatusBit(ZsbDiscard); Result := 0; end; end; ZmrRename: begin // zmrRename _ keep RefRec, rename and keep NRec NRec.SetStatusBit(ZsbRenamed); Result := NRec.ChangeName(NewName); if (Result < 0) then begin Result := Body.PrepareErrMsg(ZE_Existing, [RefRec.FileName], _U_ + 712); if not Body.Skipping(QualifiedName(RefZipName, RefRec.FileName), StFileExists, Result) then Result := 1; // ignore end else begin NRec.Selected := True; NRec.SetStatusBit(ZsbRenamed); Result := 0; end; end; end; end; function TZMMergeOpr.MergeSafeName(ZipIndex: Integer; const Name: string): string; var EName: string; Extn: string; N: Cardinal; begin EName := ExtractFilePath(Name) + ExtractNameOfFile(Name); Extn := ExtractFileExt(Name); N := 0; repeat if N = 0 then Result := Format('%s[%d]%s', [EName, ZipIndex, Extn]) else Result := Format('%s[%d.%x]%s', [EName, ZipIndex, N, Extn]); Inc(N); until (FOutZip.FindName(Result, nil) = nil); end; function TZMMergeOpr.MergeWrite: Integer; var DstZip: TZMReader; // orig dest zip (read only) Existed: Boolean; I: Integer; Includes: Integer; Rec: TZMEntryCopier; RenamedCnt: Integer; ReplaceCnt: Integer; Rubbish: Integer; SourceZip: TZMReader; TotalCnt: Integer; WillSplit: Boolean; begin // find total files in dest and list of files added/replaced DstZip := FZipList[0]; Body.ClearIncludeSpecs; // add names of files to be added Includes := 0; TotalCnt := 0; ReplaceCnt := 0; Rubbish := 0; RenamedCnt := 0; for I := 0 to FOutZip.Count - 1 do begin CheckCancel; Rec := TZMEntryCopier(FOutZip[I]); if Rec.StatusBit[ZsbError or ZsbDiscard or ZsbSelected] <> ZsbSelected then begin Inc(Rubbish); Continue; end; SourceZip := TZMReader(Rec.Link.MyFile); if Rec.StatusBit[ZsbDiscard] <> 0 then begin if SourceZip = DstZip then Inc(ReplaceCnt); Inc(Rubbish); Continue; end; Inc(TotalCnt); if SourceZip = DstZip then Continue; // count and mark for later adding to FSpecArgs if Rec.StatusBit[ZsbRenamed] <> 0 then Inc(RenamedCnt); Rec.Status[ZsbHail] := True; Inc(Includes); end; DiagFmt(ZT_TotalReplacedNewDiscarded, [TotalCnt, ReplaceCnt, Includes, Rubbish, RenamedCnt], _U_ + 795); if (TotalCnt < 1) or (Includes < 1) then begin Diag(ZI_NothingToDo, _U_ + 798); Result := ZMError(ZE_NothingToDo, _U_ + 799); if not Body.Skipping(DstZip.Name, StNothingToDo, Result) then Result := 0; Exit; end; // can we just append to original Existed := (Zfi_Loaded and DstZip.Info) <> 0; WillSplit := DstZip.MultiDisk or ((not Existed) and (ZwoDiskSpan in WriteOptions)); if (not WillSplit) or (not(ZwoSafe in WriteOptions)) then begin if not Existed then begin // need to create the new file // write new file FOutZip.ArchiveName := DstZip.ArchiveName; FOutZip.ZipComment := Lister.ZipComment; // keep orig ShowProgress := ZspFull; if Assigned(DstZip.Stub) and DstZip.UseSFX then begin FOutZip.AssignStub(DstZip); FOutZip.UseSFX := True; end; Result := ZMError(ZE_NoOutFile, _U_ + 822); FOutZip.File_Create(DstZip.ArchiveName); if FOutZip.IsOpen then begin Result := FOutZip.Commit(ZwoZipTime in WriteOptions); FOutZip.File_Close; FZipList.CloseAll; // close all source files end; // if Result < 0 then DiagErr(ZI_MergingNewFileFailed, Result, _U_ + 831); Exit; end else begin // try to append to existing zip if PrepareAppend then begin // commit it Result := CommitAppend; if Result >= 0 then Diag(ZT_MergingAppendSuccessful, _U_ + 842); if AbsErr(Result) <> ZE_NoAppend then Exit; // fix to allow safe write ClearAppend; DiagErr(ZI_MergingAppendFailed, Result, _U_ + 847); end; end; end; // write to intermediate if WillSplit then FOutZip.File_CreateTemp(PRE_INTER, '') else FOutZip.File_CreateTemp(PRE_INTER, DstZip.ArchiveName); if not FOutZip.IsOpen then begin Result := ZMError(ZE_NoOutFile, _U_ + 859); Exit; end; if not WillSplit then begin // initial temporary destination if Assigned(DstZip.Stub) and DstZip.UseSFX then begin FOutZip.AssignStub(DstZip); FOutZip.UseSFX := True; end; FOutZip.DiskNr := 0; end; FOutZip.ZipComment := DstZip.ZipComment; // keep orig ShowProgress := ZspFull; // now we write it Result := FOutZip.Commit(ZwoZipTime in WriteOptions); FOutZip.File_Close; FZipList.CloseAll; // close all source files if Result >= 0 then begin if (FOutZip.Count - Rubbish) <> TotalCnt then Result := ZMError(ZE_InternalError, _U_ + 881) else Result := Recreate(FOutZip, DstZip); // all correct so Recreate source end; end; // IncludeSpecs = Zips and files to include // zipname // ExcludeSpecs = files to exclude function TZMMergeOpr.MergeZippedFiles(Opts: TZMMergeOpts; TheDest: TZMWriter): Integer; var DstZip: TZMReader; SelectCount: Integer; begin ShowProgress := ZspFull; FOutZip := nil; // will be used to write the output if IncludeSpecs.Count < 1 then raise EZipMaster.CreateMsg(Body, ZE_InvalidArguments, _U_ + 899); if ZipFileName = '' then raise EZipMaster.CreateMsg(Body, ZE_NoZipSpecified, _U_ + 901); FZipList.Clear; FSkippedFiles.Clear; if TheDest <> nil then DstZip := TheDest else DstZip := Prepare(False, True); DstZip.Select('*', ZzsSet); // initial want all FZipList.ProtectZero := True; // do not destroy DstZip FZipList.Add(DstZip); // add source zips to list and select their files Result := ProcessIncludeList(SelectCount); if Result < 0 then raise EZipMaster.CreateMsg(Body, Result, 0); Body.ClearIncludeSpecs; // for new/updated files if SelectCount >= 1 then begin // add all selected to OutZip Result := MergeIntermediate(SelectCount, Opts); if Result < 0 then raise EZipMaster.CreateMsg(Body, Result, 0); // we have processed list now resolve merge conflicts // write the results if Result >= 0 then Result := MergeWrite; // Update the Zip Directory by calling List method // for spanned exe avoid swapping to last disk Reload := ZlrReload; // force reload end; if Result < 0 then raise EZipMaster.CreateMsg(Body, Result, 0); // it was successful SuccessCnt := IncludeSpecs.Count; FZipList.Clear; FSkippedFiles.Clear; end; (* TZMMergeOpr.Prepare Prepare destination and get SFX stub as needed *) function TZMMergeOpr.Prepare(MustExist: Boolean; SafePart: Boolean = False) : TZMReader; var Err: Integer; begin Result := CurrentZip(MustExist, SafePart); Err := PrepareZip(Result); if Err < 0 then raise EZipMaster.CreateMsg(Body, Err, 0); end; // prepare to commit by appending to orig file, return false if not possible function TZMMergeOpr.PrepareAppend: Boolean; var DstZip: TZMReader; HighKept: Int64; I: Integer; LocalOfs: Int64; LowDiscard: Int64; OrigCnt: Integer; Rec: TZMEntryMerger; ShowXProgress: Boolean; begin Result := False; DstZip := FZipList[0]; OrigCnt := DstZip.Count; if OrigCnt < 1 then Exit; // check can append ShowXProgress := OrigCnt > PrepareAppendThreshold; if ShowXProgress then Progress.NewXtraItem(ZxProcessing, IncludeSpecs.Count); LowDiscard := DstZip.SOCOfs; HighKept := -1; for I := 0 to OrigCnt - 1 do begin if ShowXProgress then Progress.AdvanceXtra(1); CheckCancel; Rec := TZMEntryMerger(FOutZip[I]); if (Rec = nil) or (Rec.StatusBit[ZsbError] <> 0) then Continue; LocalOfs := Rec.RelOffLocalHdr; if Rec.StatusBit[ZsbDiscard] <> 0 then begin if LocalOfs < LowDiscard then begin LowDiscard := LocalOfs; if HighKept > LowDiscard then Exit; // would produce a hole end; end else begin if LocalOfs > HighKept then begin HighKept := LocalOfs; if HighKept > LowDiscard then Exit; // would produce a hole end; end; end; Diag(ZT_ShouldBeAbleToAppend, _U_ + 1003); SetupAppendRecs(True); Result := True; end; // select files in Source, return files selected or <0 = error function TZMMergeOpr.ProcessInclude(SrcZip: TZMReader; const Args: TMOArgOptions): Integer; var MergeArgs: TZMMergeArgs; begin if Verbosity > ZvVerbose then DiagStr(ZT_Including, QualifiedName(SrcZip.Name, Args.Arg), _U_ + 1015); MergeArgs := TZMMergeArgs.Create; MergeArgs.ZipName := SrcZip.ArchiveName; MergeArgs.FromDate := DateTimeToFileDate(Lister.AddFrom); MergeArgs.List := FSkippedFiles; MergeArgs.XArg := Args.XArg; MergeArgs.NFlag := Args.NFlag; Result := SrcZip.SelectRec(Args.Arg, Args.Excludes, ZzsSet, MergeArgs); if Result < 1 then begin // none found MergeArgs.Free; Result := ZMError(ZE_NotFound, _U_ + 1027); if not Body.Skipping(QualifiedName(SrcZip.Name(), Args.Arg), StNotFound, Result) then Result := 0; end else SrcZip.AddSelectArgs(MergeArgs); end; // returns <0 _ error (* [zipname] [switch] [[switch] ...] switches /N[+ or -] flags not to use AddNewName (default N- _ use AddNewName) /X:[old]::[new] replace 'old' with 'new' - must result in valid internal name >>spec before any source zip is specified sets the default select spec >>spec select files in current zip according to spec /E:[|][spec[|spec]...] set excludes, if starts with | it appends to globals otherwise use spec changes to excludes occur at current line and continue until changed - does not change already included files. when used on same line as '>>' it only applies to that line and modifies the 'current' excludes. *) function TZMMergeOpr.ProcessIncludeList(var SelectCount: Integer): Integer; var DefaultExcludes: string; Effectives: TMOArgOptions; I: Integer; Locals: TMOArgOptions; ShowXProgress: Boolean; ZipsIndex: Integer; begin Result := 0; SelectCount := 0; DefaultExcludes := FlattenExcludes(ExcludeSpecs); Effectives.Excludes := DefaultExcludes; Effectives.Arg := '*.*'; Effectives.NFlag := False; // N- or none Effectives.XArg := ''; FSplitter.Allow := '>ENX'; FSplitter.Options := [ZaoLastSpec, ZaoWildSpec, ZaoMultiSpec]; // locate source zips and their files ZipsIndex := ZMError(ZE_NoInFile, _U_ + 1070); // no current yet ShowXProgress := IncludeSpecs.Count > MergeIncludeListThreshold; if ShowXProgress then Progress.NewXtraItem(ZxProcessing, IncludeSpecs.Count); for I := 0 to IncludeSpecs.Count - 1 do begin if Result < 0 then Break; if ShowXProgress then Progress.AdvanceXtra(1); CheckCancel; Result := 0; FSplitter.Raw := IncludeSpecs[I]; if FSplitter.Error <> ZasNone then raise EZipMaster.CreateMsgFmt(Body, ZE_InvalidParameter, [FSplitter.Raw], _U_ + 1085); if FSplitter.Main <> '' then begin // we are specifying a zip to process ZipsIndex := IncludeAZip(FSplitter.Main); Result := ZipsIndex; if Result < 0 then Break; // error if Result = 0 then Continue; // skipped it // process spec and/or switches end else // no zip specified begin // ignore empty lines if FSplitter.Found = '' then Continue; // any zips specified yet if ZipsIndex < 0 then begin // none yet, set defaults SetArgsOptionsFromSplitter(Effectives, DefaultExcludes); Continue; end; end; if (Result < 0) or (ZipsIndex < 0) then Break; // must have open file if FSplitter.Has(ZSPECARG) or (FSplitter.Main <> '') then begin // using local settings from splitter AssignArgOptions(Locals, Effectives); SetArgsOptionsFromSplitter(Locals, Effectives.Excludes); // include a spec in the current zip Result := ProcessInclude(FZipList[ZipsIndex], Locals); if Result > 0 then SelectCount := SelectCount + Result; Continue; end; // Only have switches _ Set effectives SetArgsOptionsFromSplitter(Effectives, DefaultExcludes); end; end; function TZMMergeOpr.ResolveConfirm(const ExistName: string; ExistRec: TZMEntryBase; const ConflictName: string; ConflictRec: TZMEntryBase; const NewName: string): TZMResolutions; var ConflictEntry: TZM_ConflictEntry; ExistEntry: TZM_ConflictEntry; Response: Integer; TmpZippedConflict: TZMMergeZippedConflictEvent; begin // Do we have a event assigned for this then don't ask. TmpZippedConflict := Master.OnMergeZippedConflict; if Assigned(TmpZippedConflict) then begin ConflictEntry := nil; ExistEntry := TZM_ConflictEntry.Create(Master, ExistRec); try ExistEntry.ZipName := ExistName; ConflictEntry := TZM_ConflictEntry.Create(Master, ConflictRec); ConflictEntry.ZipName := ConflictName; Result := ZmrRename; TmpZippedConflict(Master, ExistEntry, ConflictEntry, Result); finally ExistEntry.Free; ConflictEntry.Free; end; Exit; end; Response := ZipMessageDlgEx(ZipLoadStr(ZC_FileConflict), Format(ZipLoadStr(ZC_Merge), [QualifiedName(ExistName, ExistRec.XName), QualifiedName(ConflictName, ConflictRec.XName), NewName]), ZmtConfirmation + DHC_CpyZipOvr, [MbYes, MbNo, MbIgnore]); if Response = MrOk then Result := ZmrRename else if Response = MrNo then Result := ZmrExisting else Result := ZmrConflicting; end; procedure TZMMergeOpr.SetArgsOptionsFromSplitter(var Args: TMOArgOptions; const ParentExcludes: string); var Xc: string; begin if FSplitter.Has(ZSPECARG) then begin Args.Arg := FSplitter.Arg(ZSPECARG); if Args.Arg = '' then Args.Arg := '*.*'; end; if FSplitter.Has('E') then begin Xc := FSplitter.Arg('E'); if (Xc <> '') and (Xc[1] = SPEC_SEP) then begin if Xc <> SPEC_SEP then Args.Excludes := ParentExcludes + Xc; end else Args.Excludes := Xc; end; if FSplitter.Has('N') then Args.NFlag := FSplitter.Arg('N') = '+'; if FSplitter.Has('X') then Args.XArg := FSplitter.Arg('X'); end; procedure TZMMergeOpr.SetupAppendRecs(Allow: Boolean); var DstZip: TZMReader; I: Integer; OrigCnt: Integer; Rec: TZMEntryMerger; begin DstZip := FZipList[0]; OrigCnt := DstZip.Count; if OrigCnt < 1 then Exit; for I := 0 to OrigCnt - 1 do begin CheckCancel; Rec := TZMEntryMerger(FOutZip[I]); if (Rec = nil) or (Rec.StatusBit[ZsbError or ZsbDiscard or ZsbSelected] <> ZsbSelected) then Continue; Rec.Keep := Allow; end; end; { TZMMerger } procedure TZMMerger.AfterConstruction; begin inherited; LastOpened := nil; end; function TZMMerger.CommitRec(Rec: TZMEntryWriter): Int64; var Err: Integer; InFile: TZMFileIO; MergeRec: TZMEntryMerger; begin if (not(Rec is TZMEntryMerger)) or (TZMEntryMerger(Rec).Link = nil) then begin Result := inherited CommitRec(Rec); Exit; end; MergeRec := TZMEntryMerger(Rec); if MergeRec.Keep then begin Result := MergeRec.Process; end else begin Result := MergeRec.ProcessSize; if Result > 0 then begin InFile := MergeRec.Link.MyFile; if (not InFile.IsOpen) and (InFile <> LastOpened) then begin if IsTrace then // Verbosity >= zvTrace then DiagStr(ZT_Opening, InFile.Name(True), _U_ + 1251); if FLastOpened <> nil then FLastOpened.File_Close; LastOpened := InFile; Err := InFile.File_Reopen(FmOpenRead or FmShareDenyWrite); // open it if Err < 0 then begin Result := Err; Exit; end; end; Result := MergeRec.Process; end; end; end; procedure TZMMerger.SetLastOpened(const Value: TZMFileIO); begin if FLastOpened <> Value then begin if FLastOpened <> nil then FLastOpened.File_Close; FLastOpened := Value; end; end; procedure TZMEntryMerger.AfterConstruction; begin inherited; Keep := False; end; function TZMEntryMerger.GetTitle: string; begin Result := QualifiedName(Link.MyFile.Name, Link.FileName) + ' => ' + FileName; end; function TZMEntryMerger.Process: Int64; var LOH: TZipLocalHeader; Nxt: Int64; begin if not Keep then begin Result := inherited Process; Exit; end; // verify at correct header Result := SeekLocalData(LOH, _FileName); if Result >= 0 then begin Nxt := RelOffLocalHdr + ProcessSize; // Good - Position to next entry if MyFile.Seek(Nxt, SoBeginning) = Nxt then Result := 0 else Result := ZMError(ZE_SeekError, _U_ + 1307); end else // if Result < 0 then <<< must be <0 Result := ZMError(ZE_NoAppend, _U_ + 1311); end; // return false = reject, too old function TZMMergeArgs.Accept(Rec: TZMCentralItem): Boolean; begin Result := True; if FromDate <> 0 then Result := FromDate <= Rec.ModifDateTime; end; procedure TZMMergeArgs.AfterConstruction; begin inherited; end; procedure TZMMergeArgs.Assign(Other: TZMSelectArgs); var Src: TZMMergeArgs; begin inherited; if Other is TZMMergeArgs then begin Src := TZMMergeArgs(Other); FFromDate := Src.FromDate; Flist := Src.List; FNFlag := Src.NFlag; FXArg := Src.XArg; FZipName := Src.ZipName; end; end; constructor TZMOpMerge.Create(Opts: TZMMergeOpts); begin inherited Create; FOpts := Opts; end; { TZMOpMerge } function TZMOpMerge.Changes: TZMOperRes; begin Result := [ZorFSpecArgs, ZorZip]; end; function TZMOpMerge.Execute(TheBody: TZMHandler): Integer; var FOper: TZMMergeOpr; begin FOper := TZMMergeOpr.Create(TheBody as TZMLister); AnOperation := FOper; Result := FOper.MergeZippedFiles(FOpts, nil); end; function TZMOpMerge.Name: string; begin Result := 'MergeZippedFiles'; end; function TZMOpMerge.Needs: TZMOperRes; begin Result := [ZorFSpecArgs, ZorZip]; end; end.
{!DOCTOPIC}{ Matrix » TByteMatrix } {!DOCREF} { @method: Single percision floating point matrix @desc: [hr] } {!DOCREF} { @method: procedure TByteMatrix.SetSize(Height,Width:Int32); @desc: Sets the size (width and height) of the matrix. Same as SetLength(Matrix, H,W); } procedure TByteMatrix.SetSize(Height,Width:Int32); begin SetLength(Self, Height,Width); end; {!DOCREF} { @method: function TByteMatrix.Width(): Int32; @desc: Retruns the width of the matrix (safely) } function TByteMatrix.Width(): Int32; begin if Length(Self) > 0 then Result := Length(Self[0]) else Result := 0; end; {!DOCREF} { @method: function TByteMatrix.Height(): Int32; @desc: Retruns the height of the matrix } function TByteMatrix.Height(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TByteMatrix.Get(const Indices:TPointArray): TByteArray @desc: Gets all the values at the given indices. If any of the points goes out of bounds, it will simply be ignored. [code=pascal] var Matrix:TByteMatrix; begin Matrix.SetSize(100,100); Matrix[10][10] := 100; Matrix[10][13] := 29; WriteLn( Matrix.Get([Point(10,10),Point(13,10),Point(20,20)])); end; [/code] } function TByteMatrix.Get(const Indices:TPointArray): TByteArray; begin Result := exp_GetValues(Self, Indices); end; {!DOCREF} { @method: procedure TByteMatrix.Put(const TPA:TPointArray; Values:TByteArray); @desc: Adds the points to the matrix with the given values. } procedure TByteMatrix.Put(const TPA:TPointArray; Values:TByteArray); begin exp_PutValues(Self, TPA, Values); end; {!DOCREF} { @method: procedure TByteMatrix.Put(const TPA:TPointArray; Value:Byte); overload; @desc: Adds the points to the matrix with the given value. } procedure TByteMatrix.Put(const TPA:TPointArray; Value:Byte); overload; begin exp_PutValues(Self, TPA, TByteArray([Value])); end; {!DOCREF} { @method: function TByteMatrix.Merge(): TByteArray; @desc: Merges the matrix is to a flat array of the same type. } function TByteMatrix.Merge(): TByteArray; var i,s,wid: Int32; begin S := 0; SetLength(Result, Self.Width()*Self.Height()); Wid := Self.Width(); for i:=0 to High(Self) do begin MemMove(Self[i][0], Result[S], Wid*SizeOf(Byte)); S := S + Wid; end; end; {!DOCREF} { @method: function TByteMatrix.Sum(): Int64; @desc: Returns the sum of the matrix } function TByteMatrix.Sum(): Int64; var i: Integer; begin for i:=0 to High(Self) do Result := Result + Self[i].Sum(); end; {!DOCREF} { @method: function TByteMatrix.Mean(): Double; @desc: Returns the mean of the matrix } function TByteMatrix.Mean(): Double; var i: Integer; begin for i:=0 to High(Self) do Result := Result + Self[i].Mean(); Result := Result / Length(Self); end; {!DOCREF} { @method: function TByteMatrix.Stdev(): Single; @desc: Returns the standard deviation of the matrix } function TByteMatrix.Stdev(): Single; var x,y,W,H,i:Int32; avg:Single; square:TFloatArray; begin W := Self.Width() - 1; H := Self.Height() - 1; avg := Self.Mean(); SetLength(square,Self.Width()*Self.Height()); i:=-1; for y:=0 to H do for x:=0 to W do Square[inc(i)] := Sqr(Self[y,x] - avg); Result := Sqrt(square.Mean()); end; {!DOCREF} { @method: function TByteMatrix.Variance(): Double; @desc: Return the sample variance. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the matrix. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. } function TByteMatrix.Variance(): Double; var avg:Double; x,y,w,h:Int32; begin W := Self.Width() - 1; H := Self.Height() - 1; avg := Self.Mean(); for y:=0 to H do for x:=0 to W do Result := Result + Sqr(Self[y,x] - avg); Result := Result / ((W+1) * (H+1)); end; {!DOCREF} { @method: function TByteMatrix.Mode(): Byte; @desc: Returns the sample mode of the matrix, which is the most frequently occurring value in the matrix. When there are multiple values occurring equally frequently, mode returns the smallest of those values. } function TByteMatrix.Mode(): Byte; begin Result := Self.Merge().Mode(); end; {------------| GetArea, GetCols, GetRows |------------} {!DOCREF} { @method: function TByteMatrix.Area(X1,Y1,X2,Y2:Int32): TByteMatrix; @desc: Crops the matrix to the given box and returns that area. } function TByteMatrix.Area(X1,Y1,X2,Y2:Int32): TByteMatrix; begin Result := exp_GetArea(Self, X1,Y1,X2,Y2); end; {!DOCREF} { @method: function TByteMatrix.Cols(FromCol, ToCol:Integer): TByteMatrix; @desc: Returns all the wanted columns as a new matrix. } function TByteMatrix.Cols(FromCol, ToCol:Integer): TByteMatrix; begin Result := exp_GetCols(Self, FromCol, ToCol); end; {!DOCREF} { @method: function TByteMatrix.Rows(FromRow, ToRow:Integer): TByteMatrix; @desc: Returns all the wanted rows as a new matrix. } function TByteMatrix.Rows(FromRow, ToRow:Integer): TByteMatrix; begin Result := exp_GetRows(Self, FromRow, ToRow); end; {------------| FlipMat |------------} {!DOCREF} { @method: function TByteMatrix.Rows(FromRow, ToRow:Integer): TByteMatrix; @desc: Order of the items in the array is flipped, meaning x becomes y, and y becomes x. Example: [code=pascal] var x:TByteMatrix; begin x := [[1,2,3],[1,2,3],[1,2,3]]; WriteLn(x.Flip()); end. [/code] >> `[[1, 1, 1], [2, 2, 2], [3, 3, 3]]` } function TByteMatrix.Flip(): TByteMatrix; begin Result := exp_Flip(Self); end; {------------| Indices |------------} {!DOCREF} { @method: function TByteMatrix.Indices(Value: Byte; const Comparator:TComparator): TPointArray; @desc: Returns all the indices which matches the given value, and comperator. EG: c'Matrix.Indices(10, __LT__)' would return all the items which are less then 10. } function TByteMatrix.Indices(Value: Byte; const Comparator:TComparator): TPointArray; begin Result := exp_Indices(Self, Value, Comparator); end; {!DOCREF} { @method: function TByteMatrix.Indices(Value: Byte; B:TBox; const Comparator:TComparator): TPointArray; overload; @desc: Returns all the indices which matches the given value, and comperator. EG: c'Matrix.Indices(10, __LT__)' would return all the items which are less then 10. Takes an extra param to only check a cirtain area of the matrix. } function TByteMatrix.Indices(Value: Byte; B:TBox; const Comparator:TComparator): TPointArray; overload; begin Result := exp_Indices(Self, B, Value, Comparator); end; {------------| ArgMin/ArgMax |------------} {!DOCREF} { @method: function TByteMatrix.ArgMax(): TPoint; @desc: ArgMax returns the index of the largest item } function TByteMatrix.ArgMax(): TPoint; begin Result := exp_ArgMax(Self) end; {!DOCREF} { @method: function TByteMatrix.ArgMax(Count:Int32): TPointArray; overload; @desc: Returns the n-largest elements, by index } function TByteMatrix.ArgMax(Count:Int32): TPointArray; overload; begin Result := exp_ArgMulti(Self, Count, True); end; {!DOCREF} { @method: function TByteMatrix.ArgMax(B:TBox): TPoint; overload; @desc: ArgMax returns the index of the largest item within the given bounds c'B'. } function TByteMatrix.ArgMax(B:TBox): TPoint; overload; begin Result := exp_ArgMax(Self, B); end; {!DOCREF} { @method: function TByteMatrix.ArgMin(): TPoint; @desc: ArgMin returns the index of the smallest item. } function TByteMatrix.ArgMin(): TPoint; begin if Length(Self) > 0 then Result := exp_ArgMin(Self); end; {!DOCREF} { @method: function TByteMatrix.ArgMin(Count:Int32): TPointArray; overload; @desc: Returns the n-smallest elements, by index } function TByteMatrix.ArgMin(Count:Int32): TPointArray; overload; begin Result := exp_ArgMulti(Self, Count, False); end; {!DOCREF} { @method: function TByteMatrix.ArgMin(B:TBox): TPoint; overload; @desc: ArgMin returns the index of the smallest item within the given bounds c'B'. } function TByteMatrix.ArgMin(B:TBox): TPoint; overload; begin if Length(Self) > 0 then Result := exp_ArgMin(Self, B); end; {------------| VarMin/VarMax |------------} {!DOCREF} { @method: function TByteMatrix.VarMax(): Byte; @desc: ArgMax returns the largest item } function TByteMatrix.VarMax(): Byte; var tmp:TPoint; begin tmp := exp_ArgMax(Self); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TByteMatrix.VarMax(Count:Int32): TByteArray; overload; @desc: Returns the n-largest elements } function TByteMatrix.VarMax(Count:Int32): TByteArray; overload; begin Result := exp_VarMulti(Self, Count, True); end; {!DOCREF} { @method: function TByteMatrix.VarMax(B:TBox): Byte; overload; @desc: ArgMax returns the largest item within the given bounds `B` } function TByteMatrix.VarMax(B:TBox): Byte; overload; var tmp:TPoint; begin tmp := exp_ArgMax(Self, B); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TByteMatrix.VarMin(): Byte; @desc: ArgMin returns the the smallest item } function TByteMatrix.VarMin(): Byte; var tmp:TPoint; begin tmp := exp_ArgMin(Self); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TByteMatrix.VarMin(Count:Int32): TByteArray; overload; @desc: Returns the n-smallest elements } function TByteMatrix.VarMin(Count:Int32): TByteArray; overload; begin Result := exp_VarMulti(Self, Count, False); end; {!DOCREF} { @method: function TByteMatrix.VarMin(B:TBox): Byte; overload; @desc: VarMin returns the smallest item within the given bounds `B` } function TByteMatrix.VarMin(B:TBox): Byte; overload; var tmp:TPoint; begin tmp := exp_ArgMin(Self, B); Result := Self[tmp.y, tmp.x]; end; {------------| MinMax |------------} {!DOCREF} { @method: procedure TByteMatrix.MinMax(var Min, Max:Byte); @desc: Returns the smallest, and the largest element in the matrix. } procedure TByteMatrix.MinMax(var Min, Max:Byte); begin exp_MinMax(Self, Min, Max); end; {------------| CombineMatrix |------------} {!DOCREF} { @method: function TByteMatrix.Combine(Other:TByteMatrix; OP:Char='+'): TByteMatrix; @desc: Merges the two matrices in to one matrix.. Supports different operatrions/methods for combining ['+','-','*','/']. [code=pascal] var Mat:TByteMatrix; begin SetLength(Mat, 3); Mat[0] := [1,1,1]; Mat[1] := [2,2,2]; Mat[2] := [3,3,3]; WriteLn( Mat.Combine(Mat, '*') ); end. [/code] Outputs: >>> `[[1, 1, 1], [4, 4, 4], [9, 9, 9]]` } function TByteMatrix.Combine(Other:TByteMatrix; OP:Char='+'): TByteMatrix; begin Result := exp_CombineMatrix(Self, Other, OP); end; {------------| Normalize (Matrix) |------------} {!DOCREF} { @method: function TByteMatrix.Normalize(Alpha, Beta:Byte): TByteMatrix; @desc: Fits each element of the matrix within the values of Alpha and Beta. } function TByteMatrix.Normalize(Alpha, Beta:Byte): TByteMatrix; begin Result := exp_Normalize(Self, Alpha, Beta); end;
unit ujxDataEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GridsEh, DBGridEh, DB, DBClient, StdCtrls, Buttons,CnProgressFrm, ExtCtrls, pngimage, frxpngimage, Mask, DBCtrlsEh, DBFieldComboBox, DBGridEhGrouping; type TjxDataEdit = class(TForm) pnl_Title: TPanel; img_Title: TImage; img_Hint: TImage; lbl_Title: TLabel; Panel2: TPanel; btn_Exit: TBitBtn; DataSource1: TDataSource; ClientDataSet1: TClientDataSet; DBGridEh1: TDBGridEh; grp1: TGroupBox; cbb_Xq: TDBComboBoxEh; cbb_Field: TDBFieldComboBox; edt_Value: TEdit; btn_Search: TBitBtn; lbl_Len: TLabel; grp2: TGroupBox; cbb_Xn: TDBComboBoxEh; btn_Export: TBitBtn; grp3: TGroupBox; cbb_Xy: TDBComboBoxEh; btn_Save: TBitBtn; chk_DisplayErrorRecord: TCheckBox; chk_AllowEdit: TCheckBox; btn_Delete: TBitBtn; btn_Edit: TBitBtn; btn_Initialize: TBitBtn; procedure btn_ExitClick(Sender: TObject); procedure btn_RefreshClick(Sender: TObject); procedure btn_AddClick(Sender: TObject); procedure btn_CancelClick(Sender: TObject); procedure btn_ExportClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbb_XqChange(Sender: TObject); procedure btn_SearchClick(Sender: TObject); procedure edt_ValueChange(Sender: TObject); procedure btn_SaveClick(Sender: TObject); procedure ClientDataSet1FilterRecord(DataSet: TDataSet; var Accept: Boolean); procedure ClientDataSet1NewRecord(DataSet: TDataSet); procedure rg_PostClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btn_DisplayErrorRecordClick(Sender: TObject); procedure chk_DisplayErrorRecordClick(Sender: TObject); procedure chk_AllowEditClick(Sender: TObject); procedure btn_EditClick(Sender: TObject); procedure btn_DeleteClick(Sender: TObject); procedure btn_InitializeClick(Sender: TObject); private { Private declarations } function GetWhere:string; procedure Open_Table; procedure GetbkLbList; procedure GetKsKcList; public { Public declarations } procedure SetYxSfKmValue(const Yx,Sf,Km:string); procedure SetFieldValue(const iCjIndex:Integer;const sCjField,sCzyField:string); end; implementation uses uDM; {$R *.dfm} procedure TjxDataEdit.btn_AddClick(Sender: TObject); begin ClientDataSet1.Append; DBGridEh1.SetFocus; end; procedure TjxDataEdit.btn_CancelClick(Sender: TObject); begin ClientDataSet1.Cancel; end; procedure TjxDataEdit.btn_DeleteClick(Sender: TObject); begin if MessageBox(Handle, '真的要删除当前记录吗? ', '系统提示', MB_YESNO + MB_ICONWARNING + MB_DEFBUTTON2 + MB_TOPMOST) = IDYES then begin ClientDataSet1.Delete; end; end; procedure TjxDataEdit.btn_DisplayErrorRecordClick(Sender: TObject); var sqlStr:string; begin sqlStr := 'select * from 教学任务表 where 规则号 in (select 规则号 from 教学任务表 group by 规则号 having count(*)>1)'; end; procedure TjxDataEdit.btn_EditClick(Sender: TObject); begin DBGridEh1.SetFocus; end; procedure TjxDataEdit.btn_ExitClick(Sender: TObject); begin Close; end; procedure TjxDataEdit.btn_ExportClick(Sender: TObject); begin dm.ExportDBEditEH(DBGridEH1); end; procedure TjxDataEdit.btn_InitializeClick(Sender: TObject); var i,ii,iWeekCount:Integer; kk,zxs1,zxs2,weekstr :string; lrxs,syxs:Double; begin ClientDataSet1.First; Screen.Cursor := crHourGlass; ClientDataSet1.DisableControls; try ShowProgress('正在处理...',ClientDataSet1.RecordCount); while not ClientDataSet1.Eof do begin UpdateProgress(ClientDataSet1.RecNo); kk := ClientDataSet1.FieldByName('周学时').AsString; ii := Pos('-',kk); if ii>0 then begin zxs1 := Copy(kk,1,ii-1); zxs2 := Copy(kk,ii+1,10); end else begin zxs1 := Copy(kk,1,10); zxs2 := '0.0'; end; lrxs := StrToFloatDef(zxs1,0); syxs := StrToFloatDef(zxs2,0); weekstr := ClientDataSet1.FieldByName('起止周').AsString; ii := Pos('-',weekstr); if ii>0 then begin iWeekCount := StrToIntDef(Copy(weekstr,ii+1,10),0)-StrToIntDef(Copy(weekstr,1,ii-1),0)+1; lrxs := lrxs*iWeekCount; end else begin iWeekCount := 1; //StrToIntDef(weekstr,0); syxs := syxs*iWeekCount; end; if lrxs>0 then begin ClientDataSet1.Edit; ClientDataSet1.FieldByName('理论学时').AsFloat := lrxs; ClientDataSet1.Post; end; if syxs>0 then begin ClientDataSet1.Edit; ClientDataSet1.FieldByName('实验学时').AsFloat := syxs; ClientDataSet1.Post; end; ClientDataSet1.Next; end; btn_Save.Click; finally HideProgress; ClientDataSet1.EnableControls; Screen.Cursor := crDefault; end; end; procedure TjxDataEdit.btn_RefreshClick(Sender: TObject); begin Open_Table; end; procedure TjxDataEdit.btn_SaveClick(Sender: TObject); begin if DataSetNoSave(ClientDataSet1) then begin if dm.UpdateData('id','select top 0 * from 教学任务表',ClientDataSet1.Delta,True) then ClientDataSet1.MergeChangeLog; end; end; procedure TjxDataEdit.btn_SearchClick(Sender: TObject); begin ClientDataSet1.Filtered := False; ClientDataSet1.Filtered := edt_Value.Text<>''; end; procedure TjxDataEdit.cbb_XqChange(Sender: TObject); begin if Self.Showing then Open_Table; end; procedure TjxDataEdit.chk_AllowEditClick(Sender: TObject); begin DBGridEh1.ReadOnly := not TCheckBox(Sender).Checked; //ClientDataSet1.ReadOnly := DBGridEh1.ReadOnly; btn_Edit.Visible := TCheckBox(Sender).Checked; btn_Delete.Visible := TCheckBox(Sender).Checked; btn_Save.Visible := TCheckBox(Sender).Checked; end; procedure TjxDataEdit.chk_DisplayErrorRecordClick(Sender: TObject); begin Open_Table; end; procedure TjxDataEdit.ClientDataSet1FilterRecord(DataSet: TDataSet; var Accept: Boolean); begin Accept := Pos(edt_Value.Text,DataSet.FieldByName(cbb_Field.Text).AsString)>0; end; procedure TjxDataEdit.ClientDataSet1NewRecord(DataSet: TDataSet); begin DataSet.FieldByName('学年').AsString := cbb_Xn.Value; DataSet.FieldByName('学期').AsString := cbb_Xq.Value; DataSet.FieldByName('开课学院').AsString := cbb_Xy.Text; end; procedure TjxDataEdit.edt_ValueChange(Sender: TObject); begin lbl_Len.Caption := '('+IntToStr(Length(edt_Value.Text))+')'; btn_Search.Click; end; procedure TjxDataEdit.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TjxDataEdit.FormCreate(Sender: TObject); var sList:TStrings; begin sList := TStringList.Create; try cbb_Xn.Items.Clear; dm.GetXnList(sList); cbb_Xn.Items.Assign(sList); cbb_Xn.Text := gb_Cur_Xn; cbb_Xq.Value := gb_Cur_Xq; cbb_Xy.Items.Clear; DM.GetXyList(sList); cbb_Xy.Items.Add('不限'); cbb_Xy.Items.AddStrings(sList); if cbb_Xy.Items.Count>0 then cbb_Xy.ItemIndex := 0; Open_Table; finally sList.Free; end; end; function TjxDataEdit.GetWhere: string; var sWhere:string; begin if cbb_Xy.Text<>'不限' then sWhere := ' and 开课学院='+quotedstr(cbb_Xy.Text); sWhere := sWhere+' and 学年='+quotedstr(cbb_Xn.Text); sWhere := sWhere+' and 学期='+quotedstr(cbb_Xq.Value); Result := sWhere; end; procedure TjxDataEdit.GetbkLbList; begin end; procedure TjxDataEdit.GetKsKcList; begin end; procedure TjxDataEdit.Open_Table; var sqlstr:string; begin Screen.Cursor := crHourGlass; try if chk_DisplayErrorRecord.Checked then sqlStr := 'select * from 教学任务表 where 规则号+授课对象 in '+ '(select 规则号+授课对象 from 教学任务表 group by 规则号+授课对象 having count(*)>1)'+ GetWhere+' order by 规则号' else sqlstr := 'select * from 教学任务表 where 1>0 '+GetWhere+' order by 规则号'; ClientDataSet1.XMLData := DM.OpenData(sqlstr); if Self.Showing then begin DBGridEh1.SetFocus; //DBGridEh1.SelectedIndex := 8; end; finally Screen.Cursor := crDefault; end; end; procedure TjxDataEdit.rg_PostClick(Sender: TObject); begin Open_Table; end; procedure TjxDataEdit.SetFieldValue(const iCjIndex:Integer;const sCjField, sCzyField: string); begin end; procedure TjxDataEdit.SetYxSfKmValue(const Yx, Sf, Km: string); begin end; end.
unit PluginAPI; interface uses ActiveX; type TClientFile = record SrvrFile: WideString; Version: WideString; ClntFile: WideString; Ext: WideString; TypeF: WideChar; Action: Integer; MD5: WideString; Source: WideChar; SID: WideString; end; ICore = interface ['{26D3EED3-A843-4E9C-83C1-FEE1ED544490}'] // private function GetVersion: Integer; safecall; // public property Version: Integer read GetVersion; end; IPlugin = interface ['{174C7DBF-C9D8-4568-8FBA-89CA8D785754}'] // private //function GetMask: WideString; safecall; function GetActionID: Integer; safecall; function GetExtension: WideString; safecall; function GetFileType: WideChar; safecall; function GetDescription: WideString; safecall; // public property ActionID: Integer read GetActionID; property FileType: WideChar read GetFileType; property Extension: WideString read GetExtension; property Description: WideString read GetDescription; end; IExportPlugin = interface ['{F78CDFC4-D72E-4D30-9639-378614F9F672}'] procedure ExportRTF(const ARTF: IStream; const AFileName: WideString); safecall; end; IImportPlugin = interface ['{52D2829D-596E-459C-B78E-9A4A2234338E}'] procedure ImportRTF(const AFileName: WideString; const ARTF: IStream); safecall; end; ISAVAccessFileAct = interface ['{339F23A7-7A7C-4D00-849E-282B6E663CFD}'] function ProcessedFile(const aOld, aNew: TClientFile; const aDir, aSID, aPath: WideString):Integer; safecall; end; type TInitPluginFunc = function(const ACore: ICore): IPlugin; safecall; TDonePluginFunc = procedure; safecall; const SPluginInitFuncName = 'D211F00C19BD4BD1BEC90B1A763983E3'; SPluginDoneFuncName = SPluginInitFuncName + '_done'; SPluginExt = '.ext'; implementation end.
namespace Sugar; interface type Consts = public static class public const PI: Double = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679; const E: Double = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274; property MaxInteger: Integer read {$IF COOPER}Int32.MAX_VALUE{$ELSEIF ECHOES}Int32.MaxValue{$ELSEIF TOFFEE}rtl.INT32_MAX{$ENDIF}; property MinInteger: Integer read {$IF COOPER}Int32.MIN_VALUE{$ELSEIF ECHOES}Int32.MinValue{$ELSEIF TOFFEE}rtl.INT32_MIN{$ENDIF}; property MaxInt64: Int64 read {$IF COOPER}Int64.MAX_VALUE{$ELSEIF ECHOES}Int64.MaxValue{$ELSEIF TOFFEE}rtl.INT64_MAX{$ENDIF}; property MinInt64: Int64 read {$IF COOPER}Int64.MIN_VALUE{$ELSEIF ECHOES}Int64.MinValue{$ELSEIF TOFFEE}rtl.INT64_MIN{$ENDIF}; property MaxChar: Integer read $FFFF; property MinChar: Integer read 0; property MaxByte: Byte read $FF; property MinByte: Byte read 0; property MaxDouble: Double read {$IF COOPER}Double.MAX_VALUE{$ELSEIF ECHOES}Double.MaxValue{$ELSEIF TOFFEE}1.7976931348623157E+308{$ENDIF}; property MinDouble: Double read {$IF COOPER}-Double.MAX_VALUE{$ELSEIF ECHOES}Double.MinValue{$ELSEIF TOFFEE}-1.7976931348623157E+308{$ENDIF}; property PositiveInfinity: Double read {$IF COOPER}Double.POSITIVE_INFINITY{$ELSEIF ECHOES}Double.PositiveInfinity{$ELSEIF TOFFEE}INFINITY{$ENDIF}; property NegativeInfinity: Double read {$IF COOPER}Double.NEGATIVE_INFINITY{$ELSEIF ECHOES}Double.NegativeInfinity{$ELSEIF TOFFEE}-INFINITY{$ENDIF}; property NaN: Double read {$IF COOPER}Double.NaN{$ELSEIF ECHOES}Double.NaN{$ELSEIF TOFFEE}rtl.nan{$ENDIF}; property TrueString: not nullable String read "True"; property FalseString: not nullable String read "False"; method IsNaN(Value: Double): Boolean; method IsInfinity(Value: Double): Boolean; method IsPositiveInfinity(Value: Double): Boolean; method IsNegativeInfinity(Value: Double): Boolean; end; implementation class method Consts.IsNaN(Value: Double): Boolean; begin {$IF COOPER} exit Double.isNaN(Value); {$ELSEIF ECHOES} exit Double.IsNaN(Value); {$ELSEIF TOFFEE} exit __inline_isnand(Value) <> 0; {$ENDIF} end; class method Consts.IsInfinity(Value: Double): Boolean; begin {$IF COOPER} exit Double.isInfinite(Value); {$ELSEIF ECHOES} exit Double.IsInfinity(Value); {$ELSEIF TOFFEE} exit __inline_isinfd(Value) <> 0; {$ENDIF} end; class method Consts.IsNegativeInfinity(Value: Double): Boolean; begin {$IF COOPER} exit Value = NegativeInfinity; {$ELSEIF ECHOES} exit Double.IsNegativeInfinity(Value); {$ELSEIF TOFFEE} exit (Value = NegativeInfinity) and (not Consts.IsNaN(Value)); {$ENDIF} end; class method Consts.IsPositiveInfinity(Value: Double): Boolean; begin {$IF COOPER} exit Value = PositiveInfinity; {$ELSEIF ECHOES} exit Double.IsPositiveInfinity(Value); {$ELSEIF TOFFEE} exit (Value = PositiveInfinity) and (not Consts.IsNaN(Value)); {$ENDIF} end; end.
unit CompName; interface uses // VCL Windows, Messages, SysUtils, Classes, Consts, Controls, Forms, ShellAPI, ShlObj, ComObj, ActiveX, FileCtrl; function BrowseComputer(AParentWnd: HWND; var ComputerName: string; const DlgText: string; AHelpContext: THelpContext): Boolean; implementation function RemoveBackSlash(const DirName: string): string; begin Result := DirName; if (Length(Result) > 1) and (Result[Length(Result)] = '\') then begin if not ((Length(Result) = 3) and (UpCase(Result[1]) in ['A'..'Z']) and (Result[2] = ':')) then Delete(Result, Length(Result), 1); end; end; function DirExists(Name: string): Boolean; var Code: Integer; begin Code := GetFileAttributes(PChar(Name)); Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0); end; procedure FitRectToScreen(var Rect: TRect); var X, Y, Delta: Integer; begin X := GetSystemMetrics(SM_CXSCREEN); Y := GetSystemMetrics(SM_CYSCREEN); with Rect do begin if Right > X then begin Delta := Right - Left; Right := X; Left := Right - Delta; end; if Left < 0 then begin Delta := Right - Left; Left := 0; Right := Left + Delta; end; if Bottom > Y then begin Delta := Bottom - Top; Bottom := Y; Top := Bottom - Delta; end; if Top < 0 then begin Delta := Bottom - Top; Top := 0; Bottom := Top + Delta; end; end; end; procedure CenterWindow(Wnd: HWnd); var R: TRect; begin GetWindowRect(Wnd, R); R := Rect((GetSystemMetrics(SM_CXSCREEN) - R.Right + R.Left) div 2, (GetSystemMetrics(SM_CYSCREEN) - R.Bottom + R.Top) div 2, R.Right - R.Left, R.Bottom - R.Top); FitRectToScreen(R); SetWindowPos(Wnd, 0, R.Left, R.Top, 0, 0, SWP_NOACTIVATE or SWP_NOSIZE or SWP_NOZORDER); end; { TBrowseFolderDlg } type TBrowseKind = (bfFolders, bfComputers); TDialogPosition = (dpDefault, dpScreenCenter); TBrowseFolderDlg = class(TComponent) private FHandle: HWnd; FText: string; FParentWnd: HWND; FFolderName: string; FImageIndex: Integer; FDisplayName: string; FSelectedName: string; FDefWndProc: Pointer; FDesktopRoot: Boolean; FObjectInstance: Pointer; FBrowseKind: TBrowseKind; FPosition: TDialogPosition; FHelpContext: THelpContext; FOnInitialized: TNotifyEvent; FOnSelChanged: TNotifyEvent; procedure DoInitialized; procedure SetOkEnable(Value: Boolean); procedure SetSelPath(const Path: string); procedure DoSelChanged(Param: PItemIDList); procedure WMCommand(var Message: TMessage); message WM_COMMAND; procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY; protected procedure DefaultHandler(var Message); override; procedure WndProc(var Message: TMessage); virtual; function TaskModalDialog(var Info: TBrowseInfo): PItemIDList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Execute: Boolean; property Handle: HWnd read FHandle; property DisplayName: string read FDisplayName; property SelectedName: string read FSelectedName write FSelectedName; property ImageIndex: Integer read FImageIndex; published property BrowseKind: TBrowseKind read FBrowseKind write FBrowseKind default bfFolders; property DesktopRoot: Boolean read FDesktopRoot write FDesktopRoot default True; property DialogText: string read FText write FText; property FolderName: string read FFolderName write FFolderName; property HelpContext: THelpContext read FHelpContext write FHelpContext default 0; property Position: TDialogPosition read FPosition write FPosition default dpScreenCenter; property OnInitialized: TNotifyEvent read FOnInitialized write FOnInitialized; property OnSelChanged: TNotifyEvent read FOnSelChanged write FOnSelChanged; end; function ExplorerHook(Wnd: HWnd; Msg: UINT; LParam: LPARAM; Data: LPARAM): Integer; stdcall; begin Result := 0; if Msg = BFFM_INITIALIZED then begin if TBrowseFolderDlg(Data).Position = dpScreenCenter then CenterWindow(Wnd); TBrowseFolderDlg(Data).FHandle := Wnd; TBrowseFolderDlg(Data).FDefWndProc := Pointer(SetWindowLong(Wnd, GWL_WNDPROC, Longint(TBrowseFolderDlg(Data).FObjectInstance))); TBrowseFolderDlg(Data).DoInitialized; end else if Msg = BFFM_SELCHANGED then begin TBrowseFolderDlg(Data).FHandle := Wnd; TBrowseFolderDlg(Data).DoSelChanged(PItemIDList(LParam)); end; end; const HelpButtonId = $FFFF; constructor TBrowseFolderDlg.Create(AOwner: TComponent); begin inherited Create(AOwner); FObjectInstance := MakeObjectInstance(WndProc); FDesktopRoot := True; FBrowseKind := bfFolders; FPosition := dpScreenCenter; SetLength(FDisplayName, MAX_PATH); end; destructor TBrowseFolderDlg.Destroy; begin if FObjectInstance <> nil then FreeObjectInstance(FObjectInstance); inherited Destroy; end; procedure TBrowseFolderDlg.DoInitialized; const SBtn = 'BUTTON'; var BtnHandle, HelpBtn, BtnFont: THandle; BtnSize: TRect; begin if (FBrowseKind = bfComputers) or DirExists(FFolderName) then SetSelPath(FFolderName); if FHelpContext <> 0 then begin BtnHandle := FindWindowEx(FHandle, 0, SBtn, nil); if (BtnHandle <> 0) then begin GetWindowRect(BtnHandle, BtnSize); ScreenToClient(FHandle, BtnSize.TopLeft); ScreenToClient(FHandle, BtnSize.BottomRight); BtnFont := SendMessage(FHandle, WM_GETFONT, 0, 0); HelpBtn := CreateWindow(SBtn, PChar(SHelpButton), WS_CHILD or WS_CLIPSIBLINGS or WS_VISIBLE or BS_PUSHBUTTON or WS_TABSTOP, 12, BtnSize.Top, BtnSize.Right - BtnSize.Left, BtnSize.Bottom - BtnSize.Top, FHandle, HelpButtonId, HInstance, nil); if BtnFont <> 0 then SendMessage(HelpBtn, WM_SETFONT, BtnFont, MakeLParam(1, 0)); UpdateWindow(FHandle); end; end; if Assigned(FOnInitialized) then FOnInitialized(Self); end; procedure TBrowseFolderDlg.DoSelChanged(Param: PItemIDList); var Temp: array[0..MAX_PATH] of Char; begin if (FBrowseKind = bfComputers) then begin FSelectedName := DisplayName; end else begin if SHGetPathFromIDList(Param, Temp) then begin FSelectedName := StrPas(Temp); SetOkEnable(DirExists(FSelectedName)); end else begin FSelectedName := ''; SetOkEnable(False); end; end; if Assigned(FOnSelChanged) then FOnSelChanged(Self); end; procedure TBrowseFolderDlg.SetSelPath(const Path: string); begin if FHandle <> 0 then SendMessage(FHandle, BFFM_SETSELECTION, 1, Longint(PChar(Path))); end; procedure TBrowseFolderDlg.SetOkEnable(Value: Boolean); begin if FHandle <> 0 then SendMessage(FHandle, BFFM_ENABLEOK, 0, Ord(Value)); end; procedure TBrowseFolderDlg.DefaultHandler(var Message); begin if FHandle <> 0 then with TMessage(Message) do Result := CallWindowProc(FDefWndProc, FHandle, Msg, WParam, LParam) else inherited DefaultHandler(Message); end; procedure TBrowseFolderDlg.WndProc(var Message: TMessage); begin Dispatch(Message); end; procedure TBrowseFolderDlg.WMCommand(var Message: TMessage); begin if (Message.wParam = HelpButtonId) and (LongRec(Message.lParam).Hi = BN_CLICKED) and (FHelpContext <> 0) then begin Application.HelpContext(FHelpContext); end else inherited; end; procedure TBrowseFolderDlg.WMNCDestroy(var Message: TWMNCDestroy); begin inherited; FHandle := 0; end; function TBrowseFolderDlg.Execute: Boolean; var BrowseInfo: TBrowseInfo; ItemIDList: PItemIDList; Temp: array[0..MAX_PATH] of Char; begin if FDesktopRoot and (FBrowseKind = bfFolders) then BrowseInfo.pidlRoot := nil else begin if FBrowseKind = bfComputers then { root - Network } OleCheck(SHGetSpecialFolderLocation(0, CSIDL_NETWORK, BrowseInfo.pidlRoot)) else { root - MyComputer } OleCheck(SHGetSpecialFolderLocation(0, CSIDL_DRIVES, BrowseInfo.pidlRoot)); end; try SetLength(FDisplayName, MAX_PATH); with BrowseInfo do begin pszDisplayName := PChar(DisplayName); if DialogText <> '' then lpszTitle := PChar(DialogText) else lpszTitle := nil; if FBrowseKind = bfComputers then ulFlags := BIF_BROWSEFORCOMPUTER else ulFlags := BIF_RETURNONLYFSDIRS or BIF_RETURNFSANCESTORS; lpfn := ExplorerHook; lParam := Longint(Self); hWndOwner := FParentWnd; iImage := 0; end; ItemIDList := TaskModalDialog(BrowseInfo); Result := ItemIDList <> nil; if Result then try if FBrowseKind = bfFolders then begin Win32Check(SHGetPathFromIDList(ItemIDList, Temp)); FFolderName := RemoveBackSlash(StrPas(Temp)); end else begin FFolderName := DisplayName; end; FSelectedName := FFolderName; FImageIndex := BrowseInfo.iImage; finally CoTaskMemFree(ItemIDList); end; finally if BrowseInfo.pidlRoot <> nil then CoTaskMemFree(BrowseInfo.pidlRoot); end; end; function TBrowseFolderDlg.TaskModalDialog(var Info: TBrowseInfo): PItemIDList; begin try Result := SHBrowseForFolder(Info); finally FHandle := 0; FDefWndProc := nil; end; end; function BrowseComputer(AParentWnd: HWND; var ComputerName: string; const DlgText: string; AHelpContext: THelpContext): Boolean; begin with TBrowseFolderDlg.Create(Application) do try BrowseKind := bfComputers; DialogText := DlgText; FolderName := ComputerName; HelpContext := AHelpContext; FParentWnd := AParentWnd; Result := Execute; if Result then ComputerName := FolderName; finally Free; end; end; end.
unit daouib; interface uses Interfaces.base, Rtti, attributes, system.SysUtils, System.Classes, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; type TDaoUib = class(TInterfacedObject, IDaoBase) private FDatabase: TFDConnection; FTransaction: TFDTransaction; procedure ConfigParams(AQuery: TFDQuery; AProp: TRttiProperty; AField: string; ATable: TTable); public Qry: TFDQuery; constructor Create(ADatabase: TFDConnection; ATransaction: TFDTransaction); procedure CloseQuery; function ExecuteQuery: Integer; function Insert(ATabela: TTable): Integer; function Save(ATabela: TTable): Integer; function Delete(ATable: TTable): Integer; function InTransaction: Boolean; procedure StartTransaction; procedure Commit; procedure RollBack; end; implementation uses Vcl.Forms; { TDaoUib } procedure TDaoUib.CloseQuery; begin Qry.Close; Qry.SQL.Clear; end; procedure TDaoUib.Commit; begin FTransaction.Commit; end; procedure TDaoUib.ConfigParams(AQuery: TFDQuery; AProp: TRttiProperty; AField: string; ATable: TTable); begin with AQuery do begin case AProp.PropertyType.TypeKind of tkInt64, tkInteger: begin Params.ParamByName(AField).Value := AProp.GetValue(ATable).AsInteger; end; tkChar, tkString, tkUString: begin Params.ParamByName(AField).Value := AProp.GetValue(ATable).AsString; end; tkFloat: begin Params.ParamByName(AField).Value := AProp.GetValue(ATable).AsCurrency; end; tkVariant: begin Params.ParamByName(AField).Value := AProp.GetValue(ATable).AsVariant; end; else raise Exception.Create('Tipo de campo não conhecido: ' + AProp.PropertyType.ToString); end; end; end; constructor TDaoUib.Create(ADatabase: TFDConnection; ATransaction: TFDTransaction); begin if not Assigned(ADatabase) then raise Exception.Create('Database não informado!'); if not Assigned(ATransaction) then raise Exception.Create('Transaction não informado!'); FDatabase := ADatabase; FTransaction := ATransaction; Qry := TFDQuery.Create(Application); Qry.Connection := FDatabase; Qry.Transaction := FTransaction; end; function TDaoUib.Delete(ATable: TTable): Integer; var Comando: TFuncReflection; begin //crio uma variável do tipo TFuncReflexao - um método anônimo Comando := function(ACampos: TFieldAnonymous): Integer var Field: string; PropRtti: TRttiProperty; begin with Qry do begin close; SQL.Clear; sql.Add('Delete from ' + ACampos.NameTable); sql.Add('Where'); //percorrer todos os campos da chave primária ACampos.Sep := ''; for Field in ACampos.PKs do begin sql.Add(ACampos.Sep+ Field + '= :' + Field); ACampos.Sep := ' and '; // setando os parâmetros for PropRtti in ACampos.TipoRtti.GetProperties do if CompareText(PropRtti.Name, Field) = 0 then begin ConfigParams(Qry, PropRtti, Field, ATable); end; end; //executa delete Prepare(); ExecSQL; Result := ExecuteQuery; end; end; //reflection da tabela e execução da query preparada acima. Result := ReflectionSQL(ATable, Comando); end; function TDaoUib.ExecuteQuery: Integer; begin Qry.Prepare(); Qry.ExecSQL; Result := Qry.RowsAffected; end; function TDaoUib.Insert(ATabela: TTable): Integer; begin end; function TDaoUib.InTransaction: Boolean; begin Result := FDatabase.InTransaction; end; procedure TDaoUib.RollBack; begin FTransaction.RollBack; end; function TDaoUib.Save(ATabela: TTable): Integer; begin end; procedure TDaoUib.StartTransaction; begin FTransaction.StartTransaction; end; end.
unit dcEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DataController, dbctrls, db, ffsException, AdvEdit, FFSTypes, ffsutils; type TdcEditChar = (dceLetters, dceNumbers, dceDash, dceSpace, dceAllOther); TdcEditChars = set of TdcEditChar; TdcEdit = class(TAdvEdit) private Fclearing: boolean; FEditChars: TdcEditChars; FLetterFilter: string; FMaskFormat: TMaskFormat; FOnF3: TNotifyEvent; procedure Setclearing(const Value: boolean); function GetDatabufIndex: integer; procedure SetDataBufIndex(const Value: integer); procedure SetEditChars(const Value: TdcEditChars); procedure SetLetterFilter(const Value: string); procedure SetMaskFormat(const Value: TMaskFormat); procedure SetOnF3(const Value: TNotifyEvent); private { Private declarations } frequired : boolean; protected { Protected declarations } OldReadonly : boolean; fTranData : String; fdcLink : TdcLink; // std data awareness function GetDataField:string; procedure SetDataField(value:string); // data controller function GetDataController:TDataController; procedure SetDataController(value:TDataController); function GetDataSource:TDataSource; procedure SetDataSource(value:TDataSource); procedure ReadData(sender:TObject); virtual; procedure WriteData(sender:TObject); virtual; procedure ClearData(sender:TObject); virtual; procedure Change; override; procedure DoEnter;override; procedure DoExit;override; procedure KeyPress(var Key: Char); override; property clearing:boolean read Fclearing write Setclearing; procedure SetParent(AParent: TWinControl); override; procedure Loaded;override; procedure FormatEntry;virtual; procedure KeyDown(var Key: Word; Shift: TShiftState);override; public { Public declarations } constructor Create(AOwner:Tcomponent);override; destructor Destroy;override; property TranData : String read fTranData; published property EditChars:TdcEditChars read FEditChars write SetEditChars; property Required : boolean read fRequired write fRequired; property LetterFilter:string read FLetterFilter write SetLetterFilter; property DataController : TDataController read GetDataController write setDataController; property DataField : String read GetDataField write SetDataField; property DataSource : TDataSource read getDataSource write SetDataSource; property DatabufIndex:integer read GetDatabufIndex write SetDataBufIndex; property MaskFormat:TMaskFormat read FMaskFormat write SetMaskFormat; property OnF3:TNotifyEvent read FOnF3 write SetOnF3; end; procedure Register; implementation constructor TdcEdit.Create(AOwner:Tcomponent); begin inherited; fdclink := tdclink.create(self); with fdcLink do begin OnReadData := ReadData; OnWriteData := WriteData; OnClearData := ClearData; end; FEditChars := [dceLetters, dceNumbers, dceSpace, dceAllOther]; // default value // font.color := FFSColor[fcsDataText]; FocusColor := FFSColor[fcsActiveEntryField]; EditType := etUppercase; ShowModified := true; end; destructor TdcEdit.Destroy; begin fdclink.Free; inherited; end; function TdcEdit.getdatasource; begin result := fdclink.DataSource; end; procedure TdcEdit.SetDatasource(value:TDataSource); begin // intentionally blank end; procedure TdcEdit.SetDataController(value:TDataController); begin fdcLink.datacontroller := value; end; function TdcEdit.GetDataController:TDataController; begin result := fdcLink.DataController; end; function TdcEdit.GetDataField:string; begin result := fdcLink.FieldName; end; procedure TdcEdit.SetDataField(value:string); begin fdcLink.FieldName := value; end; procedure TdcEdit.ReadData; begin if not assigned(fdclink.DataController) then exit; if (databufindex = 0) and (DataField <> '') then begin case edittype of etString, etUpperCase, etMixedCase, etLowerCase, etPassword : if maskFormat = mtNone then Text := fdclink.DataController.dcStrings.StrVal[DataField] else text := AddMask(fdclink.DataController.dcStrings.StrVal[DataField], maskFormat); etNumeric : IntValue := fdcLink.DataController.dcStrings.IntVal[DataField]; etFloat : FloatValue := fdcLink.DataController.dcStrings.FloatVal[DataField]; etMoney : FloatValue := fdcLink.DataController.dcStrings.CurrVal[DataField]; end; end else begin if not assigned(fdclink.datacontroller.databuf) then exit; case edittype of etString, etUppercase, etMixedCase, etLowerCase, etPassword : if maskFormat = mtNone then Text := fdclink.datacontroller.databuf.AsString[DataBufIndex] else text := AddMask(fdclink.datacontroller.databuf.AsString[DataBufIndex], maskFormat); etNumeric : IntValue := fdclink.datacontroller.databuf.AsInt[DataBufIndex]; etFloat, etMoney : FloatValue := fdclink.datacontroller.databuf.Ascurrency[DataBufIndex]; end; end; Modified := false; end; procedure TdcEdit.ClearData; begin clearing := true; Text := ''; clearing := false; end; procedure TdcEdit.WriteData; begin if ReadOnly then exit; if not assigned(fdclink.DataController) then exit; if (databufindex = 0) and (DataField <> '') then begin case edittype of etString, etUpperCase, etMixedCase, etLowerCase, etPassword : if maskFormat = mtNone then fdclink.DataController.dcStrings.StrVal[DataField] := Text else fdclink.DataController.dcStrings.StrVal[DataField] := StripMask(Text, MaskFormat); etNumeric : fdcLink.DataController.dcStrings.IntVal[DataField] := IntValue; etFloat : fdcLink.DataController.dcStrings.FloatVal[DataField] := FloatValue; etMoney : fdcLink.DataController.dcStrings.CurrVal[DataField] := FloatValue; end; end else begin if not assigned(fdclink.datacontroller.databuf) then exit; case edittype of etString, etUppercase, etMixedCase, etLowerCase, etPassword : if MaskFormat = mtNone then fdclink.datacontroller.databuf.asString[DataBufIndex] := Text else begin if self.Focused then text := AddMask(Text, maskFormat); fdclink.datacontroller.databuf.asString[DataBufIndex] := StripMask(Text, MaskFormat); end; etNumeric : fdclink.datacontroller.databuf.AsInt[DataBufIndex] := IntValue; etFloat, etMoney : fdclink.datacontroller.databuf.Ascurrency[DataBufIndex] := FloatValue; end; end; end; procedure Register; begin RegisterComponents('FFS Data Entry', [TdcEdit]); end; procedure TdcEdit.DoEnter; begin inherited; OldReadOnly := ReadOnly; if assigned(FDCLink.DataController) then begin if DataController.ReadOnly then ReadOnly := true; end; if not readonly then begin if (EditType in [etString, etUppercase, etMixedCase, etLowerCase, etPassword]) and (maskFormat > mtNone) then text := StripMask(Text, maskFormat); end; end; procedure TdcEdit.DoExit; begin if not readonly then begin if (EditType in [etString, etUppercase, etMixedCase, etLowerCase, etPassword]) and (maskFormat > mtNone) then text := AddMask(Text, maskFormat); end; ReadOnly := OldReadOnly; inherited; end; procedure TdcEdit.Setclearing(const Value: boolean); begin Fclearing := Value; end; function TdcEdit.GetDatabufIndex: integer; begin result := 0; if assigned(fdclink.Datacontroller) then if assigned(fdclink.datacontroller.databuf) then result := fdclink.datacontroller.databuf.FieldNameToIndex(fdclink.FieldName); end; procedure TdcEdit.SetDataBufIndex(const Value: integer); begin // intentionally empty end; procedure TdcEdit.SetEditChars(const Value: TdcEditChars); begin FEditChars := Value; end; procedure TdcEdit.KeyPress(var Key: Char); var echar : TdcEditChar; begin if (Key > #31) then begin if letterfilter > '' then begin if pos(key,letterfilter) = 0 then key := #0; end; if key > #0 then begin echar := dceAllOther; case key of 'A'..'Z', 'a'..'z' : echar := dceLetters; '0'..'9' : echar := dceNumbers; '-' : echar := dceDash; ' ' : echar := dceSpace; end; if not (echar in EditChars) then key := #0; end; end; inherited KeyPress(Key); end; procedure TdcEdit.SetLetterFilter(const Value: string); begin FLetterFilter := Value; end; procedure TdcEdit.Change; begin if assigned(fdclink.datacontroller) then if not clearing then fdclink.BeginEdit; inherited; end; procedure TdcEdit.SetParent(AParent: TWinControl); begin inherited; if AParent <> nil then Flat := true; end; procedure TdcEdit.Loaded; begin inherited; font.color := FFSColor[fcsDataText]; FocusColor := FFSColor[fcsActiveEntryField]; //VG 080617: TODO These members are private in TAdvEdit. Check if setting them is really needed // Calling Init sets those members based on the Color and Font.Color, so it can be used as a workaround // ffontcolor := font.color; // FNormalColor := FFSColor[fcsDatabackground]; height := 16; // if EditType in [etString, etLowerCase, etMixedCase] then EditType := etUppercase; end; procedure TdcEdit.FormatEntry; begin // does nothing now. end; procedure TdcEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if (shift = []) and (key in [VK_ESCAPE, VK_RETURN]) then begin FormatEntry; GetParentForm(Self).Perform(CM_DIALOGKEY, WParam(Key), Word(Shift)); if Key = VK_RETURN then begin inherited KeyDown(key,shift); Key := 0; Exit; end; end; inherited; if (key = VK_F3) and (Shift = []) then begin if assigned(FOnF3) then begin key := 0; OnF3(self); end; end; end; procedure TdcEdit.SetMaskFormat(const Value: TMaskFormat); begin FMaskFormat := Value; end; procedure TdcEdit.SetOnF3(const Value: TNotifyEvent); begin FOnF3 := Value; end; end.
{$I OVC.INC} {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} {$IFNDEF Win32} {$G+} {286 Instructions} {$N+} {Numeric Coprocessor} {$C MOVEABLE,DEMANDLOAD,DISCARDABLE} {$ENDIF} {*********************************************************} {* OVCMISC.PAS 2.17 *} {* Copyright (c) 1995-98 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} unit OvcMisc; {-Miscellaneous functions and procedures} interface uses {$IFDEF Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Classes, Controls, Forms, Graphics, Messages, SysUtils, OvcData; function CompStruct(const S1, S2; Size : Cardinal) : Integer; {-Compare two fixed size structures} function LoadOvcBaseBitmap(lpBitmapName : PAnsiChar) : HBITMAP; {-load a bitmap and return the handle} procedure FixRealPrim(P : PAnsiChar; DC : AnsiChar); {!!.16} {-get a PChar string representing a real ready for Val()} function GetLeftButton: Byte; {-return the mapped left button} function GetNextDlgItem(Ctrl : hWnd) : hWnd; {-get handle of next control in the same form} function GetShiftFlags : Byte; {-get current shift flags, the high order bit is set if the key is down} function CreateRotatedFont(F : TFont; Angle : Integer) : hFont; {-create a rotated font based on the font object F} {!!.01} {revised} function GetTopTextMargin(Font : TFont; BorderStyle : TBorderStyle; Height : Integer; Ctl3D : Boolean) : Integer; {-return the pixel top margin size} function PtrDiff(const P1, P2) : Word; {!!.10} {-return the difference between P1 and P2} procedure PtrInc(var P; Delta : Word); {!!.10} {-increase P by Delta} procedure PtrDec(var P; Delta : Word); {!!.10} {-decrease P by Delta} implementation uses {$IFDEF Version3} {this circular reference causes problems with Delphi 1} OvcBase, {and is only really needed for version 3 or later. } {$ENDIF} OvcStr; {$IFDEF Win32} function CompStruct(const S1, S2; Size : Cardinal) : Integer; register; {-compare two fixed size structures} asm push esi push edi mov esi, eax {pointer to S1} mov edi, edx {pointer to S2} xor eax, eax {eax holds temporary result (Equal)} or ecx, ecx {size is already in ecx} jz @@CSDone {make sure size isn't zero} cld {go forward} repe cmpsb {compare until no match or ecx = 0} je @@CSDone {if equal, result is already in eax} inc eax {prepare for greater} ja @@CSDone {S1 greater? return +1} mov eax, -1 {else S1 less, return -1} @@CSDone: pop edi pop esi end; {$ELSE} function CompStruct(const S1, S2; Size : Cardinal) : Integer; assembler; {-compare two fixed size structures} asm mov dx,ds {save ds} xor ax,ax {AX holds temporary result (Equal)} mov cx,Size {size in cx} jcxz @@CSDone {make sure size isn't zero} les di,S2 {es:di points to S2} lds si,S1 {ds:si points to S1} cld {go forward} repe cmpsb {compare until no match or cx = 0} je @@CSDone {if equal, result ready based on length} inc ax {prepare for greater} ja @@CSDone {S1 greater? return +1} mov ax,-1 {else S1 less, return -1} @@CSDone: mov ds,dx {restore ds} end; {$ENDIF} function LoadOvcBaseBitmap(lpBitmapName : PAnsiChar) : HBITMAP; begin {$IFDEF Version3} Result := LoadBitmapA(FindClassHInstance(TOvcBase), lpBitmapName); {$ELSE} Result := LoadBitmap(HInstance, lpBitmapName); {$ENDIF} end; {!!.16} procedure FixRealPrim(P : PAnsiChar; DC : AnsiChar); {-Get a string representing a real ready for Val()} var DotPos : Cardinal; EPos : Cardinal; Len : Word; Found : Boolean; EFound : Boolean; begin TrimAllSpacesPChar(P); Len := StrLen(P); if Len > 0 then begin if P[Len-1] = DC then begin Dec(Len); P[Len] := #0; TrimAllSpacesPChar(P); {!!.14} end; {Val doesn't accept alternate decimal point chars} Found := StrChPos(P, DC, DotPos); if Found and (DotPos > 0) then P[DotPos] := '.'; {replace with '.'} if Found then begin {check for 'nnnn.'} if DotPos + 1 = Len then begin P[Len] := '0'; Inc(Len); P[Len] := #0; end; {check for '.nnnn'} if DotPos = 0 then begin StrChInsertPrim(P, '0', 0); Inc(Len); Inc(DotPos); end; {check for '-.nnnn'} if (Len > 1) and (P^ = '-') and (DotPos = 1) then begin StrChInsertPrim(P, '0', 1); Inc(DotPos); end; end; {fix up numbers with exponents} EFound := StrChPos(P, 'E', EPos); if EFound and (EPos > 0) then begin if not Found then begin StrChInsertPrim(P, '.', EPos); DotPos := EPos; Inc(EPos); end; if EPos-DotPos < 12 then StrStInsertPrim(P, '00000', EPos); end; {remove blanks before and after '.' } if Found then begin while (DotPos > 0) and (P[DotPos-1] = ' ') do begin StrStDeletePrim(P, DotPos-1, 1); Dec(DotPos); end; while P[DotPos+1] = ' ' do StrStDeletePrim(P, DotPos+1, 1); end; end else begin {empty string = '0'} P[0] := '0'; P[1] := #0; end; end; function GetLeftButton: Byte; const RLButton : array[Boolean] of Word = (VK_LBUTTON, VK_RBUTTON); begin Result := RLButton[GetSystemMetrics(SM_SWAPBUTTON) <> 0]; end; function GetNextDlgItem(Ctrl : hWnd) : hWnd; {-Get handle of next control in the same form} begin {asking for previous returns next} Result := GetNextWindow(Ctrl, GW_HWNDPREV); if Result = 0 then begin {asking for last returns first} Result := GetWindow(Ctrl, GW_HWNDLAST); if Result = 0 then Result := Ctrl; end; end; function GetShiftFlags : Byte; {-get current shift flags, the high order bit is set if the key is down} begin Result := (Ord(GetKeyState(VK_CONTROL) < 0) * ss_Ctrl) + (Ord(GetKeyState(VK_SHIFT ) < 0) * ss_Shift) + (Ord(GetKeyState(VK_ALT ) < 0) * ss_Alt); end; function CreateRotatedFont(F : TFont; Angle : Integer) : hFont; {-create a rotated font based on the font object F} var LF : TLogFont; begin FillChar(LF, SizeOf(LF), #0); with LF do begin lfHeight := F.Height; lfWidth := 0; lfEscapement := Angle*10; lfOrientation := 0; if fsBold in F.Style then lfWeight := FW_BOLD else lfWeight := FW_NORMAL; lfItalic := Byte(fsItalic in F.Style); lfUnderline := Byte(fsUnderline in F.Style); lfStrikeOut := Byte(fsStrikeOut in F.Style); lfCharSet := F.CharSet; //DEFAULT_CHARSET; StrPCopy(lfFaceName, F.Name); lfQuality := DEFAULT_QUALITY; {everything else as default} lfOutPrecision := OUT_DEFAULT_PRECIS; lfClipPrecision := CLIP_DEFAULT_PRECIS; case F.Pitch of fpVariable : lfPitchAndFamily := VARIABLE_PITCH; fpFixed : lfPitchAndFamily := FIXED_PITCH; else lfPitchAndFamily := DEFAULT_PITCH; end; end; Result := CreateFontIndirect(LF); end; {!!.01} {revised} function GetTopTextMargin(Font : TFont; BorderStyle : TBorderStyle; Height : Integer; Ctl3D : Boolean) : Integer; {-return the pixel top margin size} var I : Integer; DC : hDC; SaveFont : hFont; Metrics : TTextMetric; SysMetrics : TTextMetric; begin DC := GetDC(0); try GetTextMetrics(DC, SysMetrics); SaveFont := SelectObject(DC, Font.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, SaveFont); finally ReleaseDC(0, DC); end; I := SysMetrics.tmHeight; if I > Metrics.tmHeight then I := Metrics.tmHeight; if NewStyleControls then begin {$IFDEF Win32} if BorderStyle = bsNone then begin Result := 0; if I >= Height-2 then Result := (Height-I-2) div 2 - Ord(Odd(Height-I)); end else if Ctl3D then begin Result := 1; if I >= Height-4 then Result := (Height-I-4) div 2 - 1; end else begin Result := 1; if I >= Height-4 then Result := (Height-I-4) div 2 - Ord(Odd(Height-I)); end; {$ELSE} if BorderStyle = bsNone then begin Result := 0; if I >= Height then Result := (Height-I) div 2 - 1; end else if Ctl3D then begin Result := 1; if I >= Height-2 then Result := (Height-2-I) div 2 - 1; end else begin Result := 2; if I >= Height-4 then Result := (Height-4-I) div 2; end; {$ENDIF} end else begin { Result := (Height-I-1) div 2;} {!!.12} Result := (Height-Metrics.tmHeight-1) div 2; {!!.12} if I > Height-2 then begin Dec(Result, 2); if BorderStyle = bsNone then Inc(Result, 1); end; end; end; {!!.10} {$IFDEF Win32} function PtrDiff(const P1, P2) : Word; {-return the difference between P1 and P2} begin {P1 and P2 are assumed to point within the same buffer} Result := PAnsiChar(P1) - PAnsiChar(P2); end; {$ELSE} function PtrDiff(const P1, P2) : Word; {-return the difference between P1 and P2} begin Result := Word(P1) - Word(P2); end; {$ENDIF} {!!.10} {$IFDEF Win32} procedure PtrInc(var P; Delta : Word); {-increase P by Delta} begin Inc(PAnsiChar(P), Delta); end; {$ELSE} procedure PtrInc(var P; Delta : Word); {-increase P by Delta} var PO : Word absolute P; begin Inc(PO, Delta); end; {$ENDIF} {!!.10} {$IFDEF Win32} procedure PtrDec(var P; Delta : Word); {-increase P by Delta} begin Dec(PAnsiChar(P), Delta); end; {$ELSE} procedure PtrDec(var P; Delta : Word); {-increase P by Delta} var PO : Word absolute P; begin Dec(PO, Delta); end; {$ENDIF} end.
{ Functions for legacy Delphi versions. Copyright (C) 2006, 2007 Kryvich, Belarusian Linguistic Software team. } {$include version.inc} unit uLegacyCode; interface uses Windows, Classes, SysUtils; {$ifdef D5} const sLineBreak = #13#10; function TryStrToInt(const S: string; out Value: Integer): Boolean; function AnsiEndsText(const ASubText, AText: string): Boolean; function Utf8Decode(const S: String): WideString; {$endif} {$ifdef D6} const CP_THREAD_ACP = 3; // current thread's ANSI code page procedure My_WStrFromStr(const Source: string; var Dest: WideString; CodePage: LongWord); function TStringsGetValueFromIndex(Strings: TStrings; Index: Integer): string; {$endif} {$ifdef D7} // Set a codepage for Wide <--> ANSI convertion operations procedure SetMultiByteConversionCodePage(cp: UINT); // Widestring replacement for StringReplace function WideStringReplace(const S, OldPattern, NewPattern: Widestring; Flags: TReplaceFlags): Widestring; {$endif} implementation {$ifdef D5} function WideUpperCase(const S: WideString): WideString; var Len: Integer; begin Len := Length(S); SetString(Result, PWideChar(S), Len); if Len > 0 then CharUpperBuffW(Pointer(Result), Len); end; function TryStrToInt(const S: string; out Value: Integer): Boolean; var E: Integer; begin Val(S, Value, E); Result := E = 0; end; function AnsiEndsText(const ASubText, AText: string): Boolean; var SubTextLocation: Integer; begin SubTextLocation := Length(AText) - Length(ASubText) + 1; if (SubTextLocation > 0) and (ASubText <> '') and (ByteType(AText, SubTextLocation) <> mbTrailByte) then Result := AnsiStrIComp(Pointer(ASubText), Pointer(@AText[SubTextLocation])) = 0 else Result := False; end; function Utf8Decode(const S: String): WideString; begin My_WStrFromStr(S, Result, 65001); end; {$endif} {$ifdef D6} procedure My_WStrFromStr(const Source: string; var Dest: WideString; CodePage: LongWord); var SourLen, DestLen: Integer; begin SourLen := length(Source); if SourLen <= 0 then begin Dest := ''; Exit; end; DestLen := MultiByteToWideChar(CodePage, 0, @Source[1], SourLen, Nil, 0); SetLength(Dest, DestLen); MultiByteToWideChar(CodePage, 0, @Source[1], SourLen, @Dest[1], DestLen); end; function TStringsGetValueFromIndex(Strings: TStrings; Index: Integer): string; var s: string; i: integer; begin if Index >= 0 then begin s := Strings[Index]; i := pos('=', s); if i <= 0 then i := MaxInt; Result := Copy(s, i+1, MaxInt) end else Result := ''; end; {$endif} {$ifdef D7} {$ifdef D6} procedure SetMultiByteConversionCodePage(cp: UINT); begin // Do nothing... end; {$else} // Set a codepage for Wide <--> ANSI convertion operations procedure SetMultiByteConversionCodePage(cp: UINT); var DefUserCP: ^integer; begin DefUserCP := pointer(integer(@ModuleUnloadList) + $2588); DefUserCP^ := cp; end; {$endif} // Widestring replacement for StringReplace function WideStringReplace(const S, OldPattern, NewPattern: Widestring; Flags: TReplaceFlags): Widestring; var SearchStr, Patt, NewStr: Widestring; Offset: Integer; begin if rfIgnoreCase in Flags then begin SearchStr := WideUpperCase(S); Patt := WideUpperCase(OldPattern); end else begin SearchStr := S; Patt := OldPattern; end; NewStr := S; Result := ''; while SearchStr <> '' do begin Offset := pos(Patt, SearchStr); if Offset = 0 then begin Result := Result + NewStr; break; end; Result := Result + copy(NewStr, 1, Offset - 1) + NewPattern; delete(NewStr, 1, Offset+length(OldPattern)-1); if not (rfReplaceAll in Flags) then begin Result := Result+NewStr; break; end; delete(SearchStr, 1, Offset+length(Patt)-1); end; end; {$endif} end.
unit pinballaction_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,ay_8910,rom_engine, pal_engine,sound_engine,timer_engine; function iniciar_pinballaction:boolean; const pinballaction_rom:array[0..2] of tipo_roms=( (n:'b-p7.bin';l:$4000;p:0;crc:$8d6dcaae),(n:'b-n7.bin';l:$4000;p:$4000;crc:$d54d5402), (n:'b-l7.bin';l:$2000;p:$8000;crc:$e7412d68)); pinballaction_sound:tipo_roms=(n:'a-e3.bin';l:$2000;p:0;crc:$0e53a91f); pinballaction_chars:array[0..2] of tipo_roms=( (n:'a-s6.bin';l:$2000;p:0;crc:$9a74a8e1),(n:'a-s7.bin';l:$2000;p:$2000;crc:$5ca6ad3c), (n:'a-s8.bin';l:$2000;p:$4000;crc:$9f00b757)); pinballaction_sprites:array[0..2] of tipo_roms=( (n:'b-c7.bin';l:$2000;p:0;crc:$d1795ef5),(n:'b-d7.bin';l:$2000;p:$2000;crc:$f28df203), (n:'b-f7.bin';l:$2000;p:$4000;crc:$af6e9817)); pinballaction_tiles:array[0..3] of tipo_roms=( (n:'a-j5.bin';l:$4000;p:0;crc:$21efe866),(n:'a-j6.bin';l:$4000;p:$4000;crc:$7f984c80), (n:'a-j7.bin';l:$4000;p:$8000;crc:$df69e51b),(n:'a-j8.bin';l:$4000;p:$c000;crc:$0094cb8b)); //DIP pinballaction_dipa:array [0..5] of def_dip=( (mask:$3;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'1C 1C'),(dip_val:$1;dip_name:'1C 2C'),(dip_val:$2;dip_name:'1C 3C'),(dip_val:$3;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coin A';number:4;dip:((dip_val:$4;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$c;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Lives';number:4;dip:((dip_val:$30;dip_name:'2'),(dip_val:$0;dip_name:'3'),(dip_val:$10;dip_name:'4'),(dip_val:$20;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Cabinet';number:2;dip:((dip_val:$40;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); pinballaction_dipb:array [0..4] of def_dip=( (mask:$7;name:'Bonus Life';number:8;dip:((dip_val:$1;dip_name:'70k 200k 1000k'),(dip_val:$4;dip_name:'100k 300k 1000k'),(dip_val:$0;dip_name:'70k 200k'),(dip_val:$3;dip_name:'100k 300k'),(dip_val:$6;dip_name:'200k 1000k'),(dip_val:$2;dip_name:'100k'),(dip_val:$5;dip_name:'200k'),(dip_val:$7;dip_name:'None'),(),(),(),(),(),(),(),())), (mask:$8;name:'Extra';number:2;dip:((dip_val:$8;dip_name:'Hard'),(dip_val:$0;dip_name:'Easy'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Flippers';number:4;dip:((dip_val:$0;dip_name:'Easy'),(dip_val:$10;dip_name:'Medium'),(dip_val:$20;dip_name:'Hard'),(dip_val:$30;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Difficulty (Outlanes)';number:4;dip:((dip_val:$0;dip_name:'Easy'),(dip_val:$40;dip_name:'Medium'),(dip_val:$80;dip_name:'Hard'),(dip_val:$c0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),()); var sound_latch,scroll_y:byte; nmi_mask:boolean; implementation procedure update_video_pinballaction; var f,color,nchar,x,y:word; atrib,atrib2:byte; begin //background for f:=0 to $3ff do begin atrib:=memoria[$dc00+f]; color:=atrib and $7; if (gfx[1].buffer[f] or buffer_color[color+$10]) then begin x:=31-(f div 32); y:=f mod 32; nchar:=memoria[$d800+f]+$10*(atrib and $70); put_gfx_flip(x*8,y*8,nchar,(color shl 4)+128,1,1,(atrib and $80)<>0,false); gfx[1].buffer[f]:=false; end; //chars atrib:=memoria[$d400+f]; color:=atrib and $f; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=31-(f div 32); y:=f mod 32; nchar:=memoria[$d000+f]+$10*(atrib and $30); put_gfx_trans_flip(x*8,y*8,nchar,color shl 3,2,0,(atrib and $80)<>0,(atrib and $40)<>0); gfx[0].buffer[f]:=false; end; end; scroll__y(1,3,scroll_y); //Sprites for f:=$1f downto 0 do begin //Si el siguiente es doble no lo pongo if ((f>0) and ((memoria[($e000+(f*4))-4] and $80)<>0)) then continue; atrib:=memoria[$e000+(f*4)]; atrib2:=memoria[$e001+(f*4)]; y:=memoria[$e003+(f*4)]; x:=memoria[$e002+(f*4)]; color:=(atrib2 and $f) shl 3; if (atrib and $80)<>0 then begin nchar:=3; atrib:=atrib and $1f; end else begin nchar:=2; end; put_gfx_sprite(atrib,color,(atrib2 and $40)<>0,(atrib2 and $80)<>0,nchar); actualiza_gfx_sprite(x,y,3,nchar); end; scroll__y(2,3,scroll_y); actualiza_trozo_final(16,0,224,256,3); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_pinballaction; begin if event.arcade then begin //Player 1 if arcade_input.but1[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.but3[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); //Player 2 if arcade_input.but1[1] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.but3[1] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); //System if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or 1) else marcade.in2:=(marcade.in2 and $fe); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or 2) else marcade.in2:=(marcade.in2 and $fd); if arcade_input.start[0] then marcade.in2:=(marcade.in2 or 4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.start[1] then marcade.in2:=(marcade.in2 or 8) else marcade.in2:=(marcade.in2 and $f7); end; end; procedure pinballaction_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_s:=z80_1.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //CPU 1 z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //CPU Sound z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; if f=240 then begin if nmi_mask then z80_0.change_nmi(PULSE_LINE); update_video_pinballaction; end; end; eventos_pinballaction; video_sync; end; end; function pinballaction_getbyte(direccion:word):byte; begin case direccion of $0..$e07f:pinballaction_getbyte:=memoria[direccion]; $e400..$e5ff:pinballaction_getbyte:=buffer_paleta[direccion and $1ff]; $e600:pinballaction_getbyte:=marcade.in0; //p1 $e601:pinballaction_getbyte:=marcade.in1; //p2 $e602:pinballaction_getbyte:=marcade.in2; //system $e604:pinballaction_getbyte:=marcade.dswa; $e605:pinballaction_getbyte:=marcade.dswb; end; end; procedure pinballaction_putbyte(direccion:word;valor:byte); procedure cambiar_color(dir:word); var tmp_color:byte; color:tcolor; begin tmp_color:=buffer_paleta[dir+1]; color.b:=pal4bit(tmp_color); tmp_color:=buffer_paleta[dir]; color.g:=pal4bit(tmp_color shr 4); color.r:=pal4bit(tmp_color); dir:=dir shr 1; set_pal_color(color,dir); case dir of 0..127:buffer_color[dir shr 3]:=true; 128..255:buffer_color[((dir shr 4) and $7)+$10]:=true; end; end; begin case direccion of 0..$7fff:; $8000..$cfff,$e000..$e07f:memoria[direccion]:=valor; $d000..$d7ff:if memoria[direccion]<>valor then begin //chars memoria[direccion]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $d800..$dfff:if memoria[direccion]<>valor then begin //tiles memoria[direccion]:=valor; gfx[1].buffer[direccion and $3ff]:=true; end; $e400..$e5ff:if buffer_paleta[direccion and $1ff]<>valor then begin buffer_paleta[direccion and $1ff]:=valor; cambiar_color(direccion and $1fe); end; $e600:nmi_mask:=(valor and $1)<>0; $e604:main_screen.flip_main_screen:=(valor and 1)<>0; $e606:scroll_y:=valor-3; $e800:begin sound_latch:=valor; z80_1.change_irq(HOLD_LINE); z80_1.im2_lo:=0; end; end; end; function snd_getbyte(direccion:word):byte; begin case direccion of $0..$1fff,$4000..$47ff:snd_getbyte:=mem_snd[direccion]; $8000:snd_getbyte:=sound_latch; end; end; procedure snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$1fff:; $4000..$47ff:mem_snd[direccion]:=valor; end; end; procedure snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $10:ay8910_0.Control(valor); $11:ay8910_0.Write(valor); $20:ay8910_1.Control(valor); $21:ay8910_1.Write(valor); $30:ay8910_2.Control(valor); $31:ay8910_2.Write(valor); end; end; procedure pbaction_sound_irq; begin z80_1.change_irq(HOLD_LINE); z80_1.im2_lo:=2; end; procedure pinballaction_sound_update; begin ay8910_0.update; ay8910_1.update; ay8910_2.update; end; //Main procedure reset_pinballaction; begin z80_0.reset; z80_1.reset; ay8910_0.reset; ay8910_1.reset; ay8910_2.reset; reset_audio; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; scroll_y:=0; sound_latch:=0; nmi_mask:=false; end; function iniciar_pinballaction:boolean; const psd_x:array[0..31] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71, 256,257,258,259,260,261,262,263, 320,321,322,323,324,325,326,327); psd_y:array[0..31] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 128+(8*0), 128+(8*1), 128+(8*2), 128+(8*3), 128+(8*4), 128+(8*5), 128+(8*6), 128+(8*7), 512+(8*0), 512+(8*1), 512+(8*2), 512+(8*3), 512+(8*4), 512+(8*5), 512+(8*6), 512+(8*7), 640+(8*0), 640+(8*1), 640+(8*2), 640+(8*3), 640+(8*4), 640+(8*5), 640+(8*6), 640+(8*7)); var memoria_temp:array[0..$ffff] of byte; begin llamadas_maquina.bucle_general:=pinballaction_principal; llamadas_maquina.reset:=reset_pinballaction; iniciar_pinballaction:=false; iniciar_audio(false); screen_init(1,256,256); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256,true); screen_mod_scroll(2,256,256,255,256,256,255); screen_init(3,256,256,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(4000000,$100); z80_0.change_ram_calls(pinballaction_getbyte,pinballaction_putbyte); //Sound CPU z80_1:=cpu_z80.create(3072000,$100); z80_1.change_ram_calls(snd_getbyte,snd_putbyte); z80_1.change_io_calls(nil,snd_outbyte); z80_1.init_sound(pinballaction_sound_update); timers.init(z80_1.numero_cpu,3072000/(2*60),pbaction_sound_irq,nil,true); //Sound Chip ay8910_0:=ay8910_chip.create(1500000,AY8910,0.25); ay8910_1:=ay8910_chip.create(1500000,AY8910,0.25); ay8910_2:=ay8910_chip.create(1500000,AY8910,0.25); //cargar roms if not(roms_load(@memoria,pinballaction_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,pinballaction_sound)) then exit; //convertir chars if not(roms_load(@memoria_temp,pinballaction_chars)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[0]:=true; gfx_set_desc_data(3,0,8*8,$400*0*8*8,$400*1*8*8,$400*2*8*8); convert_gfx(0,0,@memoria_temp,@psd_x,@psd_y,true,false); //tiles if not(roms_load(@memoria_temp,pinballaction_tiles)) then exit; init_gfx(1,8,8,$800); gfx_set_desc_data(4,0,8*8,$800*0*8*8,$800*1*8*8,$800*2*8*8,$800*3*8*8); convert_gfx(1,0,@memoria_temp,@psd_x,@psd_y,true,false); //convertir sprites if not(roms_load(@memoria_temp,pinballaction_sprites)) then exit; init_gfx(2,16,16,$100); gfx[2].trans[0]:=true; gfx_set_desc_data(3,0,32*8,$100*0*8*32,$100*1*8*32,$100*2*8*32); convert_gfx(2,0,@memoria_temp,@psd_x,@psd_y,true,false); //convertir sprites double init_gfx(3,32,32,$20); gfx[3].trans[0]:=true; gfx_set_desc_data(3,0,128*8,$40*0*8*128,$40*1*8*128,$40*2*8*128); convert_gfx(3,0,@memoria_temp[$1000],@psd_x,@psd_y,true,false); //DIP marcade.dswa:=$40; marcade.dswa_val:=@pinballaction_dipa; marcade.dswb:=$0; marcade.dswb_val:=@pinballaction_dipb; reset_pinballaction; iniciar_pinballaction:=true; end; end.
unit uDM; interface uses System.SysUtils, System.Classes, Data.DB, Datasnap.DBClient, frxClass, frxDBSet, frxExportBaseDialog, frxExportPDF, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSSQL, FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs; type TDM = class(TDataModule) CDS: TClientDataSet; CDSCodigo: TIntegerField; CDSNome: TStringField; frxReport1: TfrxReport; frxPDFExport1: TfrxPDFExport; frxds_Mestre: TfrxDBDataset; ConnBanco: TFDConnection; qrAux: TFDQuery; qrBancos: TFDQuery; qrBancosid: TStringField; qrBancosnome: TStringField; qrBancoscnpj: TStringField; procedure DataModuleCreate(Sender: TObject); private { Private declarations } public { Public declarations } procedure CriarDados; function GUIDToString2(const Guid: TGUID): string; end; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDM } procedure TDM.CriarDados; var I: Integer; begin CDS.Close; CDS.CreateDataSet; for I := 1 to 50 do begin CDS.Append; CDSCodigo.AsInteger := I; CDSNome.AsString := 'Nome de Teste ' + I.ToString; CDS.Post; end; end; procedure TDM.DataModuleCreate(Sender: TObject); begin ConnBanco.Params.Clear; ConnBanco.ConnectionDefName := 'PRINCIPAL'; ConnBanco.Connected := True; end; function TDM.GUIDToString2(const Guid: TGUID): string; begin SetLength(Result, 36); StrLFmt(PChar(Result), 36, '%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x', [Guid.d1, Guid.d2, Guid.D3, Guid.D4[0], Guid.D4[1], Guid.D4[2], Guid.D4[3], Guid.D4[4], Guid.D4[5], Guid.D4[6], Guid.D4[7]]); end; end.
{ Subroutine SST_W_C_SYMBOL (SYM) * * Write the declaration for the symbol SYM, if appropriate. If the * declaration of this symbol depends on other symbols, then these symbols will * be declared first, if not already done so. * * Nothing will be done if the symbol declaration was previously written. } module sst_w_c_symbol; define sst_w_c_symbol; %include 'sst_w_c.ins.pas'; define sst_w_c; var nest_level: sys_int_machine_t := 0; {recursive nesting level} procedure sst_w_c_symbol ( {declare symbol and others depended on} in out sym: sst_symbol_t); {symbol to declare} const max_msg_parms = 2; {max parameters we can pass to a message} var i: sys_int_machine_t; {scratch integer} arg_p: sst_proc_arg_p_t; {pointer to procedure argument descriptor} dt_p, dt2_p: sst_dtype_p_t; {scratch data type descriptor pointers} dt: sst_dtype_t; {scratch data type descriptor} name_ele: string_var132_t; {for making declared element name} scope_old_p: sst_scope_p_t; {saved current scope pointer} names_old_p: sst_scope_p_t; {saved current namespace pointer} sym_p: sst_symbol_p_t; {scratch pointer to another symbol} sym_pp: sst_symbol_pp_t; {pointer to hash entry user data area} pos: string_hash_pos_t; {handle to output name symbol table position} last_init_p: sst_symbol_p_t; {points to last comblock var with init value} val_p: sst_var_value_p_t; {points to constant value descriptor} val: sst_var_value_t; {scratch constant value descriptor} sment_decl: sment_type_k_t; {selects global/local declaration statement} pop: boolean; {TRUE if need to pop to old state at end} kluge_old: boolean; {saved copy of NO_IBM_STR_KLUGE flag} ins_ignore: boolean; {doing INS translate, but symbol not from ins} msg_parm: {references to paramters for messages} array[1..max_msg_parms] of sys_parm_msg_t; label var_done_init, comblock, routine_done_args, loop_com, com_done_init, leave; begin if {already did or working on this symbol ?} ( (sst_symflag_written_k in sym.flags) or (sst_symflag_writing_k in sym.flags) or (sst_symflag_intrinsic_out_k in sym.flags)) and not (sst_symflag_defnow_k in sym.flags) then return; if sst_ins then begin {this is an include file translation} ins_ignore := {true if not supposed to write this symbol} (not sst_char_from_ins(sym.char_h)) and (not (sst_symflag_created_k in sym.flags)); end else begin {this is a regular non-include file translate} ins_ignore := false; end ; if {var in common block not being declared now ?} (sym.symtype = sst_symtype_var_k) and {symbol is a variable ?} (sym.var_com_p <> nil) and then {variable is in a common block ?} (not (sst_symflag_writing_k in sym.var_com_p^.flags)) {not doing block now ?} then begin sst_w_c_symbol (sym.var_com_p^); {declare the whole common block} return; end; name_ele.max := size_char(name_ele.str); {init local var string} if sym.name_out_p = nil then begin {no output name currently exists ?} case sym.symtype of {check for special handling symbol types} sst_symtype_abbrev_k: begin {symbol is abbreviation for variable ref} scope_old_p := sst_scope_p; {save old scope/namespace context} names_old_p := sst_names_p; sst_scope_p := sym.scope_p; {temp swap to symbol's scope} sst_names_p := sst_scope_p; sst_w.name^ ( {make output name for abbrev symbol} sym.name_in_p^.str, sym.name_in_p^.len, {input name and length} '_p', 2, {suffix name and length} sst_rename_all_k, {make unique name in all visible scopes} name_ele, {returned output symbol name} pos); {pos handle where name goes in symbol table} string_hash_ent_add ( {add name to output symbol table} pos, {hash table handle where to add entry} sym.name_out_p, {returned pnt to name string in hash table} sym_pp); {returned pnt to hash table data area} sym_pp^ := addr(sym); {point hash table entry to symbol descriptor} sst_scope_p := scope_old_p; {restore old scope} sst_names_p := names_old_p; end; {done handling var reference abbrev symbol} otherwise {normal symbol output naming case} sst_w.name_sym^ (sym); {make output name for this symbol} end; end; if {global symbol being defined here ?} (sst_symflag_global_k in sym.flags) and (not (sst_symflag_extern_k in sym.flags)) then sment_decl := sment_type_declg_k else sment_decl := sment_type_decll_k; %debug 2; writeln ('':nest_level*2, sym.name_out_p^.str:sym.name_out_p^.len); nest_level := nest_level + 1; sym.flags := sym.flags + [sst_symflag_writing_k]; {symbol write is in progress} pop := false; {init to not pop writing state before exit} case sym.symtype of {what kind of symbol is this ?} { ************************************* * * Symbol is a constant. } sst_symtype_const_k: begin sst_w_c_decl_sym_exp (sym.const_exp_p^); {declare nested symbols in expression} if ins_ignore then goto leave; if (frame_scope_p^.scope_type = scope_type_prog_k) or (frame_scope_p^.scope_type = scope_type_module_k) then begin {at top level PROGRAM or MODULE scope ?} sment_decl := sment_type_declg_k; {write declaration at global level} end; sst_w_c_header_decl (sment_decl, pop); {prepare for declaration statement} sst_w_c_sment_start; if {trying to declare string const on IBM ?} (sst_config.os = sys_os_aix_k) and {IBM AIX operating system ?} (sym.const_exp_p^.dtype_p^.dtype = sst_dtype_array_k) and {dtype is ARRAY ?} sym.const_exp_p^.dtype_p^.ar_string {array is a string of characters ?} then begin sst_w.appendn^ ('const char', 10); sst_w.delimit^; sst_w.append_sym_name^ (sym); {write constant's name} sst_w.appendn^ ('[', 1); string_f_int (name_ele, sym.const_exp_p^.dtype_p^.ar_ind_n); sst_w.append^ (name_ele); {write size of string in characters} sst_w.appendn^ (']', 1); sst_w.delimit^; sst_w.appendn^ ('=', 1); sst_w.delimit^; sst_w_c_exp_const (sym.const_exp_p^, 0, nil, enclose_yes_k); {write string} sst_w_c_sment_end; goto leave; end; {done special case AIX string constants} sst_w.appendn^ ('#define', 7); sst_w.delimit^; sst_w.append_sym_name^ (sym); {write constant's name} sst_w.delimit^; sst_w_c_exp_const (sym.const_exp_p^, 0, nil, enclose_yes_k); {write constant's value} sst_w_c_sment_end_nclose; sst_w.line_close^; end; { ************************************* * * Symbol is a data type. } sst_symtype_dtype_k: begin sst_w_c_decl_sym_dtype (sym.dtype_dtype_p^); {declare nested symbols in dtype} if ins_ignore then goto leave; {don't really want to write this symbol ?} if (frame_scope_p^.scope_type = scope_type_prog_k) or (frame_scope_p^.scope_type = scope_type_module_k) then begin {at top level PROGRAM or MODULE scope ?} sment_decl := sment_type_declg_k; {write declaration at global level} end; sst_w_c_header_decl (sment_decl, pop); {prepare for declaration statement} sst_w_c_sment_start; {start a new statement} sst_w.appendn^ ('typedef', 7); sst_w.delimit^; sst_w_c_dtype (sym.dtype_dtype_p^, sym.name_out_p^, false); {write dtype definition} sst_w_c_sment_end; {end this statement} sst_w.blank_line^; {skip one line after each dtype definition} end; {end of symbol is data type case} { ************************************* * * Symbol is a field name of a record. } sst_symtype_field_k: begin sst_w_c_decl_sym_dtype (sym.field_dtype_p^); {declare data type of this field} end; { ************************************* * * Symbol is a variable. } sst_symtype_var_k: begin sst_w_c_decl_sym_dtype (sym.var_dtype_p^); {declare nested symbols in dtype} if sym.var_val_p <> nil then begin {variable has initial value ?} sst_w_c_decl_sym_exp (sym.var_val_p^); {declare nested symbols in initial val} end; if ins_ignore then goto leave; if sym.var_com_p <> nil {variable is in a common block} then goto comblock; {common block vars are handled separately} { ************ * * This variable is not in a common block. } sst_w_c_header_decl (sment_decl, pop); {prepare for declaration statement} sst_w_c_sment_start; {start a new statement} { * Write the storage class. Variables declared at the module level default * to being globally known. The storage class STATIC makes them local. * The default for variables in routines is AUTO, however we must make sure * that any variable in a routine that is initialized is explicitly declared * as STATIC. } i := 0; {make GLOBAL/EXTERNAL flags value} if sst_symflag_extern_k in sym.flags then i := i + 1; if sst_symflag_global_k in sym.flags then i := i + 2; case i of {where is variable supposed to live ?} 0: begin {variable is local only} if {need to explicitly declare as STATIC ?} (frame_scope_p^.sment_type = sment_type_declg_k) or {outside routine ?} (sst_symflag_static_k in sym.flags) {variable is in static storage ?} then begin sst_w.appendn^ ('static', 6); sst_w.delimit^; end; end; 1: begin {externally defined, not globally known} sys_msg_parm_vstr (msg_parm[1], sym.name_in_p^); sys_message_bomb ('sst_c_write', 'extern_not_global', msg_parm, 1); end; 2: ; {globally known and defined here} 3: begin {globally known, defined elsewhere} sst_w.appendn^ ('extern', 6); sst_w.delimit^; end; end; {end of GLOBAL/EXTERNAL cases} { * Special handling for Franklin C51 compiler for Intel 8051 and its * derivatives. Static variables with intial values are really constants, * and must therefore be forced into CODE address space, since that's * the only place where any constants can come from. } if (sst_config.os = sys_os_solaris_k) and {Franklin C51 compiler ?} (sst_config.int_machine_p^.size_used = 1) and (sym.var_val_p <> nil) {variable has an initial value ?} then begin sst_w.delimit^; {make sure "variable" lives in ROM} sst_w.appendn^ ('code', 4); sst_w.delimit^; end; {end of Franklin C51 special case} sst_w_c_dtype_simple ( {declare the variable} sym.var_dtype_p^, sym.name_out_p^, false); { * Handle initial value, if any. } if sym.var_val_p <> nil then begin {this variable has an initial value ?} sst_w.delimit^; sst_w.appendn^ ('=', 1); sst_w.delimit^; dt_p := sym.var_dtype_p; {resolve symbol's base data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; dt2_p := sym.var_val_p^.dtype_p; {resolve expressions base data type} while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p; if {variable is a string ?} (dt_p^.dtype = sst_dtype_array_k) and dt_p^.ar_string then begin val_p := addr(sym.var_val_p^.val); {make pointer to constant value descriptor} if val_p^.dtype = sst_dtype_char_k then begin {value is CHAR, not STRING ?} val.dtype := sst_dtype_array_k; {fill in local val descriptor as a string} val.ar_str_p := univ_ptr(addr(name_ele)); name_ele.len := 1; name_ele.str[1] := val_p^.char_val; val_p := addr(val); {point to converted STRING value descriptor} end; kluge_old := no_ibm_str_kluge; {save value of kluge inhibit flag} no_ibm_str_kluge := {OK to write value as normal quoted string ?} val_p^.ar_str_p^.len < dt_p^.ar_ind_n; sst_w_c_value (val_p^, enclose_no_k); {write string initial value constant} no_ibm_str_kluge := kluge_old; {restore kluge inhibit flag} goto var_done_init; {done writing initial value for this variable} end; {end of variable is string special case} sst_w_c_exp_const (sym.var_val_p^, 0, nil, enclose_yes_k); {write init value exp} end; var_done_init: { * Done handling initial value, if any. } sst_w_c_sment_end; {end this statement} goto leave; { ************ * * This variable is a member of a common block. } comblock: sst_w.tab_indent^; sst_w.indent^; sst_w_c_dtype_simple ( {declare the variable} sym.var_dtype_p^, sym.name_out_p^, false); sst_w.appendn^ (';', 1); sst_w.undent^; sst_w.line_close^; end; { ************************************* * * Symbol is an abbreviation for a variable reference. * These symbols are declared as local variables with a data type * of pointer to the abbreviation expansion. } sst_symtype_abbrev_k: begin sst_w_c_symbol ( {declare nested symbols in abbrev expansion} sym.abbrev_var_p^.mod1.top_sym_p^); if ins_ignore then goto leave; sst_w_c_header_decl (sment_decl, pop); {prepare for declaration statement} sst_w_c_sment_start; {start a new statement} dt.symbol_p := nil; {make dtype of pointer to abbrev expansion} dt.dtype := sst_dtype_pnt_k; dt.bits_min := sst_dtype_uptr_p^.bits_min; dt.align_nat := sst_dtype_uptr_p^.align_nat; dt.align := sst_dtype_uptr_p^.align; dt.size_used := sst_dtype_uptr_p^.size_used; dt.size_align := sst_dtype_uptr_p^.size_align; dt.pnt_dtype_p := sym.abbrev_var_p^.dtype_p; sst_w_c_dtype_simple ( {declare the abbrev pointer variable} dt, {data type descriptor} sym.name_out_p^, {name to declare with data type} false); {not part of packed record} sst_w_c_sment_end; {end variable declaration statement} end; { ************************************* * * Symbol is a routine name. } sst_symtype_proc_k: begin { * Make sure all other symbols referenced by this declaration are declared first. } if sym.proc.dtype_func_p <> nil then begin {routine is a function ?} sst_w_c_decl_sym_dtype (sym.proc.dtype_func_p^); {insure func dtype declared} end; arg_p := sym.proc.first_arg_p; {init current argument to first arg} while arg_p <> nil do begin {loop thru all the routine arguments} sst_w_c_decl_sym_dtype (arg_p^.dtype_p^); {insure arg data type is declared} arg_p := arg_p^.next_p; end; {back and do next call argument} if ins_ignore then goto leave; { * Set up the output text formatting environment. } sst_w.blank_line^; sst_w_c_sment_start; {function declaration will be a "statement"} if sst_symflag_defnow_k in sym.flags then begin {body will be written here ?} sst_w.indent^; {indent one more time for function body} end; { * Write the EXTERN or STATIC keywords, when appropriate. } if sst_symflag_global_k in sym.flags then begin {function is globally known} if sst_symflag_extern_k in sym.flags then begin {function lives externally ?} sst_w.appendn^ ('extern', 6); sst_w.delimit^; end; if sst_config.os = sys_os_win32_k then begin {writing for Win32 API ?} sst_w.appends^ ('__declspec(dllexport)'(0)); {export all global routines} sst_w.delimit^; end; end else begin {function is local to this file} sst_w.appendn^ ('static', 6); sst_w.delimit^; end ; { * If the function is only being declared (not defined) here, then call * SST_W_C_DTYPE to do all the work. } if not (sst_symflag_defnow_k in sym.flags) then begin {just declared here ?} sst_w_c_dtype (sym.proc_dtype_p^, sym.name_out_p^, false); {declare routine} sst_w_c_sment_end; goto leave; {all done declaring routine} end; { * The routine is not just being declared here, but also being defined here. * that means the arguments template includes the dummy argument names. * * Write the function's return value data type. The C language only has * functions, so subroutines are declared with the VOID data type. } scope_old_p := sst_scope_p; {save old scope/namespace context} names_old_p := sst_names_p; sst_scope_p := sym.proc_scope_p; {temp swap in scope of this routine} sst_names_p := sst_scope_p; if sym.proc.dtype_func_p <> nil then begin {routine is a true function (returns a value)} name_ele.len := 0; {null to avoid writing symbol name} sst_w_c_dtype_simple (sym.proc.dtype_func_p^, name_ele, false); {declare func value} end else begin {routine does not return a value} sst_w.appendn^ ('void', 4); end ; sst_w.delimit^; { * Write function's name and start the parameter list. } if (sst_symflag_global_k in sym.flags) and {this is a global function ?} (sst_config.os = sys_os_win32_k) {writing for Win32 API ?} then begin sst_w.appends^ ('__stdcall'(0)); {specify linkage conventions} sst_w.delimit^; end; sst_w.append_sym_name^ (sym); sst_w.delimit^; sst_w.appendn^ ('(', 1); { * Handle special case where function takes no passed parameters. } if sym.proc.n_args <= 0 then begin {function takes no arguments ?} sst_w.appendn^ ('void', 4); goto routine_done_args; end; { * Declare the call parameters. } arg_p := sym.proc.first_arg_p; {init current argument to first argument} while arg_p <> nil do begin {loop thru each call argument} sst_w.line_close^; {put each argument on its own line} sst_w.tab_indent^; sst_w.name_sym^ (arg_p^.sym_p^); {make output name for this dummy argument} arg_p^.sym_p^.flags := {prevent dummy arg being declared later} arg_p^.sym_p^.flags + [sst_symflag_written_k]; dt_p := arg_p^.dtype_p; {get argument's base data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; case arg_p^.pass of {how is this argument passed ?} sst_pass_ref_k: begin {argument is passed by reference} if dt_p^.dtype = sst_dtype_array_k then begin {argument is implicitly passed as pointer} name_ele.len := 0; end else begin {explicitly indicate arg passed as pointer} name_ele.str[1] := '*'; {indicate argument is a pointer} name_ele.len := 1; end ; string_append (name_ele, arg_p^.sym_p^.name_out_p^); {add on argument name} sst_w_c_dtype_simple ( {declare data type of this argument} arg_p^.dtype_p^, {data type descriptor} name_ele, {name of symbol to declare} false); {no, this is not a field in a packed record} end; sst_pass_val_k: begin {argument is passed by value} sst_w_c_dtype_simple ( {declare data type of this argument} arg_p^.dtype_p^, {data type descriptor} arg_p^.sym_p^.name_out_p^, {name of symbol to declare} false); {no, this is not a field in a packed record} end; otherwise sys_msg_parm_int (msg_parm[1], ord(arg_p^.pass)); sys_message_bomb ('sst_c_write', 'arg_pass_method_bad', msg_parm, 1); end; arg_p := arg_p^.next_p; {advance to next argument descriptor in list} if arg_p <> nil then begin {more arguments follow ?} sst_w.appendn^ (',', 1); sst_w.delimit^; end; end; {back and process next call argument} routine_done_args: {done writing last call argument} sst_w.appendn^ (')', 1); {close argument list} { * Just finished writing the end of the argument list. } sst_w.delimit^; sst_w.appendn^ ('{', 1); sst_w_c_sment_end_nclose; sst_w.line_close^; sst_scope_p := scope_old_p; {restore old scope/namespace} sst_names_p := names_old_p; end; { ************************************* * * Symbol is a common block name. * * Common blocks are emulated in C with globally known variables that are * STRUCTs, where each field in the struct is a variable in the common block. } sst_symtype_com_k: begin if sym.com_first_p = nil then goto leave; {don't write empty common blocks} last_init_p := nil; {init to no variable has an initial value} sst_scope_new; {create new scope for var names in com block} sym_p := sym.com_first_p; {init current common var to first in list} while sym_p <> nil do begin {once for each variable in common block} sym_p^.flags := {prevent recursive follow of this variable} sym_p^.flags + [sst_symflag_writing_k]; scope_old_p := sym_p^.scope_p; {save pointer to var's scope} sym_p^.scope_p := sst_scope_p; {temp put variable into scope for com block} sst_w_c_name_com_var (sym_p^); {set output name for common block variable} sym_p^.scope_p := scope_old_p; {restore variable's original scope} if sym_p^.var_val_p <> nil then begin {this variable has an initial value ?} sst_w_c_decl_sym_exp (sym_p^.var_val_p^); {declare nested symbols in init val} last_init_p := sym_p; {update last variable with initial value} end; sym_p := sym_p^.var_next_p; {point to next variable in common block} end; {back and process this new variable name} sst_scope_old; {restore current scope} if ins_ignore then goto leave; sst_w.blank_line^; sst_w_c_header_decl (sment_decl, pop); {prepare for declaration statement} sst_w_c_sment_start; {avoid interrupting common block declaration} if sst_symflag_extern_k in sym.flags then begin {common block not def here ?} sst_w.appendn^ ('extern', 6); sst_w.delimit^; end; sst_w.appendn^ ('struct', 6); sst_w.delimit^; sst_w.appendn^ ('{', 1); sst_w.line_close^; sym_p := sym.com_first_p; {init current common var to first in list} while sym_p <> nil do begin {once for each variable in common block} sym_p^.flags := {turn off temporary recursive prevent lock} sym_p^.flags - [sst_symflag_writing_k]; sst_w_c_symbol (sym_p^); {declare this variable} sym_p := sym_p^.var_next_p; {point to next variable in common block} end; {back and process this new variable name} sst_w.tab_indent^; sst_w.appendn^ ('}', 1); {close the STRUCT definition} sst_w.delimit^; sst_w.append_sym_name^ (sym); {name of var being declared with the STRUCT} { * If any variable in the common block has an initial value, then every variable * in the common block, up to the last one with an initial value, must be * initialized. This is because the common block is really a structure, and * that is how structures are initialized in C. * * LAST_INIT_P is pointing to the symbol descriptor for the last variable in the * common block that has an initial value. It is NIL if none of the variables * had initial values. } if (last_init_p <> nil) and {at least one variable had initial value ?} (not (sst_symflag_extern_k in sym.flags)) {common block being defined here ?} then begin sst_w.appendn^ (' = {', 4); sst_w.indent^; {indent extra level for initial values} sst_w.tab_indent^; sym_p := sym.com_first_p; {init current com block var to first in list} loop_com: {back here each new variable in common block} sst_w.line_close^; sst_w.tab_indent^; sst_w.indent^; if sym_p^.var_val_p = nil then begin {this variable has no initial value} sst_w_c_ival_unspec ( {write the "unspecified" value for this dtype} sym_p^.var_dtype_p^); end else begin {this variable has an explicit initial value} dt_p := sym_p^.var_dtype_p; {resolve symbol's base data type} while dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; dt2_p := sym_p^.var_val_p^.dtype_p; {resolve expressions base data type} while dt2_p^.dtype = sst_dtype_copy_k do dt2_p := dt2_p^.copy_dtype_p; if {variable is a string ?} (dt_p^.dtype = sst_dtype_array_k) and dt_p^.ar_string then begin val_p := addr(sym.var_val_p^.val); {make pointer to constant value descriptor} if val_p^.dtype = sst_dtype_char_k then begin {value is CHAR, not STRING ?} val.dtype := sst_dtype_array_k; {fill in local val descriptor as a string} val.ar_str_p := univ_ptr(addr(name_ele)); name_ele.len := 1; name_ele.str[1] := val_p^.char_val; val_p := addr(val); {point to converted STRING value descriptor} end; kluge_old := no_ibm_str_kluge; {save value of kluge inhibit flag} no_ibm_str_kluge := {OK to write value as normal quoted string ?} val_p^.ar_str_p^.len < dt_p^.ar_ind_n; sst_w_c_value (val_p^, enclose_no_k); {write string initial value constant} no_ibm_str_kluge := kluge_old; {restore kluge inhibit flag} goto com_done_init; {done writing initial value for this variable} end; {end of variable is string special case} sst_w_c_exp ( {write explicit initial value for this var} sym_p^.var_val_p^, 0, nil, enclose_no_k); com_done_init: {done writing initial value for this var} end ; sst_w.undent^; if sym_p <> last_init_p then begin {this was not last variable to initialize ?} sst_w.appendn^ (',', 1); sst_w.delimit^; sym_p := sym_p^.var_next_p; {advance to next common block variable} goto loop_com; {back and process this new variable} end; sst_w.line_close^; sst_w.tab_indent^; sst_w.appendn^ ('}', 1); {close initial values list} sst_w.undent^; {undo extra indent for initial values} sst_w.line_close^; sst_w.tab_indent^; end; {all done initializing variables} { * Done handling initial values, if any. } sst_w_c_sment_end; {end the common block definition} sst_w.blank_line^; end; { ************************************* * * Symbol types that require no special processing. } sst_symtype_enum_k: ; sst_symtype_label_k: ; sst_symtype_prog_k: ; sst_symtype_module_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(sym.symtype)); sys_message_bomb ('sst', 'symbol_type_unknown', msg_parm, 1); end; {end of symbol type cases} { ************************************* * * Done with each of the code sections that handle the symbol uniquely depending * on what type of symbol it is. Now do common cleanup, and then leave. } leave: {jump here if done declaring symbol} sym.flags := sym.flags + {flag symbol as completely written} [sst_symflag_written_k]; sym.flags := sym.flags - {symbol write no longer in process} [sst_symflag_writing_k, sst_symflag_defnow_k, sst_symflag_writing_dt_k]; if pop then begin {need to pop to previous writing state ?} sst_w_c_pos_pop; end; nest_level := nest_level - 1; end;
unit MdIntfTest; interface uses Windows, Messages, SysUtils, Classes, StdCtrls; type IMdViewer = interface ['{9766860D-8E4A-4254-9843-59B98FEE6C54}'] procedure View (const str: string); end; TMdIntfTest = class(TComponent) private FViewer: IMdViewer; FText: string; procedure SetViewer(const Value: IMdViewer); procedure SetText(const Value: string); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property Viewer: IMdViewer read FViewer write SetViewer; property Text: string read FText write SetText; end; TViewerLabel = class (TLabel, IMdViewer) public procedure View(const str: String); function Component: TComponent; end; procedure Register; implementation procedure Register; begin RegisterComponents('Md', [TMdIntfTest, TViewerLabel]); end; { TMdIntfTest } procedure TMdIntfTest.Notification(AComponent: TComponent; Operation: TOperation); var intf: IMdViewer; begin inherited; if (Operation = opRemove) and (Supports (AComponent, IMdViewer, intf)) and (intf = fViewer) then begin fViewer := nil; end; end; procedure TMdIntfTest.SetText(const Value: string); begin FText := Value; if Assigned (fViewer) then fViewer.View(fText); end; procedure TMdIntfTest.SetViewer(const Value: IMdViewer); var iComp: IInterfaceComponentReference; begin if FViewer <> Value then begin FViewer := Value; FViewer.View(fText); if Supports (FViewer, IInterfaceComponentReference, iComp) then iComp.GetComponent.FreeNotification(self); end; end; { TViewerLabel } function TViewerLabel.Component: TComponent; begin Result := self; end; procedure TViewerLabel.View(const str: String); begin Caption := str; end; end.
unit uBorder; interface uses Graphics; type TBorder = class private public TL, DL, TR, DR, THL, LVL, DHL, RVL: TBitMap; procedure Make(AImage: TBitMap); constructor Create(Path: string); destructor Destroy; override; end; implementation uses SysUtils; { TBorder } constructor TBorder.Create(Path: string); begin THL := TBitMap.Create; THL.LoadFromFile(Path + 'THL.bmp'); DHL := TBitMap.Create; DHL.LoadFromFile(Path + 'DHL.bmp'); LVL := TBitMap.Create; LVL.LoadFromFile(Path + 'LVL.bmp'); RVL := TBitMap.Create; RVL.LoadFromFile(Path + 'RVL.bmp'); DR := TBitMap.Create; DR.Transparent := True; DR.TransparentColor := clFuchsia; DR.LoadFromFile(Path + 'DR.bmp'); TR := TBitMap.Create; TR.Transparent := True; TR.TransparentColor := clFuchsia; TR.LoadFromFile(Path + 'TR.bmp'); DL := TBitMap.Create; DL.Transparent := True; DL.TransparentColor := clFuchsia; DL.LoadFromFile(Path + 'DL.bmp'); TL := TBitMap.Create; TL.LoadFromFile(Path + 'TL.bmp'); TL.TransparentColor := clFuchsia; TL.Transparent := True; end; destructor TBorder.Destroy; begin THL.Free; DHL.Free; LVL.Free; RVL.Free; TL.Free; DL.Free; TR.Free; DR.Free; inherited; end; procedure TBorder.Make(AImage: TBitMap); var C: Word; B: TBitmap; begin B := TBitMap.Create; try B.Assign(AImage); C := TL.Width; while (C < AImage.Width - THL.Width) do begin B.Canvas.Draw(C, 0, THL); B.Canvas.Draw(C, AImage.Height - DHL.Height, DHL); Inc(C, THL.Width); end; C := TL.Height; while (C < AImage.Height - LVL.Height) do begin B.Canvas.Draw(0, C, LVL); B.Canvas.Draw(AImage.Width - RVL.Width, C, RVL); Inc(C, LVL.Height); end; B.Canvas.Draw(0, 0, TL); B.Canvas.Draw(0, AImage.Height - DL.Height, DL); B.Canvas.Draw(AImage.Width - TR.Width, 0, TR); B.Canvas.Draw(AImage.Width - DR.Width, AImage.Height - DR.Height, DR); AImage.Assign(B); finally FreeAndNil(B); end; end; end.
unit uItens; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, PngSpeedButton, Vcl.ExtCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait, FireDAC.Comp.DataSet, FireDAC.Comp.Client, objItem; type TfItens = class(TForm) pnlFundoItens: TPanel; pnlItens: TPanel; pnl6: TPanel; sbtNovoItem: TPngSpeedButton; sbtEditarItem: TPngSpeedButton; sbtCancelarEdicaoItem: TPngSpeedButton; sbtExcluirItem: TPngSpeedButton; sbtConfirmarItem: TPngSpeedButton; pnlDadosItens: TPanel; dbgItens: TDBGrid; lblValor: TLabel; edtValor: TEdit; chkAtivo: TCheckBox; lblDescricao: TLabel; mmoDescricao: TMemo; quItens: TFDQuery; dsItens: TDataSource; quItenscodigo: TFDAutoIncField; quItensdescricao: TStringField; quItensvalor: TFloatField; quItensativo: TWideStringField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure sbtExcluirItemClick(Sender: TObject); procedure sbtCancelarEdicaoItemClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure sbtEditarItemClick(Sender: TObject); procedure sbtNovoItemClick(Sender: TObject); procedure sbtConfirmarItemClick(Sender: TObject); procedure edtValorKeyPress(Sender: TObject; var Key: Char); procedure edtValorExit(Sender: TObject); procedure dbgItensCellClick(Column: TColumn); procedure edtValorEnter(Sender: TObject); private { Private declarations } Fconexao : TFDConnection; Fitem : TItem; novoItem : Boolean; alterarItem : Boolean; procedure LimpaCampos; public { Public declarations } procedure AtribuiConexao(objConexao : TFDConnection); procedure CarregaItens; end; var fItens: TfItens; implementation {$R *.dfm} procedure TfItens.AtribuiConexao(objConexao: TFDConnection); begin try Fconexao := objConexao; Fconexao.Connected := True; if quItens.Connection = nil then begin quItens.Connection := Fconexao; quItens.Active := True; end; Fitem := TItem.Create(Fconexao); except on e:Exception do ShowMessage('Erro ao atribuir conexão!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.CarregaItens; begin try quItens.Close; quItens.SQL.Clear; Fitem.CarregarItens(quItens); quItens.Open; except on e:Exception do ShowMessage('Erro ao carregar itens!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.dbgItensCellClick(Column: TColumn); begin try if not quItens.Eof then begin Fitem.codigo := quItens.FieldByName('CODIGO').AsInteger; Fitem.descricao := quItens.FieldByName('DESCRICAO').AsString; Fitem.valor := quItens.FieldByName('VALOR').AsFloat; Fitem.ativo := quItens.FieldByName('ATIVO').AsString = 'Sim'; edtValor.Text := FloatToStr(Fitem.valor); edtValorExit(Self); chkAtivo.Checked := Fitem.ativo; mmoDescricao.Lines.Text := Fitem.descricao; end; except on e:Exception do ShowMessage('Erro ao carregar informações do item!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.edtValorEnter(Sender: TObject); begin edtValor.Text := StringReplace(edtValor.Text, '.', '', [rfReplaceAll]); end; procedure TfItens.edtValorExit(Sender: TObject); begin try if Trim(edtValor.Text) <> '' then begin if StrToFloat(StringReplace(edtValor.Text, '.', '', [rfReplaceAll])) > 0 then begin edtValor.Text := FormatFloat('##,###,###.##', StrToFloat(edtValor.Text)); end; end; except on e:Exception do ShowMessage('Erro ao formatar valor!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.edtValorKeyPress(Sender: TObject; var Key: Char); begin try if not (Key in ['0'..'9', Chr(44), Chr(127), Chr(8)]) then Key := #0; except on e:Exception do ShowMessage('Erro ao aplicar regra!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.FormClose(Sender: TObject; var Action: TCloseAction); begin Fconexao.Connected := False; Fitem.Destroy; Action := caFree; fItens := nil; end; procedure TfItens.FormCreate(Sender: TObject); begin novoItem := False; alterarItem := False; end; procedure TfItens.LimpaCampos; begin try edtValor.Text := '0,00'; chkAtivo.Checked := False; mmoDescricao.Lines.Clear; except on e:Exception do ShowMessage('Erro ao limpar campos!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.sbtCancelarEdicaoItemClick(Sender: TObject); begin try pnlDadosItens.Enabled := False; sbtCancelarEdicaoItem.Enabled := False; sbtConfirmarItem.Enabled := False; dbgItens.Enabled := True; sbtNovoItem.Enabled := True; sbtExcluirItem.Enabled := True; sbtEditarItem.Enabled := True; novoItem := False; alterarItem := False; except on e:Exception do ShowMessage('Erro ao cancelar inserção/edição de item.' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.sbtConfirmarItemClick(Sender: TObject); begin try Fconexao.StartTransaction; try if Trim(mmoDescricao.Lines.Text) = '' then begin ShowMessage('Uma descrição deve ser informada!'); mmoDescricao.SetFocus; Exit; end; if Trim(edtValor.Text) = '' then begin ShowMessage('Um valor deve ser informado!'); edtValor.SetFocus; Exit; end; if StrToFloat(StringReplace(edtValor.Text, '.', '', [rfReplaceAll])) <= 0 then begin ShowMessage('O valor deve ser maior que zero!'); edtValor.SetFocus; Exit; end; if StrToFloat(StringReplace(edtValor.Text, '.', '', [rfReplaceAll])) > 99999999.99 then begin ShowMessage('O valor deve ser menor que R$99.999.999,99!'); edtValor.SetFocus; Exit; end; Fitem.valor := StrToFloat(StringReplace(edtValor.Text, '.', '', [rfReplaceAll])); Fitem.descricao := mmoDescricao.Lines.Text; Fitem.ativo := chkAtivo.Checked; if novoItem then Fitem.Salvar else if alterarItem then begin Fitem.codigo := quItens.FieldByName('CODIGO').AsInteger; Fitem.Editar; end else raise Exception.Create('Nenhuma operação de item selecionada!'); quItens.Refresh; sbtCancelarEdicaoItemClick(Self); Fconexao.Commit; except on e:Exception do begin Fconexao.Rollback; ShowMessage('Erro ao salvar/alterar item.' + #13 + 'Erro: ' + e.Message); end; end; finally if Fconexao.InTransaction then Fconexao.Rollback; end; end; procedure TfItens.sbtEditarItemClick(Sender: TObject); begin try if quItens.Eof then Exit; if quItens.FieldByName('CODIGO').AsInteger <= 0 then begin ShowMessage('Um item deve ser selecionado para exclusão.'); Exit; end; dbgItens.Enabled := False; sbtNovoItem.Enabled := False; sbtExcluirItem.Enabled := False; sbtEditarItem.Enabled := False; sbtCancelarEdicaoItem.Enabled := True; pnlDadosItens.Enabled := True; sbtConfirmarItem.Enabled := True; alterarItem := True; edtValor.SetFocus; except on e:Exception do ShowMessage('Erro ao habilitar edição de item!' + #13 + 'Erro: ' + e.Message); end; end; procedure TfItens.sbtExcluirItemClick(Sender: TObject); begin if quItens.Eof then Exit; if quItens.FieldByName('CODIGO').AsInteger <= 0 then begin ShowMessage('Um item deve ser selecionado para exclusão.'); Exit; end; if MessageDlg('Deseja excluir o item ' + IntToStr(quItens.FieldByName('CODIGO').AsInteger) + '?', mtConfirmation, [mbYes, mbNo], 0) = mrNo then Exit; try Fconexao.StartTransaction; try Fitem.codigo := quItens.FieldByName('CODIGO').AsInteger; Fitem.Excluir; Fconexao.Commit; LimpaCampos; quItens.Refresh; except on e:Exception do begin Fconexao.Rollback; ShowMessage('Erro ao excluir item.' + #13 + 'Erro: ' + e.Message); end; end; finally if Fconexao.InTransaction then Fconexao.Rollback; end; end; procedure TfItens.sbtNovoItemClick(Sender: TObject); begin try LimpaCampos; dbgItens.Enabled := False; sbtNovoItem.Enabled := False; sbtExcluirItem.Enabled := False; sbtEditarItem.Enabled := False; sbtCancelarEdicaoItem.Enabled := True; pnlDadosItens.Enabled := True; sbtConfirmarItem.Enabled := True; novoItem := True; chkAtivo.Checked := True; edtValor.SetFocus; except on e:Exception do ShowMessage('Erro ao habilitar inserção de item!' + #13 + 'Erro: ' + e.Message); end; end; end.
unit uGnSingleton; interface uses SysUtils, Generics.Collections; type ESingletonException = class(Exception); TSingleton = class(TObject) strict private FRefCounter: Integer; strict protected procedure CreateSingleton; virtual; procedure DestroySingleton; virtual; public class function NewInstance: TObject; override; procedure FreeInstance; override; end; TTypedSingleton<T: class> = class(TSingleton) public class function NewInstance: T; reintroduce; end; implementation type TSingletonList = class (TObjectList<TSingleton>) public destructor Destroy; override; function Find(AClassName: string): TSingleton; end; var SingletonList: TSingletonList; { TSingleton } procedure TSingleton.DestroySingleton; begin end; procedure TSingleton.FreeInstance; begin Dec(FRefCounter); if FRefCounter > 0 then Exit; if FRefCounter < 0 then raise Exception.Create('Error Message'); DestroySingleton; SingletonList.Delete(SingletonList.IndexOf(Self)); inherited FreeInstance; end; procedure TSingleton.CreateSingleton; begin end; class function TSingleton.NewInstance: TObject; var OldObject: TSingleton; begin OldObject := SingletonList.Find(ClassName); if not Assigned(OldObject) then begin OldObject := TSingleton(inherited NewInstance); OldObject.CreateSingleton; SingletonList.Add(OldObject); end; Inc(OldObject.FRefCounter); Exit(OldObject); end; { TSingletonList } destructor TSingletonList.Destroy; var Singleton: TSingleton; begin for Singleton in Self do Singleton.Destroy; inherited; end; function TSingletonList.Find(AClassName: string): TSingleton; var Obj: TSingleton; begin for Obj in Self do if Obj.ClassNameIs(AClassName) then Exit(Obj); Exit(nil); end; { TTypedSingleton<T> } class function TTypedSingleton<T>.NewInstance: T; begin Result := T(inherited NewInstance); end; initialization SingletonList := TSingletonList.Create(False); finalization FreeAndNil(SingletonList); 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.38 11/10/2004 8:25:54 AM JPMugaas Fix for AV caused by short-circut boolean evaluation. Rev 1.37 27.08.2004 21:58:20 Andreas Hausladen Speed optimization ("const" for string parameters) Rev 1.36 8/2/04 5:44:40 PM RLebeau Moved ConnectTimeout over from TIdIOHandlerStack Rev 1.35 7/21/2004 12:22:32 PM BGooijen Fix to .connected Rev 1.34 6/30/2004 12:31:34 PM BGooijen Added OnSocketAllocated Rev 1.33 4/24/04 12:52:52 PM RLebeau Added setter method to UseNagle property Rev 1.32 2004.04.18 12:52:02 AM czhower Big bug fix with server disconnect and several other bug fixed that I found along the way. Rev 1.31 2004.02.03 4:16:46 PM czhower For unit name changes. Rev 1.30 2/2/2004 11:46:46 AM BGooijen Dotnet and TransparentProxy Rev 1.29 2/1/2004 9:44:00 PM JPMugaas Start on reenabling Transparant proxy. Rev 1.28 2004.01.20 10:03:28 PM czhower InitComponent Rev 1.27 1/2/2004 12:02:16 AM BGooijen added OnBeforeBind/OnAfterBind Rev 1.26 12/31/2003 9:51:56 PM BGooijen Added IPv6 support Rev 1.25 11/4/2003 10:37:40 PM BGooijen JP's patch to fix the bound port Rev 1.24 10/19/2003 5:21:26 PM BGooijen SetSocketOption Rev 1.23 10/18/2003 1:44:06 PM BGooijen Added include Rev 1.22 2003.10.14 1:26:54 PM czhower Uupdates + Intercept support Rev 1.21 10/9/2003 8:09:06 PM SPerry bug fixes Rev 1.20 8/10/2003 2:05:50 PM SGrobety Dotnet Rev 1.19 2003.10.07 10:18:26 PM czhower Uncommneted todo code that is now non dotnet. Rev 1.18 2003.10.02 8:23:42 PM czhower DotNet Excludes Rev 1.17 2003.10.01 9:11:18 PM czhower .Net Rev 1.16 2003.10.01 5:05:12 PM czhower .Net Rev 1.15 2003.10.01 2:46:38 PM czhower .Net Rev 1.14 2003.10.01 11:16:32 AM czhower .Net Rev 1.13 2003.09.30 1:22:58 PM czhower Stack split for DotNet Rev 1.12 7/4/2003 08:26:44 AM JPMugaas Optimizations. Rev 1.11 7/1/2003 03:39:44 PM JPMugaas Started numeric IP function API calls for more efficiency. Rev 1.10 2003.06.30 5:41:56 PM czhower -Fixed AV that occurred sometimes when sockets were closed with chains -Consolidated code that was marked by a todo for merging as it no longer needed to be separate -Removed some older code that was no longer necessary Passes bubble tests. Rev 1.9 6/3/2003 11:45:58 PM BGooijen Added .Connected Rev 1.8 2003.04.22 7:45:34 PM czhower Rev 1.7 4/2/2003 3:24:56 PM BGooijen Moved transparantproxy from ..stack to ..socket Rev 1.6 2/28/2003 9:51:56 PM BGooijen removed the field: FReadTimeout: Integer, it hided the one in TIdIOHandler Rev 1.5 2/26/2003 1:15:38 PM BGooijen FBinding is now freed in IdIOHandlerSocket, instead of in IdIOHandlerStack Rev 1.4 2003.02.25 1:36:08 AM czhower Rev 1.3 2002.12.07 12:26:26 AM czhower Rev 1.2 12-6-2002 20:09:14 BGooijen Changed SetDestination to search for the last ':', instead of the first Rev 1.1 12-6-2002 18:54:14 BGooijen Added IPv6-support Rev 1.0 11/13/2002 08:45:08 AM JPMugaas } unit IdIOHandlerSocket; interface {$I IdCompilerDefines.inc} uses Classes, IdCustomTransparentProxy, IdBaseComponent, IdGlobal, IdIOHandler, IdSocketHandle; const IdDefTimeout = 0; IdBoundPortDefault = 0; type { TIdIOHandlerSocket is the base class for socket IOHandlers that implement a binding. Descendants -TIdIOHandlerStack -TIdIOHandlerChain } TIdIOHandlerSocket = class(TIdIOHandler) protected FBinding: TIdSocketHandle; FBoundIP: string; FBoundPort: TIdPort; FBoundPortMax: TIdPort; FBoundPortMin: TIdPort; FDefaultPort: TIdPort; FOnBeforeBind: TNotifyEvent; FOnAfterBind: TNotifyEvent; FOnSocketAllocated: TNotifyEvent; FTransparentProxy: TIdCustomTransparentProxy; FUseNagle: Boolean; FReuseSocket: TIdReuseSocket; FIPVersion: TIdIPVersion; // procedure ConnectClient; virtual; procedure DoBeforeBind; virtual; procedure DoAfterBind; virtual; procedure DoSocketAllocated; virtual; procedure InitComponent; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetDestination: string; override; procedure SetDestination(const AValue: string); override; function GetReuseSocket: TIdReuseSocket; procedure SetReuseSocket(AValue: TIdReuseSocket); function GetTransparentProxy: TIdCustomTransparentProxy; virtual; procedure SetTransparentProxy(AProxy: TIdCustomTransparentProxy); virtual; function GetUseNagle: Boolean; procedure SetUseNagle(AValue: Boolean); // function SourceIsAvailable: Boolean; override; function CheckForError(ALastResult: Integer): Integer; override; procedure RaiseError(AError: Integer); override; public destructor Destroy; override; function BindingAllocated: Boolean; procedure Close; override; function Connected: Boolean; override; procedure Open; override; function WriteFile(const AFile: String; AEnableTransferFile: Boolean = False): Int64; override; // property Binding: TIdSocketHandle read FBinding; property BoundPortMax: TIdPort read FBoundPortMax write FBoundPortMax; property BoundPortMin: TIdPort read FBoundPortMin write FBoundPortMin; // events property OnBeforeBind: TNotifyEvent read FOnBeforeBind write FOnBeforeBind; property OnAfterBind: TNotifyEvent read FOnAfterBind write FOnAfterBind; property OnSocketAllocated: TNotifyEvent read FOnSocketAllocated write FOnSocketAllocated; published property BoundIP: string read FBoundIP write FBoundIP; property BoundPort: TIdPort read FBoundPort write FBoundPort default IdBoundPortDefault; property DefaultPort: TIdPort read FDefaultPort write FDefaultPort; property IPVersion: TIdIPVersion read FIPVersion write FIPVersion default ID_DEFAULT_IP_VERSION; property ReuseSocket: TIdReuseSocket read GetReuseSocket write SetReuseSocket default rsOSDependent; property TransparentProxy: TIdCustomTransparentProxy read GetTransparentProxy write SetTransparentProxy; property UseNagle: boolean read GetUseNagle write SetUseNagle default True; end; implementation uses //facilitate inlining only. {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.IO, {$ENDIF} {$ENDIF} {$IFDEF WIN32_OR_WIN64 } Windows, {$ENDIF} SysUtils, IdStack, IdStackConsts, IdSocks; { TIdIOHandlerSocket } procedure TIdIOHandlerSocket.Close; begin if FBinding <> nil then begin FBinding.CloseSocket; end; inherited Close; end; procedure TIdIOHandlerSocket.ConnectClient; begin with Binding do begin DoBeforeBind; // Allocate the socket IPVersion := Self.FIPVersion; AllocateSocket; DoSocketAllocated; // Bind the socket if BoundIP <> '' then begin IP := BoundIP; end; Port := BoundPort; ClientPortMin := BoundPortMin; ClientPortMax := BoundPortMax; ReuseSocket := Self.FReuseSocket; Bind; // Turn off Nagle if specified UseNagle := Self.FUseNagle; DoAfterBind; end; end; function TIdIOHandlerSocket.Connected: Boolean; begin Result := (BindingAllocated and inherited Connected) or (not InputBufferIsEmpty); end; destructor TIdIOHandlerSocket.Destroy; begin if Assigned(FTransparentProxy) then begin if FTransparentProxy.Owner = nil then begin FreeAndNil(FTransparentProxy); end; end; FreeAndNil(FBinding); inherited Destroy; end; procedure TIdIOHandlerSocket.DoBeforeBind; begin if Assigned(FOnBeforeBind) then begin FOnBeforeBind(self); end; end; procedure TIdIOHandlerSocket.DoAfterBind; begin if Assigned(FOnAfterBind) then begin FOnAfterBind(self); end; end; procedure TIdIOHandlerSocket.DoSocketAllocated; begin if Assigned(FOnSocketAllocated) then begin FOnSocketAllocated(self); end; end; function TIdIOHandlerSocket.GetDestination: string; begin Result := Host; if (Port <> DefaultPort) and (Port > 0) then begin Result := Host + ':' + IntToStr(Port); end; end; procedure TIdIOHandlerSocket.Open; begin inherited Open; if not Assigned(FBinding) then begin FBinding := TIdSocketHandle.Create(nil); end else begin FBinding.Reset(True); end; FBinding.ClientPortMin := BoundPortMin; FBinding.ClientPortMax := BoundPortMax; //if the IOHandler is used to accept connections then port+host will be empty if (Host <> '') and (Port > 0) then begin ConnectClient; end; end; procedure TIdIOHandlerSocket.SetDestination(const AValue: string); var LPortStart: integer; begin // Bas Gooijen 06-Dec-2002: Changed to search the last ':', instead of the first: LPortStart := LastDelimiter(':', AValue); if LPortStart > 0 then begin Host := Copy(AValue, 1, LPortStart-1); Port := IndyStrToInt(Trim(Copy(AValue, LPortStart + 1, $FF)), DefaultPort); end; end; function TIdIOHandlerSocket.BindingAllocated: Boolean; begin Result := FBinding <> nil; if Result then begin Result := FBinding.HandleAllocated; end; end; function TIdIOHandlerSocket.WriteFile(const AFile: String; AEnableTransferFile: Boolean): Int64; {$IFDEF WIN32_OR_WIN64} var LOldErrorMode : Integer; {$ENDIF} begin Result := 0; {$IFDEF WIN32_OR_WIN64} LOldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try {$ENDIF} if FileExists(AFile) then begin if Assigned(GServeFileProc) and (not WriteBufferingActive) {and (Intercept = nil)} and AEnableTransferFile then begin Result := GServeFileProc(Binding.Handle, AFile); Exit; end else begin Result := inherited WriteFile(AFile, AEnableTransferFile); end; end; {$IFDEF WIN32_OR_WIN64} finally SetErrorMode(LOldErrorMode) end; {$ENDIF} end; function TIdIOHandlerSocket.GetReuseSocket: TIdReuseSocket; begin if FBinding <> nil then begin Result := FBinding.ReuseSocket; end else begin Result := FReuseSocket; end; end; procedure TIdIOHandlerSocket.SetReuseSocket(AValue: TIdReuseSocket); begin FReuseSocket := AValue; if FBinding <> nil then begin FBinding.ReuseSocket := AValue; end; end; procedure TIdIOHandlerSocket.SetTransparentProxy(AProxy : TIdCustomTransparentProxy); var LClass: TIdCustomTransparentProxyClass; begin // All this is to preserve the compatibility with old version // In the case when we have SocksInfo as object created in runtime without owner form it is treated as temporary object // In the case when the ASocks points to an object with owner it is treated as component on form. if Assigned(AProxy) then begin if not Assigned(AProxy.Owner) then begin if Assigned(FTransparentProxy) then begin if Assigned(FTransparentProxy.Owner) then begin FTransparentProxy.RemoveFreeNotification(Self); FTransparentProxy := nil; end; end; LClass := TIdCustomTransparentProxyClass(AProxy.ClassType); if Assigned(FTransparentProxy) and (FTransparentProxy.ClassType <> LClass) then begin FreeAndNil(FTransparentProxy); end; if not Assigned(FTransparentProxy) then begin FTransparentProxy := LClass.Create(nil); end; FTransparentProxy.Assign(AProxy); end else begin if Assigned(FTransparentProxy) then begin if not Assigned(FTransparentProxy.Owner) then begin FreeAndNil(FTransparentProxy); end else begin FTransparentProxy.RemoveFreeNotification(Self); end; end; FTransparentProxy := AProxy; FTransparentProxy.FreeNotification(Self); end; end else if Assigned(FTransparentProxy) then begin if not Assigned(FTransparentProxy.Owner) then begin FreeAndNil(FTransparentProxy); end else begin FTransparentProxy.RemoveFreeNotification(Self); FTransparentProxy := nil; //remove link end; end; end; function TIdIOHandlerSocket.GetTransparentProxy: TIdCustomTransparentProxy; begin // Necessary at design time for Borland SOAP support if FTransparentProxy = nil then begin FTransparentProxy := TIdSocksInfo.Create(nil); //default end; Result := FTransparentProxy; end; function TIdIOHandlerSocket.GetUseNagle: Boolean; begin if FBinding <> nil then begin Result := FBinding.UseNagle; end else begin Result := FUseNagle; end; end; procedure TIdIOHandlerSocket.SetUseNagle(AValue: Boolean); begin FUseNagle := AValue; if FBinding <> nil then begin FBinding.UseNagle := AValue; end; end; procedure TIdIOHandlerSocket.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FTransparentProxy) then begin FTransparentProxy := nil; end; inherited Notification(AComponent, Operation); end; procedure TIdIOHandlerSocket.InitComponent; begin inherited InitComponent; FUseNagle := True; FIPVersion := ID_DEFAULT_IP_VERSION; end; function TIdIOHandlerSocket.SourceIsAvailable: Boolean; begin Result := BindingAllocated; end; function TIdIOHandlerSocket.CheckForError(ALastResult: Integer): Integer; begin Result := GStack.CheckForSocketError(ALastResult, [Id_WSAESHUTDOWN, Id_WSAECONNABORTED, Id_WSAECONNRESET]); end; procedure TIdIOHandlerSocket.RaiseError(AError: Integer); begin GStack.RaiseSocketError(AError); end; end.
program folding; type EvalFunc = function (x, y : Integer) : Integer; function Sum(x, y : Integer) : Integer; begin Sum:=x+y; end; function Max(x, y : Integer) : Integer; begin If x < y then Max:=y Else Max:=x; end; function foldl(f : EvalFunc; init : Integer; arr : array of Integer) : Integer; var i, cul : Integer; begin cul:=init; For i:=low(arr) to high(arr) do begin cul:=f(arr[i], cul); end; foldl:=cul; end; function foldr(f : EvalFunc; init : Integer; arr : array of Integer) : Integer; var i, cul : Integer; begin cul:=init; For i:=high(arr) downto low(arr) do begin cul:=f(arr[i], cul); end; foldr:=cul; end; function arraySum(arr : array of Integer) : Integer; begin arraySum:=foldl(@Sum, 0, arr); end; function arrayMax(arr : array of Integer) : Integer; begin arrayMax:=foldr(@Max, arr[high(arr)], arr); end; // var testArray : array [0..5] of Integer; // var s, m, i : Integer; begin // For i := 0 to 5 do // begin // readln(testArray[i]); // end; // s := arraySum(testArray); // m := arrayMax(testArray); // writeln(s); // writeln(m); end.
unit Form.Interval; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Plus.Vcl.Timer, Patterns.Observable, Interval; type TForm1 = class(TForm, IObserver) LabelExampleInfo: TLabel; GroupBox1: TGroupBox; Label1: TLabel; edtStartField: TEdit; Label2: TLabel; edtEndField: TEdit; Label3: TLabel; edtLengthField: TEdit; procedure FormCreate(Sender: TObject); procedure edtStartFieldExit(Sender: TObject); procedure edtEndFieldExit(Sender: TObject); procedure edtLengthFieldExit(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FInterval: TInterval; procedure OnObserverUpdate(AObservable: TObservable; AObject: TObject); procedure _editTextUpdate(edit: TEdit; newValue: integer); procedure _highlightEditAfterUpdate(edit: TEdit); public end; var Form1: TForm1; implementation {$R *.dfm} function Integer_parseInt(const s: String): integer; begin Result := StrToInt(s); end; function IsInteger(const s: String): boolean; var i: integer; begin Result := TryStrToInt(s, i); end; procedure TForm1.FormCreate(Sender: TObject); begin FInterval := TInterval.Create; FInterval.addObserver(Self); with FInterval do begin MinValue := 1; MaxValue := 8; end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin FInterval.Free; end; procedure TForm1._highlightEditAfterUpdate(edit: TEdit); begin edit.Color := clMoneyGreen; TPlusTimer.RunOnce(Self, 500, procedure begin edit.Color := clWindow; end); end; procedure TForm1._editTextUpdate(edit: TEdit; newValue: integer); begin if edit.Text <> newValue.ToString then begin edit.Text := newValue.ToString; _highlightEditAfterUpdate(edit); end; end; procedure TForm1.OnObserverUpdate(AObservable: TObservable; AObject: TObject); begin _editTextUpdate(edtStartField, FInterval.MinValue); _editTextUpdate(edtEndField, FInterval.MaxValue); _editTextUpdate(edtLengthField, FInterval.Length); end; procedure TForm1.edtStartFieldExit(Sender: TObject); begin FInterval.MinValue := IfThen(IsInteger(edtStartField.Text), Integer_parseInt(edtStartField.Text), 0); end; procedure TForm1.edtEndFieldExit(Sender: TObject); begin FInterval.MaxValue := IfThen(IsInteger(edtEndField.Text), Integer_parseInt(edtEndField.Text), 0); end; procedure TForm1.edtLengthFieldExit(Sender: TObject); begin FInterval.Length := IfThen(IsInteger(edtLengthField.Text), Integer_parseInt(edtLengthField.Text), 0); end; end.
{----------------------------------------------------------------------------- hpp_searchthread (historypp project) Version: 1.0 Created: 05.08.2004 Author: Oxygen [ Description ] Global searching in History++ is performed in background so we have separate thread for doing it. Here it is, all bright and shiny. In this module the thread is declared, also you can find all text searching routines used and all search logic. See TSearchThread and independent SearchText* funcs The results are sent in batches of 500, for every contact. First batch is no more than 50 for fast display. Yeah, all search is CASE-INSENSITIVE (at the time of writing :) [ History ] 1.5 (05.08.2004) First version [ Modifications ] none [ Known Issues ] none Copyright (c) Art Fedorov, 2004 -----------------------------------------------------------------------------} unit hpp_searchthread; interface uses Windows, SysUtils, Controls, Messages, HistoryGrid, Classes, m_GlobalDefs, hpp_global, hpp_events, TntSysUtils; const ST_FIRST_BATCH = 50; ST_BATCH = 500; type PDBArray = ^TDBArray; TDBArray = array[0..ST_BATCH-1] of Integer; TSearchMethod = (smExact, smAnyWord, smAllWords); TSearchThread = class(TThread) private Buffer: TDBArray; BufCount: Integer; FirstBatch: Boolean; CurContact: THandle; CurContactCP: Cardinal; CurProgress: Integer; MaxProgress: Integer; FParentHandle: THandle; FSearchTime: Integer; SearchStart: Integer; SearchWords: array of WideString; FSearchText: WideString; FSearchMethod: TSearchMethod; FSearchProtected: Boolean; procedure GenerateSearchWords; protected function GetContactsCount: Integer; function GetItemsCount(hContact: THandle): Integer; procedure CalcMaxProgress; procedure IncProgress; procedure SetProgress(Progress: Integer); function SearchEvent(DBEvent: THandle): Boolean; procedure SearchContact(Contact: THandle); procedure SendItem(hDBEvent: Integer); procedure SendBatch; procedure Execute; override; procedure DoMessage(Message: DWord; wParam, lParam: DWord); public AllContacts, AllEvents: Integer; constructor Create(CreateSuspended: Boolean); destructor Destroy; override; property SearchProtectedContacts: Boolean read FSearchProtected write FSearchProtected; property SearchText: WideString read FSearchText write FSearchText; property SearchMethod: TSearchMethod read FSearchMethod write FSearchMethod; property SearchTime: Integer read FSearchTime; property ParentHandle: THandle read FParentHandle write FParentHandle; property Terminated; end; const SM_BASE = WM_APP + 421; SM_PREPARE = SM_BASE + 1; // the search is prepared (0,0) SM_PROGRESS = SM_BASE + 2; // report the progress (progress, max) SM_ITEMFOUND = SM_BASE + 3; // (OBSOLETE) item is found (hDBEvent,0) SM_NEXTCONTACT = SM_BASE + 4; // the next contact is searched (hContact, ContactCount) SM_FINISHED = SM_BASE + 5; // search finished (0,0) SM_ITEMSFOUND = SM_BASE + 6; // (NEW) items are found (array of hDBEvent, array size) // helper functions function SearchTextExact(MessageText: WideString; SearchText: WideString): Boolean; function SearchTextAnyWord(MessageText: WideString; SearchWords: array of WideString): Boolean; function SearchTextAllWords(MessageText: WideString; SearchWords: array of WideString): Boolean; implementation uses PassForm; {$I m_database.inc} {$I m_icq.inc} function SearchTextExact(MessageText: WideString; SearchText: WideString): Boolean; begin Result := Pos(SearchText, MessageText) <> 0; end; function SearchTextAnyWord(MessageText: WideString; SearchWords: array of WideString): Boolean; var i: Integer; begin Result := False; for i := 0 to Length(SearchWords)-1 do begin Result := SearchTextExact(MessageText,SearchWords[i]); if Result then exit; end; end; function SearchTextAllWords(MessageText: WideString; SearchWords: array of WideString): Boolean; var i: Integer; begin Result := False; for i := 0 to Length(SearchWords)-1 do begin Result := SearchTextExact(MessageText,SearchWords[i]); if not Result then exit; end; end; { TSearchThread } procedure TSearchThread.CalcMaxProgress; var hCont: THandle; begin MaxProgress := 0; hCont := PluginLink.CallService(MS_DB_CONTACT_FINDFIRST,0,0); while hCont <> 0 do begin // I hope I haven't messed this up by // if yes, also fix the same in Execute if SearchProtectedContacts or (not SearchProtectedContacts and (not IsUserProtected(hCont))) then MaxProgress := MaxProgress + GetItemsCount(hCont); hCont := PluginLink.CallService(MS_DB_CONTACT_FINDNEXT,hCont,0); end; // add sysem history MaxProgress := MaxProgress + GetItemsCount(hCont); end; constructor TSearchThread.Create(CreateSuspended: Boolean); begin inherited Create(CreateSuspended); AllContacts := 0; AllEvents := 0; SearchMethod := smExact; SearchProtectedContacts := True; end; destructor TSearchThread.Destroy; begin SetLength(SearchWords,0); inherited; end; procedure TSearchThread.DoMessage(Message, wParam, lParam: DWord); begin PostMessage(ParentHandle,Message,wParam,lParam); end; procedure TSearchThread.Execute; var hCont: THandle; begin BufCount := 0; FirstBatch := True; try SearchStart := GetTickCount; DoMessage(SM_PREPARE,0,0); CalcMaxProgress; SetProgress(0); // make it case-insensitive SearchText := Tnt_WideUpperCase(SearchText); if SearchMethod in [smAnyWord, smAllWords] then GenerateSearchWords; hCont := PluginLink.CallService(MS_DB_CONTACT_FINDFIRST,0,0); while hCont <> 0 do begin Inc(AllContacts); // I hope I haven't messed this up by // if yes, also fix the same in CalcMaxProgress if SearchProtectedContacts or (not SearchProtectedContacts and (not IsUserProtected(hCont))) then SearchContact(hCont); hCont := PluginLink.CallService(MS_DB_CONTACT_FINDNEXT,hCont,0); end; SearchContact(hCont); finally FSearchTime := GetTickCount - SearchStart; // only Post..., not Send... because we wait for this thread // to die in this message PostMessage(ParentHandle,SM_FINISHED,0,0); end; end; procedure TSearchThread.GenerateSearchWords; var n: Integer; st: WideString; begin SetLength(SearchWords,0); st := SearchText; n := Pos(' ',st); while n > 0 do begin if n > 1 then begin SetLength(SearchWords,Length(SearchWords)+1); SearchWords[High(SearchWords)] := Copy(st,1,n-1); end; Delete(st,1,n); n := Pos(' ',st); end; if st <> '' then begin SetLength(SearchWords,Length(SearchWords)+1); SearchWords[High(SearchWords)] := st; end; end; function TSearchThread.GetContactsCount: Integer; begin Result := PluginLink.CallService(MS_DB_CONTACT_GETCOUNT,0,0); end; function TSearchThread.GetItemsCount(hContact: THandle): Integer; begin Result := PluginLink.CallService(MS_DB_EVENT_GETCOUNT,hContact,0); end; procedure TSearchThread.IncProgress; begin SetProgress(CurProgress+1); end; procedure TSearchThread.SearchContact(Contact: THandle); var hDBEvent: THandle; begin CurContactCP := CP_ACP; CurContact := Contact; DoMessage(SM_NEXTCONTACT, Contact, GetContactsCount); hDbEvent:=PluginLink.CallService(MS_DB_EVENT_FINDLAST,Contact,0); while hDBEvent <> 0 do begin if SearchEvent(hDBEvent) then begin SendItem(hDBEvent); end; hDbEvent:=PluginLink.CallService(MS_DB_EVENT_FINDPREV,hDBEvent,0); end; SendBatch; end; function TSearchThread.SearchEvent(DBEvent: THandle): Boolean; var hi: THistoryItem; begin //Sleep(50); Inc(AllEvents); if Terminated then raise EAbort.Create('Thread terminated'); hi := ReadEvent(DBEvent, CurContactCP); case SearchMethod of smAnyWord: Result := SearchTextAnyWord(Tnt_WideUpperCase(hi.Text),SearchWords); smAllWords: Result := SearchTextAllWords(Tnt_WideUpperCase(hi.Text),SearchWords) else // smExact Result := SearchTextExact(Tnt_WideUpperCase(hi.Text),SearchText); end; IncProgress; end; procedure TSearchThread.SendItem(hDBEvent: Integer); var CurBuf: Integer; begin //DoMessage(SM_ITEMFOUND,hDBEvent,0); Inc(BufCount); if FirstBatch then CurBuf := ST_FIRST_BATCH else CurBuf := ST_BATCH; Buffer[BufCount-1] := hDBEvent; if BufCount = CurBuf then begin SendBatch; end; end; procedure TSearchThread.SendBatch; var Batch: PDBArray; begin if BufCount > 0 then begin GetMem(Batch,SizeOf(Batch^)); CopyMemory(Batch,@Buffer,SizeOf(Buffer)); DoMessage(SM_ITEMSFOUND,DWord(Batch),DWord(BufCount)); BufCount := 0; FirstBatch := False; end; end; procedure TSearchThread.SetProgress(Progress: Integer); begin CurProgress := Progress; if CurProgress > MaxProgress then MaxProgress := CurProgress; if (CurProgress mod 1000 = 0) or (CurProgress = MaxProgress) then DoMessage(SM_PROGRESS,CurProgress,MaxProgress); end; end.
unit XMLModel; {*************************************************************************} { } { Hitsoft Xml Object Library } { } { Copyright (C) 2009 Hitsoft LLC. (http://opensource.hitsoft-it.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 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/>. } { } {*************************************************************************} interface uses RttiClasses; type TRealEnabled = class(TRttiEnabled) private FValue: Real; published property Value : Real read FValue write FValue; end; TRealEnabledArray = array of TRealEnabled; TSubNode = class(TRttiEnabled) private FHello: string; published property Hello : string read FHello write FHello; end; TDemoModel = class(TRttiEnabled) private FNumber: Integer; FCaption: string; FBirthday: TDateTime; FPrice: Currency; FIntervals: TRealEnabledArray;//array of real FSubNode: TSubNode; public procedure InsertInterval(Value: Real); published property Number : Integer read FNumber write FNumber; property Caption : string read FCaption write FCaption; property Birthday : TDateTime read FBirthday write FBirthday; property Price : Currency read FPrice write FPrice; property Intervals : TRealEnabledArray read FIntervals write FIntervals; property SubNode : TSubNode read FSubNode write FSubNode; end; implementation { TDemoModel } procedure TDemoModel.InsertInterval(Value: Real); begin SetLength(FIntervals, Length(FIntervals) + 1); FIntervals[High(FIntervals)] := TRealEnabled.Create; FIntervals[High(FIntervals)].Value := Value; 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 uTaskbar; interface uses SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, XLib, uWMConsts, uXPTaskbar; type TTaskbar = class(TForm) procedure FormCreate(Sender: TObject); procedure startbuttonDblClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public ataskbar: TXPTaskbar; { Public declarations } procedure addwindowtotray(const w: window); procedure removewindowfromtray(const w: window); procedure addtask(const client:IWMClient); procedure updatetask(const task:IWMClient); procedure activatetask(const task:IWMClient); procedure removetask(const task:IWMClient); function getRect:TRect; end; var taskbar: Ttaskbar; implementation { TODO : Use theme directories for the several images that make up the taskbar } {$R *.xfm} procedure Ttaskbar.FormCreate(Sender: TObject); begin height:=29; left:=0; top:=qforms.screen.Height-height; width:=qforms.screen.width; ataskbar:=TXPTaskbar.create(self); ataskbar.align:=alClient; ataskbar.Parent:=self; end; procedure Ttaskbar.startbuttonDblClick(Sender: TObject); begin application.Terminate; end; procedure TTaskbar.activatetask(const task: IWMClient); begin ataskbar.activatetask(task); end; procedure TTaskbar.addtask(const client: IWMClient); begin ataskbar.addtask(client); end; procedure TTaskbar.addwindowtotray(const w: window); begin end; function TTaskbar.getRect: TRect; begin result:=boundsrect; end; procedure TTaskbar.removetask(const task: IWMClient); begin ataskbar.removetask(task); end; procedure TTaskbar.removewindowfromtray(const w: window); begin end; procedure TTaskbar.updatetask(const task: IWMClient); begin ataskbar.updatetask(task); end; procedure TTaskbar.FormShow(Sender: TObject); begin bringtofront; end; end.
unit uClimateSpiralUtils; interface uses System.UITypes; function GetViridisColor(APercent: Single): TAlphaColor; function Map(AValue, AInputMin, AInputMax, AOutputMin, AOutputMax: Double): Double; forward; const FEdHawkinsGrey = $FF424242; FEdHawkinsWhite = $FFD6D6D6; VIRIDIS_HEX_DATA: array of TAlphaColor = [ $FF440154, $FF440256, $FF450457, $FF450559, $FF46075A, $FF46085C, $FF460A5D, $FF460B5E, $FF470D60, $FF470E61, $FF471063, $FF471164, $FF471365, $FF481467, $FF481668, $FF481769, $FF48186A, $FF481A6C, $FF481B6D, $FF481C6E, $FF481D6F, $FF481F70, $FF482071, $FF482173, $FF482374, $FF482475, $FF482576, $FF482677, $FF482878, $FF482979, $FF472A7A, $FF472C7A, $FF472D7B, $FF472E7C, $FF472F7D, $FF46307E, $FF46327E, $FF46337F, $FF463480, $FF453581, $FF453781, $FF453882, $FF443983, $FF443A83, $FF443B84, $FF433D84, $FF433E85, $FF423F85, $FF424086, $FF424186, $FF414287, $FF414487, $FF404588, $FF404688, $FF3F4788, $FF3F4889, $FF3E4989, $FF3E4A89, $FF3E4C8A, $FF3D4D8A, $FF3D4E8A, $FF3C4F8A, $FF3C508B, $FF3B518B, $FF3B528B, $FF3A538B, $FF3A548C, $FF39558C, $FF39568C, $FF38588C, $FF38598C, $FF375A8C, $FF375B8D, $FF365C8D, $FF365D8D, $FF355E8D, $FF355F8D, $FF34608D, $FF34618D, $FF33628D, $FF33638D, $FF32648E, $FF32658E, $FF31668E, $FF31678E, $FF31688E, $FF30698E, $FF306A8E, $FF2F6B8E, $FF2F6C8E, $FF2E6D8E, $FF2E6E8E, $FF2E6F8E, $FF2D708E, $FF2D718E, $FF2C718E, $FF2C728E, $FF2C738E, $FF2B748E, $FF2B758E, $FF2A768E, $FF2A778E, $FF2A788E, $FF29798E, $FF297A8E, $FF297B8E, $FF287C8E, $FF287D8E, $FF277E8E, $FF277F8E, $FF27808E, $FF26818E, $FF26828E, $FF26828E, $FF25838E, $FF25848E, $FF25858E, $FF24868E, $FF24878E, $FF23888E, $FF23898E, $FF238A8D, $FF228B8D, $FF228C8D, $FF228D8D, $FF218E8D, $FF218F8D, $FF21908D, $FF21918C, $FF20928C, $FF20928C, $FF20938C, $FF1F948C, $FF1F958B, $FF1F968B, $FF1F978B, $FF1F988B, $FF1F998A, $FF1F9A8A, $FF1E9B8A, $FF1E9C89, $FF1E9D89, $FF1F9E89, $FF1F9F88, $FF1FA088, $FF1FA188, $FF1FA187, $FF1FA287, $FF20A386, $FF20A486, $FF21A585, $FF21A685, $FF22A785, $FF22A884, $FF23A983, $FF24AA83, $FF25AB82, $FF25AC82, $FF26AD81, $FF27AD81, $FF28AE80, $FF29AF7F, $FF2AB07F, $FF2CB17E, $FF2DB27D, $FF2EB37C, $FF2FB47C, $FF31B57B, $FF32B67A, $FF34B679, $FF35B779, $FF37B878, $FF38B977, $FF3ABA76, $FF3BBB75, $FF3DBC74, $FF3FBC73, $FF40BD72, $FF42BE71, $FF44BF70, $FF46C06F, $FF48C16E, $FF4AC16D, $FF4CC26C, $FF4EC36B, $FF50C46A, $FF52C569, $FF54C568, $FF56C667, $FF58C765, $FF5AC864, $FF5CC863, $FF5EC962, $FF60CA60, $FF63CB5F, $FF65CB5E, $FF67CC5C, $FF69CD5B, $FF6CCD5A, $FF6ECE58, $FF70CF57, $FF73D056, $FF75D054, $FF77D153, $FF7AD151, $FF7CD250, $FF7FD34E, $FF81D34D, $FF84D44B, $FF86D549, $FF89D548, $FF8BD646, $FF8ED645, $FF90D743, $FF93D741, $FF95D840, $FF98D83E, $FF9BD93C, $FF9DD93B, $FFA0DA39, $FFA2DA37, $FFA5DB36, $FFA8DB34, $FFAADC32, $FFADDC30, $FFB0DD2F, $FFB2DD2D, $FFB5DE2B, $FFB8DE29, $FFBADE28, $FFBDDF26, $FFC0DF25, $FFC2DF23, $FFC5E021, $FFC8E020, $FFCAE11F, $FFCDE11D, $FFD0E11C, $FFD2E21B, $FFD5E21A, $FFD8E219, $FFDAE319, $FFDDE318, $FFDFE318, $FFE2E418, $FFE5E419, $FFE7E419, $FFEAE51A, $FFECE51B, $FFEFE51C, $FFF1E51D, $FFF4E61E, $FFF6E620, $FFF8E621, $FFFBE723, $FFFDE725 ]; implementation // ---------------------------------------------------------------------------- function GetViridisColor(APercent: Single): TAlphaColor; var LIndex: Integer; begin LIndex := Round(Map(APercent, 0, 100, 0, Length(VIRIDIS_HEX_DATA) - 1)); Result := VIRIDIS_HEX_DATA[LIndex]; end; // ---------------------------------------------------------------------------- // Delphi implementation of Processing's Map() function // https://processing.org/reference/map_.html function Map(AValue, AInputMin, AInputMax, AOutputMin, AOutputMax: Double): Double; begin Result := AOutputMin + (AOutputMax - AOutputMin) * ((AValue - AInputMin) / (AInputMax - AInputMin)); end; end.
unit SelectCategory; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, dcEdit, AdvGrid, FFSAdvStringGrid, Grids, dcEditBtn, sBitBtn, AdvUtil, AdvObj, BaseGrid; type TfrmSelectCategory = class(TForm) grdCats: TFFSAdvStringGrid; btnOk: TsBitBtn; btnCancel: TsBitBtn; procedure FormShow(Sender: TObject); procedure grdTrackDblClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure grdCatsMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure grdCatsMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); private FSelectedCategory: string; CatCount : integer; { Private declarations } public property SelectedCategory:string read FSelectedCategory; end; function DlgSelectCategory(fld:TdcEditBtn):boolean; implementation uses datamod, TicklerGlobals; {$R *.DFM} function DlgSelectCategory(fld:TdcEditbtn):boolean; var frmSelectCategory: TfrmSelectCategory; begin Result := false; frmSelectCategory := TfrmSelectCategory.Create(nil); try if frmSelectCategory.showmodal = mrOk then begin fld.Text := frmSelectCategory.SelectedCategory; Result := true; end; finally frmSelectCategory.Release; end; end; procedure TfrmSelectCategory.FormShow(Sender: TObject); var sl : TStringList; x : integer; begin FSelectedCategory := ''; sl := TStringList.create; daapi.TrakGetCodeDescList(CurrentLend.Number, sl); grdCats.LoadFromCSVStringList(sl); btnOk.Enabled := sl.count > 0; catcount := sl.count; sl.free; grdCats.FitLastColumn; end; procedure TfrmSelectCategory.grdTrackDblClick(Sender: TObject); begin btnOk.Click; end; procedure TfrmSelectCategory.btnOkClick(Sender: TObject); begin if catcount = 0 then exit; FSelectedCategory := trim(grdcats.Cells[0,grdCats.row]); ModalResult := mrOk; end; procedure TfrmSelectCategory.grdCatsMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdCats.SetFocus; end; procedure TfrmSelectCategory.grdCatsMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin grdCats.SetFocus; end; end.
unit uTipoController; interface uses System.SysUtils, uDMTipo, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uTipoVO, uConverter; type TTipoController = class private FModel: TDMTipo; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure FiltrarPrograma(ATipoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer); overload; procedure LocalizarCodigo(ACodigo: integer; ATipoPrograma: TEnumPrograma); overload; procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); procedure Salvar(AIdUsuario: Integer); procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, ACodigo: Integer); overload; procedure Pesquisar(AId, ACodigo: Integer; ATipoPrograma: TEnumPrograma); overload; function CodigoAtual: Integer; function RetornoUmRegistro(APrograma: TEnumPrograma): TTipoVO; property Model: TDMTipo read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TTipoController } uses uFuncoesSIDomper; procedure TTipoController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TTipoController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroTip_Codigo.AsInteger; end; constructor TTipoController.Create; begin inherited Create; FModel := TDMTipo.Create(nil); end; destructor TTipoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TTipoController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerMethods1Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CTipoPrograma, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerMethods1Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CTipoPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.Filtrar(CTipoPrograma, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CTipoPrograma, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.FiltrarPrograma(ATipoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerMethods1Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try iEnum := Integer(ATipoPrograma); FModel.CDSConsulta.Close; Negocio.FiltrarTipoPrograma(ACampo, ATexto, AAtivo, iEnum, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.Imprimir(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin dm.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CTipoPrograma, AIdUsuario); FModel.Rel.Print; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CTipoPrograma, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.LocalizarCodigo(ACodigo: integer; ATipoPrograma: TEnumPrograma); var Negocio: TServerMethods1Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try iEnum := integer(ATipoPrograma); FModel.CDSCadastro.Close; Negocio.LocalizarCodigoTipoPrograma(iEnum, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.LocalizarId(AId: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CTipoPrograma, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.Novo(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CTipoPrograma, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSCadastroTip_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.Pesquisar(AId, ACodigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(ACodigo); end; procedure TTipoController.Pesquisar(AId, ACodigo: Integer; ATipoPrograma: TEnumPrograma); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(ACodigo, ATipoPrograma); end; procedure TTipoController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TTipoController.ProximoCodigo: Integer; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := StrToInt(Negocio.ProximoCodigo(CTipoPrograma).ToString); dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TTipoController.ProximoId: Integer; var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Result := StrToInt(Negocio.ProximoId(CTipoPrograma).ToString); dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TTipoController.RetornoUmRegistro(APrograma: TEnumPrograma): TTipoVO; var Negocio: TServerMethods1Client; iPrograma: Integer; Model: TTipoVO; begin iPrograma := Integer(APrograma); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Model := TConverte.JSONToObject<TTipoVO>(Negocio.TipoRetornoUmRegistro(iPrograma)); Result := Model; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TTipoController.Salvar(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin if FModel.CDSCadastroTip_Codigo.AsInteger <= 0 then raise Exception.Create('Informe o Código!'); if Trim(FModel.CDSCadastroTip_Nome.AsString) = '' then raise Exception.Create('Informe o Nome!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try try Post(); Negocio.Salvar(CTipoPrograma, AIdUsuario); FModel.CDSCadastro.ApplyUpdates(0); FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin DM.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Creation: March 2007 Version: 0.99d ALPHA CODE Description: TMultipartHttpDownloader is a component to download files using simultaneous connections to speedup download. The demo make also use of the TMultiProgressBar (included in ICS) which is a segmented progress bar. EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2012 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> 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. Updates: Oct 30, 2010 0.99b In DownloadDocData, fixed call to Seek so that the int64 overloaded version is used. Nov 08, 2010 0.99c Arno improved final exception handling, more details in OverbyteIcsWndControl.pas (V1.14 comments). Oct 17, 2012 0.99d Vladimir Kudelin fixed EDivByZero in TMultipartHttpDownloader.Timer1Timer. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsMultipartHttpDownloader; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFDEF COMPILER2_UP} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} interface uses Windows, Messages, SysUtils, Classes, ExtCtrls, IniFiles, OverbyteIcsHttpProt, OverbyteIcsUrl, OverbyteIcsWndControl; const MultipartHttpDownloaderVersion = 600; CopyRight : String = ' TMultipartHttpDownloader ' + '(c) 2012 F. Piette V6.00 '; type TDisplayEvent = procedure (Sender : TObject; const Msg : String) of object; TRequestDoneEvent = procedure (Sender : TObject; ErrorCode : Integer; const Reason : String) of object; TProgressAddSegmentEvent = procedure (Sender : TObject; StartOffset : Int64; ASpan : Int64; InitPos : Int64) of Object; TProgressSetPositionEvent = procedure (Sender : TObject; Index : Integer; Position : Int64) of object; TMyHttpCli = class(THttpCli) protected FDataCount : THttpBigInt; FDataMax : THttpBigInt; FStartOffset : THttpBigInt; FEndOffset : THttpBigInt; FIndex : Integer; FDone : Boolean; end; TMultipartHttpDownloader = class(TIcsWndControl) protected FHttp : array of TMyHttpCli; FContentLength : THttpBigInt; FPartCount : Integer; FTotalCount : THttpBigInt; FPrevCount : THttpBigInt; FPrevTick : Cardinal; FFileStream : TStream; FStartTime : TDateTime; FElapsedTime : TDateTime; FCurSpeed : Double; FPercentDone : Double; FURL : String; FUsername : String; FPassword : String; FProxy : String; FProxyPort : String; FSocksServer : String; FSocksLevel : String; FSocksPort : String; FServerAuth : THttpAuthType; FProxyAuth : THttpAuthType; FProgressCaption : String; FAbortFlag : Boolean; FPauseFlag : Boolean; FStateFileName : String; FOnDisplay : TDisplayEvent; FOnRequestDone : TRequestDoneEvent; FOnProgressAddSegment : TProgressAddSegmentEvent; FOnProgressSetPosition : TProgressSetPositionEvent; FOnShowStats : TNotifyEvent; FMsg_WM_START_MULTI : UINT; Timer1 : TIcsTimer; procedure AbortComponent; override; { 0.99c } procedure AllocateMsgHandlers; override; procedure FreeMsgHandlers; override; function MsgHandlersCount: Integer; override; procedure GetASyncRequestDone(Sender : TObject; Request : THttpRequest; ErrorCode : Word); procedure GetAsyncHeaderEnd(Sender : TObject); procedure Display(const Msg : String); procedure WMStartMulti(var Msg: TMessage); procedure WndProc(var MsgRec: TMessage); override; procedure DownloadRequestDone(Sender : TObject; Request : THttpRequest; ErrorCode : Word); procedure DownloadDocData(Sender : TObject; Data : Pointer; Len : Integer); procedure CheckDone(ErrCode : Integer; const Reason : String); procedure LocationChange(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure RestartDownload(MyHttp : TMyHttpCli); procedure TriggerShowStats; virtual; procedure TriggerProgressSetPosition(Index : Integer; Position : Int64); virtual; procedure TriggerProgressAddSegment(StartOffset, ASpan, InitPos: Int64); virtual; procedure LoadStatus; procedure SaveStatus; procedure SetStateFileName(const Value: String); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Start; procedure Abort; procedure Pause; procedure Resume; property TotalCount : THttpBigInt read FTotalCount; property ContentLength : THttpBigInt read FContentLength; property CurSpeed : Double read FCurSpeed; property ElapsedTime : TDateTime read FElapsedTime; property PercentDone : Double read FPercentDone; published property OnBgException; { 0.99c } property URL : String read FURL write FURL; property Username : String read FUsername write FUsername; property Password : String read FPassword write FPassword; property Proxy : String read FProxy write FProxy; property ProxyPort : String read FProxyPort write FProxyPort; property SocksServer : String read FSocksServer write FSocksServer; property SocksPort : String read FSocksPort write FSocksPort; property SocksLevel : String read FSocksLevel write FSocksLevel; property PartCount : Integer read FPartCount write FPartCount; property FileStream : TStream read FFileStream write FFileStream; property ServerAuth : THttpAuthType read FServerAuth write FServerAuth; property ProxyAuth : THttpAuthType read FProxyAuth write FProxyAuth; property StateFileName : String read FStateFileName write SetStateFileName; property OnDisplay : TDisplayEvent read FOnDisplay write FOnDisplay; property OnRequestDone : TRequestDoneEvent read FOnRequestDone write FOnRequestDone; property OnProgressAddSegment : TProgressAddSegmentEvent read FOnProgressAddSegment write FOnProgressAddSegment; property OnProgressSetPosition : TProgressSetPositionEvent read FOnProgressSetPosition write FOnProgressSetPosition; property OnShowStats : TNotifyEvent read FOnShowStats write FOnShowStats; end; implementation const SectionData = 'Data'; KeyPart = 'Part'; KeyUrl = 'Url'; KeyPartCount = 'PartCount'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TMultipartHttpDownloader.Create(AOwner: TComponent); begin inherited Create(AOwner); AllocateHWnd; Timer1 := TIcsTimer.Create(Self); Timer1.Enabled := FALSE; Timer1.Interval := 1000; Timer1.OnTimer := Timer1Timer; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TMultipartHttpDownloader.Destroy; var I : Integer; begin for I := 0 to Length(FHttp) - 1 do FreeAndNil(FHttp[I]); SetLength(FHttp, 0); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.Display(const Msg: String); begin if Assigned(FOnDisplay) then FOnDisplay(Self, Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.Start; var I : Integer; begin if FPartCount <= 1 then raise ERangeError.Create('PartCount must be positive'); FAbortFlag := FALSE; FPauseFlag := FALSE; FContentLength := 0; FTotalCount := 0; FPrevCount := 0; FPrevTick := GetTickCount; FStartTime := Now; FElapsedTime := 0; TriggerShowStats; for I := 0 to Length(FHttp) - 1 do FreeAndNil(FHttp[I]); SetLength(FHttp, 1); FHttp[0] := TMyHttpCli.Create(Self); FHttp[0].FIndex := 0; FHttp[0].URL := FURL; FHttp[0].Username := FUsername; FHttp[0].Password := FPassword; FHttp[0].Proxy := FProxy; FHttp[0].ProxyPort := FProxyPort; FHttp[0].SocksServer := FSocksServer; FHttp[0].SocksPort := FSocksPort; FHttp[0].SocksLevel := FSocksLevel; FHttp[0].OnRequestDone := GetASyncRequestDone; FHttp[0].OnHeaderEnd := GetAsyncHeaderEnd; FHttp[0].OnBgException := OnBgException; { 0.99c } FHttp[0].ExceptAbortProc := AbortComponent; { 0.99c } FHttp[0].ServerAuth := FServerAuth; FHttp[0].GetASync; Display('GetASync'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.GetASyncRequestDone( Sender : TObject; Request : THttpRequest; ErrorCode : Word); var HttpCli : TMyHttpCli; begin Display('GetASyncRequestDone'); if FContentLength > 0 then begin // We are happy with a document to get PostMessage(Handle, FMsg_WM_START_MULTI, 0, 0); Exit; end; HttpCli := Sender as TMyHttpCli; if ErrorCode <> 0 then begin Display('ErrorCode = ' + IntToStr(ErrorCode)); if Assigned(FOnRequestDone) then FOnrequestDone(Self, ErrorCode, 'Download failed'); Exit; end; if HttpCli.StatusCode <> 200 then begin Display('StatusCode = ' + IntToStr(HttpCli.StatusCode) + ' ' + HttpCli.ReasonPhrase); if Assigned(FOnRequestDone) then FOnrequestDone(Self, HttpCli.StatusCode, HttpCli.ReasonPhrase); Exit; end; Display('RequestDone DataCount = ' + IntToStr(HttpCli.FDataCount)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.GetAsyncHeaderEnd(Sender: TObject); var HttpCli : TMyHttpCli; begin HttpCli := Sender as TMyHttpCli; if HttpCli.ContentLength > 0 then begin Display('HeaderEnd ContentLength = ' + IntToStr(HttpCli.ContentLength)); Display('HeaderEnd AcceptRanges = ' + HttpCli.AcceptRanges); Display('HeaderEnd DocName = ' + UrlDecode(HttpCli.DocName)); end; Display('HeaderEnd StatusCode = ' + IntToStr(HttpCli.StatusCode) + ' ' + HttpCli.ReasonPhrase ); if HttpCli.StatusCode <> 200 then Exit; FContentLength := HttpCli.ContentLength; TriggerShowStats; HttpCli.Abort; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.LocationChange(Sender: TObject); var HttpCli : TMyHttpCli; begin HttpCli := TMyHttpCli(Sender); Display('LocationChange = ' + HttpCli.Location); HttpCli.ContentRangeBegin := IntToStr(HttpCli.FStartOffset + HttpCli.FDataCount); HttpCli.ContentRangeEnd := IntToStr(HttpCli.FEndOffset); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TMultipartHttpDownloader.MsgHandlersCount : Integer; begin Result := 1 + inherited MsgHandlersCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.AllocateMsgHandlers; begin inherited AllocateMsgHandlers; FMsg_WM_START_MULTI := FWndHandler.AllocateMsgHandler(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.FreeMsgHandlers; begin if Assigned(FWndHandler) then begin FWndHandler.UnregisterMessage(FMsg_WM_START_MULTI); end; inherited FreeMsgHandlers; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.WndProc(var MsgRec: TMessage); begin try { 0.99c } with MsgRec do begin if Msg = FMsg_WM_START_MULTI then WMStartMulti(MsgRec) else inherited WndProc(MsgRec); end; except { 0.99c } on E: Exception do HandleBackGroundException(E); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.WMStartMulti(var msg: TMessage); var Chunk : THttpBigInt; Offset : THttpBigInt; I : Integer; MyHttp : TMyHttpCli; begin Chunk := FContentLength div FPartCount; Offset := 0; SetLength(FHttp, FPartCount); for I := 0 to FPartCount - 1 do begin if I > 0 then begin // First component already created ! FHttp[I] := TMyHttpCli.Create(Self); end else FHttp[I].OnHeaderEnd := nil; MyHttp := FHttp[I]; MyHttp.FStartOffset := Offset; if I < (FPartCount - 1) then MyHttp.FEndOffset := Offset + Chunk else MyHttp.FEndOffset := FContentLength; Offset := Offset + Chunk + 1; MyHttp.ContentRangeBegin := IntToStr(MyHttp.FStartOffset); MyHttp.ContentRangeEnd := IntToStr(MyHttp.FEndOffset); TriggerProgressAddSegment(MyHttp.FStartOffset, MyHttp.FEndOffset - MyHttp.FStartOffset, MyHttp.FStartOffset); MyHttp.FIndex := I; MyHttp.URL := FURL; MyHttp.Username := FUsername; MyHttp.Password := FPassword; MyHttp.Proxy := FProxy; MyHttp.ProxyPort := FProxyPort; MyHttp.SocksServer := FSocksServer; MyHttp.SocksPort := FSocksPort; MyHttp.SocksLevel := FSocksLevel; MyHttp.OnLocationChange := LocationChange; MyHttp.OnRequestDone := DownloadRequestDone; MyHttp.OnDocData := DownloadDocData; MyHttp.OnBgException := OnBgException; { 0.99c } MyHttp.ExceptAbortProc := AbortComponent; { 0.99c } MyHttp.ServerAuth := FServerAuth; MyHttp.FDataCount := 0; MyHttp.FDone := FALSE; //ListBox1.Items.Add('0'); end; for I := 0 to Length(FHttp) - 1 do FHttp[I].GetASync; Timer1.Enabled := TRUE; Display('GetASync'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.LoadStatus; const Default = '0'; var SectionNames : TStringList; Cnt : Integer; I : Integer; MyHttp : TMyHttpCli; IniFile : TIniFile; //Dls : TDownloadState; begin for I := 0 to Length(FHttp) - 1 do FreeAndNil(FHttp[I]); SetLength(FHttp, 0); FTotalCount := 0; IniFile := TIniFile.Create(FStateFileName); try //FFileName := IniFile.ReadString('GLOBAL', 'FileName', ''); FContentLength := StrToInt64Def(IniFile.ReadString('GLOBAL', 'ContentLength', Default), 0); FUrl := IniFile.ReadString('GLOBAL', 'Url', ''); FPartCount := IniFile.ReadInteger('GLOBAL', 'PartCount', 1); SetLength(FHttp, FPartCount); if FPartCount > 0 then begin SectionNames := TStringList.Create; try IniFile.ReadSections(SectionNames); for I := 0 to SectionNames.Count - 1 do begin if Copy(SectionNames[I], 1, 5) <> 'PART_' then Continue; Cnt := StrToInt(Copy(SectionNames[I], 6, 8)); FHttp[Cnt] := TMyHttpCli.Create(Self); MyHttp := FHttp[Cnt]; MyHttp.FIndex := Cnt; MyHttp.FStartOffset := StrToInt64Def(IniFile.ReadString(SectionNames[I], 'StartOffset', Default), 0); MyHttp.FEndOffset := StrToInt64Def(IniFile.ReadString(SectionNames[I], 'EndOffset', Default), 0); MyHttp.FDataCount := StrToInt64Def(IniFile.ReadString(SectionNames[I], 'DataCount', Default), 0); // MyHttp.FDone := IniFile.ReadBool(SectionNames[I], 'Done', FALSE); MyHttp.URL := IniFile.ReadString(SectionNames[I], 'URL', ''); MyHttp.OnLocationChange := LocationChange; MyHttp.OnRequestDone := DownloadRequestDone; MyHttp.OnDocData := DownloadDocData; MyHttp.ServerAuth := FServerAuth; Inc(FTotalCount, MyHttp.FDataCount); end; FPrevCount := FTotalCount; FPrevTick := GetTickCount; FStartTime := Now; FElapsedTime := 0; finally FreeAndNil(SectionNames); end; end; finally FreeAndNil(IniFile); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.SaveStatus; var SectionNames : TStringList; I : Integer; IniFile : TIniFile; begin IniFile := TIniFile.Create(FStateFileName); try SectionNames := TStringList.Create; try IniFile.ReadSections(SectionNames); for I := 0 to SectionNames.Count - 1 do begin if Copy(SectionNames[I], 1, 5) = 'PART_' then IniFile.EraseSection(SectionNames[I]); end; finally FreeAndNil(SectionNames); end; IniFile.EraseSection('GLOBAL'); IniFile.WriteString('GLOBAL', 'Url', FUrl); IniFile.WriteString('GLOBAL', 'ContentLength', IntToStr(FContentLength)); IniFile.WriteInteger('GLOBAL', 'PartCount', Length(FHttp)); for I := 0 to Length(FHttp) - 1 do begin IniFile.WriteString('PART_' + IntToStr(I), 'StartOffset', IntToStr(FHttp[I].FStartOffset)); IniFile.WriteString('PART_' + IntToStr(I), 'EndOffset', IntToStr(FHttp[I].FEndOffset)); IniFile.WriteString('PART_' + IntToStr(I), 'DataCount', IntToStr(FHttp[I].FDataCount)); // IniFile.WriteBool('PART_' + IntToStr(I), 'Done', FHttp[I].FDone); IniFile.WriteString('PART_' + IntToStr(I), 'URL', FHttp[I].URL); FHttp[I].FDone := (FHttp[I].FDataCount >= (FHttp[I].FEndOffset - FHttp[I].FStartOffset)); end; finally FreeAndNil(IniFile); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.DownloadRequestDone( Sender : TObject; Request : THttpRequest; ErrorCode : Word); var HttpCli : TMyHttpCli; ErrCode : Integer; Reason : String; begin HttpCli := Sender as TMyHttpCli; HttpCli.FDone := TRUE; if FAbortFlag then begin // We are aborting transfert, just ignore any error Display('Download done index = ' + IntToStr(HttpCli.FIndex) + ' Aborted'); ErrCode := 503; // 503 is service unavailable Reason := 'Transfert aborted'; end else if FPauseFlag then begin // We are aborting transfert, just ignore any error Display('Download done index = ' + IntToStr(HttpCli.FIndex) + ' Paused'); ErrCode := 204; Reason := 'Transfert paused'; end else begin if ErrorCode <> 0 then begin Display('Download done index = ' + IntToStr(HttpCli.FIndex) + ' ErrorCode = ' + IntToStr(ErrorCode)); RestartDownload(HttpCli); Exit; end else if HttpCli.StatusCode <> 206 then begin Display('Download done index = ' + IntToStr(HttpCli.FIndex) + ' Status = ' + IntToStr(HttpCli.StatusCode)); RestartDownload(HttpCli); Exit; end; Display('Download done index = ' + IntToStr(HttpCli.FIndex) + ' OK'); ErrCode := 200; Reason := 'OK'; end; CheckDone(ErrCode, Reason); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.CheckDone( ErrCode : Integer; const Reason : String); var Done : Boolean; I : Integer; begin Done := TRUE; for I := 0 to Length(FHttp) - 1 do Done := Done and (FHttp[I].FDone); if Done then begin Timer1.Enabled := FALSE; Timer1.OnTimer(nil); Display('All done'); if FPauseFlag then SaveStatus; if Assigned(FOnRequestDone) then FOnrequestDone(Self, ErrCode, Reason); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.DownloadDocData( Sender : TObject; Data : Pointer; Len : Integer); var HttpCli : TMyHttpCli; begin if Len <= 0 then Exit; if FPauseFlag then Exit; HttpCli := Sender as TMyHttpCli; FFilestream.Seek(HttpCli.FStartOffset + HttpCli.FDataCount, soBeginning); // Warning: Using soFromBeginning make sthe compiler pick the 32 bit overload ! FFilestream.WriteBuffer(Data^, Len); HttpCli.FDataCount := HttpCli.FDataCount + Len; FTotalCount := FTotalCount + Len; TriggerProgressSetPosition(HttpCli.FIndex, HttpCli.FStartOffset + HttpCli.FDataCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.TriggerProgressSetPosition( Index : Integer; Position : Int64); begin if Assigned(FOnProgressSetPosition) then FOnProgressSetPosition(Self, Index, Position); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.TriggerProgressAddSegment( StartOffset : Int64; ASpan : Int64; InitPos : Int64); begin if Assigned(FOnProgressAddSegment) then FOnProgressAddSegment(Self, StartOffset, ASpan, InitPos); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.TriggerShowStats; begin if Assigned(FOnShowStats) then FOnShowStats(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.Timer1Timer(Sender: TObject); var HttpCli : TMyHttpCli; I : Integer; Done : Boolean; Tick : Cardinal; begin Done := TRUE; for I := 0 to Length(FHttp) - 1 do begin HttpCli := FHttp[I]; Done := Done and (HttpCli.FDone); //MultipartDownloadForm.ListBox1.Items[HttpCli.FIndex] := IntToStr(HttpCli.FDataCount); end; Tick := GetTickCount; if Tick = FPrevTick then {V0.99d} FCurSpeed := 0 else FCurSpeed := 8 * (FTotalCount - FPrevCount) / (Tick - FPrevTick); FElapsedTime := Now - FStartTime; if FContentLength = 0 then FPercentDone := 0 else FPercentDone := 100.0 * FTotalCount / FContentLength; TriggerShowStats; FPrevTick := Tick; FPrevCount := FTotalCount; if not Done then Exit; // Download is finished Timer1.Enabled := FALSE; FCurSpeed := 8 * FTotalCount / (FElapsedTime * 86400000); TriggerShowStats; FreeAndNil(FFilestream); Display('Done'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.RestartDownload(MyHttp : TMyHttpCli); begin Display('Restarting ' + IntToStr(MyHttp.FIndex)); TriggerProgressSetPosition(MyHttp.FIndex, MyHttp.FStartOffset); MyHttp.ContentRangeBegin := IntToStr(MyHttp.FStartOffset); MyHttp.ContentRangeEnd := IntToStr(MyHttp.FEndOffset); MyHttp.Username := FUsername; MyHttp.Password := FPassword; MyHttp.Proxy := FProxy; MyHttp.ProxyPort := FProxyPort; MyHttp.SocksServer := FSocksServer; MyHttp.SocksPort := FSocksPort; MyHttp.SocksLevel := FSocksLevel; MyHttp.ServerAuth := FServerAuth; MyHttp.FDataCount := 0; MyHttp.FDone := FALSE; MyHttp.GetASync; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.Abort; var HttpCli : TMyHttpCli; I : Integer; begin FAbortFlag := TRUE; for I := 0 to Length(FHttp) - 1 do begin HttpCli := FHttp[I]; HttpCli.Abort; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.Pause; var HttpCli : TMyHttpCli; I : Integer; begin if StateFileName = '' then raise Exception.Create('TMultipartHttpDownloader.Pause: ' + 'No file name specified'); FPauseFlag := TRUE; for I := 0 to Length(FHttp) - 1 do begin HttpCli := FHttp[I]; HttpCli.Abort; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.Resume; var HttpCli : TMyHttpCli; I : Integer; begin if StateFileName = '' then raise Exception.Create('TMultipartHttpDownloader.Resume: ' + 'No file name specified'); FAbortFlag := FALSE; FPauseFlag := FALSE; LoadStatus; for I := 0 to Length(FHttp) - 1 do begin HttpCli := FHttp[I]; HttpCli.Username := FUsername; HttpCli.Password := FPassword; HttpCli.Proxy := FProxy; HttpCli.ProxyPort := FProxyPort; HttpCli.SocksServer := FSocksServer; HttpCli.SocksPort := FSocksPort; HttpCli.SocksLevel := FSocksLevel; HttpCli.ServerAuth := FServerAuth; HttpCli.ContentRangeBegin := IntToStr(HttpCli.FStartOffset + HttpCli.FDataCount); HttpCli.ContentRangeEnd := IntToStr(HttpCli.FEndOffset); Display('Resuming ' + IntToStr(I) + ' Offset=' + HttpCli.ContentRangeBegin + ' DataCount=' + IntToStr(HttpCli.FDataCount)); TriggerProgressAddSegment(HttpCli.FStartOffset, HttpCli.FEndOffset - HttpCli.FStartOffset, HttpCli.FStartOffset + HttpCli.FDataCount); end; // Start all download which is not done yet for I := 0 to Length(FHttp) - 1 do begin if not FHttp[I].FDone then FHttp[I].GetASync; end; Timer1.Enabled := TRUE; CheckDone(0, 'OK'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.SetStateFileName(const Value: String); begin // We use TIniFile which create a file with no path into Windows directory // Add the current directory specifier to the filename if required. if ExtractFilePath(Value) = '' then FStateFileName := '.\' + Value else FStateFileName := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TMultipartHttpDownloader.AbortComponent; { 0.99c } begin try Abort; except end; inherited; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit EquipAttributesForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OkCancel_frame, DB, FIBDataSet, pFIBDataSet, StdCtrls, DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, PrjConst, DBGridEh; type TEquipAttributesForm = class(TForm) OkCancelFrame1: TOkCancelFrame; srcAttributes: TDataSource; dsAttributes: TpFIBDataSet; dbluAttribute: TDBLookupComboboxEh; DBMemo1: TDBMemoEh; Label1: TLabel; lblAttribute: TLabel; Label2: TLabel; dbValue: TDBEditEh; dsAttr: TpFIBDataSet; srcAttr: TDataSource; CnErrors: TCnErrorProvider; cbbList: TDBComboBoxEh; procedure OkCancelFrame1bbOkClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dbluAttributeEnter(Sender: TObject); procedure dbluAttributeChange(Sender: TObject); private FEQID: Integer; public { Public declarations } end; function EditAttribute(const EQID: Integer; const EQ_TYPE: Integer; const Attribut: Integer): boolean; function AttributeIPTV(const IPTV_ID: Integer; const Attribut: Integer): boolean; implementation uses DM, RegularExpressions, pFIBQuery; {$R *.dfm} function EditAttribute(const EQID: Integer; const EQ_TYPE: Integer; const Attribut: Integer): boolean; begin with TEquipAttributesForm.Create(Application) do try FEQID := EQID; dsAttr.SQLs.SelectSQL.Clear; dsAttr.SQLs.SelectSQL.Add(' SELECT A.O_NAME, CA.* FROM equipment_attributes CA '); dsAttr.SQLs.SelectSQL.Add(' INNER JOIN OBJECTS A ON (CA.O_ID = A.O_ID and a.O_Type in (5,6))'); dsAttr.SQLs.SelectSQL.Add(' where CA.eid = :eid and ca.O_ID = :oid '); dsAttr.SQLs.InsertSQL.Text := 'INSERT INTO EQUIPMENT_ATTRIBUTES( EID, O_ID, CA_VALUE, NOTICE ) VALUES(:EID, :O_ID, :CA_VALUE, :NOTICE )'; dsAttr.SQLs.UpdateSQL.Clear; dsAttr.SQLs.UpdateSQL.Add('UPDATE EQUIPMENT_ATTRIBUTES SET EID = :EID, O_ID = :O_ID, CA_VALUE = :CA_VALUE, NOTICE = :NOTICE'); dsAttr.SQLs.UpdateSQL.Add('WHERE EA_ID = :OLD_EA_ID'); dsAttr.ParamByName('EID').AsInt64 := EQID; dsAttr.ParamByName('OID').AsInt64 := Attribut; dsAttr.Open; if Attribut = -1 then begin dsAttr.Insert; dsAttr['EID'] := EQID; dsAttributes.ParamByName('EID').AsInt64 := EQID; end else begin dsAttr.Edit; dbluAttribute.Enabled := false; dsAttributes.ParamByName('EID').AsInt64 := -1; end; case EQ_TYPE of 1: dsAttributes.ParamByName('TYPEEQ').AsInt64 := 5; 2: dsAttributes.ParamByName('TYPEEQ').AsInt64 := 6; end; dsAttributes.Open; if ShowModal = mrOk then begin try dsAttr.Post; result := true; except result := false; end; end else result := false; if dsAttributes.Active then dsAttributes.Close; finally free end; end; function AttributeIPTV(const IPTV_ID: Integer; const Attribut: Integer): boolean; begin with TEquipAttributesForm.Create(Application) do try dsAttributes.SQLs.SelectSQL.Clear; dsAttributes.SQLs.SelectSQL.Add('SELECT O_ID, O_NAME, O_DESCRIPTION, O_DELETED, O_DIMENSION, coalesce(O_CHECK, '''') REGEXP, coalesce(O_CHARFIELD, '''') VLIST'); dsAttributes.SQLs.SelectSQL.Add('FROM OBJECTS o WHERE O_TYPE = :TYPEEQ AND O_DELETED = 0'); dsAttributes.SQLs.SelectSQL.Add('and not exists(select ca.o_id from Iptv_Group_Attributes ca where ca.o_id = o.O_ID and ca.Ig_Id = :Ig_Id)'); dsAttributes.SQLs.SelectSQL.Add('order BY O_NAME'); dsAttr.SQLs.SelectSQL.Clear; dsAttr.SQLs.SelectSQL.Add('SELECT A.O_NAME, CA.* FROM Iptv_Group_Attributes CA'); dsAttr.SQLs.SelectSQL.Add('INNER JOIN OBJECTS A ON (CA.O_ID = A.O_ID and a.O_Type = 32)'); dsAttr.SQLs.SelectSQL.Add('where CA.Ig_Id = :Ig_Id and ca.O_ID = :oid'); dsAttr.SQLs.InsertSQL.Text := 'insert into Iptv_Group_Attributes (Ig_Id, O_Id, Ca_Value, Notice) values (:Ig_Id, :O_Id, :Ca_Value, :Notice)'; dsAttr.SQLs.UpdateSQL.Clear; dsAttr.SQLs.UpdateSQL.Add('update Iptv_Group_Attributes'); dsAttr.SQLs.UpdateSQL.Add('set Ig_Id = :Ig_Id, O_Id = :O_Id, Ca_Value = :Ca_Value, Notice = :Notice'); dsAttr.SQLs.UpdateSQL.Add('where Iga_Id = :OLD_Iga_Id'); dsAttr.ParamByName('Ig_Id').AsInt64 := IPTV_ID; dsAttr.ParamByName('OID').AsInt64 := Attribut; dsAttr.Open; if Attribut = -1 then begin dsAttr.Insert; dsAttr['Ig_Id'] := IPTV_ID; dsAttributes.ParamByName('Ig_Id').AsInt64 := IPTV_ID; end else begin dsAttr.Edit; dbluAttribute.Enabled := false; dsAttributes.ParamByName('Ig_Id').AsInt64 := -1; end; dsAttributes.ParamByName('TYPEEQ').AsInt64 := 32; dsAttributes.Open; if ShowModal = mrOk then begin try dsAttr.Post; result := true; except result := false; end; end else result := false; if dsAttributes.Active then dsAttributes.Close; finally free end; end; procedure TEquipAttributesForm.dbluAttributeChange(Sender: TObject); begin cbbList.Items.Clear; cbbList.KeyItems.Clear; cbbList.Items.Text := dsAttributes['VLIST']; cbbList.KeyItems.Text := dsAttributes['VLIST']; cbbList.Visible := (dsAttributes['VLIST'] <> ''); dbValue.Visible := not cbbList.Visible; end; procedure TEquipAttributesForm.dbluAttributeEnter(Sender: TObject); begin CnErrors.Dispose(dbluAttribute); end; procedure TEquipAttributesForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then ModalResult := mrOk; end; procedure TEquipAttributesForm.OkCancelFrame1bbOkClick(Sender: TObject); var errors: boolean; s, reg: string; fq: TpFIBQuery; begin errors := false; if dbluAttribute.Text = '' then begin CnErrors.SetError(dbluAttribute, rsSelectAttribute, iaMiddleLeft, bsNeverBlink); errors := true; end else CnErrors.Dispose(dbluAttribute); if ((dbluAttribute.Text <> '')) then begin if dbValue.Visible then begin if dsAttributes['REGEXP'] <> '' then begin s := dbValue.Text; reg := '^' + dsAttributes['REGEXP'] + '$'; errors := not TRegEx.IsMatch(s, reg); if errors then CnErrors.SetError(dbValue, rsInputIncorrect, iaMiddleLeft, bsNeverBlink) else CnErrors.Dispose(dbValue); end end else begin if cbbList.Text = '' then begin CnErrors.SetError(cbbList, rsInputIncorrect, iaMiddleLeft, bsNeverBlink); errors := true; end else CnErrors.Dispose(cbbList); end; end; if (dsAttributes['O_UNIQ'] = 1) then begin fq := TpFIBQuery.Create(Self); try fq.Database := dmMain.dbTV; fq.Transaction := dmMain.trReadQ; with fq.sql do begin Clear; add('select first 1 c.Name as who'); add('from Equipment_Attributes a inner join Equipment c on (a.Eid = c.Eid)'); add('where a.O_Id = :aid and a.Eid <> :cid and upper(a.Ca_Value) = upper(:val)'); end; fq.ParamByName('cid').AsInteger := FEQID; fq.ParamByName('aid').AsInteger := dbluAttribute.VALUE; if cbbList.Visible then fq.ParamByName('val').AsString := cbbList.Text else fq.ParamByName('val').AsString := dbValue.Text; fq.Transaction.StartTransaction; fq.ExecQuery; s := ''; if not fq.FieldByName('who').IsNull then s := fq.FieldByName('who').AsString; fq.Transaction.Commit; fq.Close; finally fq.free; end; if s <> '' then begin errors := true; s := format(rsERROR_UNIQUE, [s]); if cbbList.Visible then CnErrors.SetError(cbbList, s, iaMiddleLeft, bsNeverBlink) else CnErrors.SetError(dbValue, s, iaMiddleLeft, bsNeverBlink); end; end; if not errors then ModalResult := mrOk else ModalResult := mrNone end; end.
unit CurrentLocationForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Sensors, System.Sensors.Components, FMX.Maps, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.ListView.Types, FMX.ListView, FMX.ListBox, FMX.Layouts, System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions; type TMapsForm = class(TForm) MapView1: TMapView; LocationSensor1: TLocationSensor; Long: TLabel; Lat: TLabel; BitmapSource: TImage; ListBox1: TListBox; LocationSensorItem: TListBoxItem; LongitudeItem: TListBoxItem; LatitudeItem: TListBoxItem; Switch1: TSwitch; ScreenshotItem: TListBoxItem; btnShareImage: TButton; ToolBar1: TToolBar; Label1: TLabel; Image1: TImage; ToolBar2: TToolBar; Label2: TLabel; ActionList1: TActionList; ShowShareSheetAction1: TShowShareSheetAction; btnScreenshot: TSpeedButton; procedure EnableLocationSensorClick(Sender: TObject); procedure LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); procedure Switch1Switch(Sender: TObject); procedure MapView1MarkerClick(Marker: TMapMarker); procedure ShowShareSheetAction1BeforeExecute(Sender: TObject); procedure btnScreenshotClick(Sender: TObject); private const Accuracy = 0.0005; private FCurrentPosition: TLocationCoord2D; { Private declarations } procedure SnapShotReady(const Bitmap: TBitmap); public { Public declarations } end; TLocationCoord2DHelper = record helper for TLocationCoord2D function Distance(const NewCoord: TLocationCoord2D): Double; end; var MapsForm: TMapsForm; implementation {$R *.fmx} procedure TMapsForm.EnableLocationSensorClick(Sender: TObject); begin LocationSensor1.Active := True; end; procedure TMapsForm.LocationSensor1LocationChanged(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); var MyLocation: TMapCoordinate; Desqr: TMapMarkerDescriptor; begin Lat.Text := Format('%2.6f', [NewLocation.Latitude]); Long.Text := Format('%2.6f', [NewLocation.Longitude]); MyLocation := TMapCoordinate.Create(StrToFloat(Lat.Text),StrToFloat(Long.Text)); MapView1.Location := MyLocation; if FCurrentPosition.Distance(NewLocation) > Accuracy then begin FCurrentPosition := NewLocation; Desqr := TMapMarkerDescriptor.Create(MyLocation, 'Dropped marker'); Desqr.Icon := BitmapSource.Bitmap; Desqr.Draggable := True; MapView1.AddMarker(Desqr); MapView1.Zoom := 7; end; end; procedure TMapsForm.MapView1MarkerClick(Marker: TMapMarker); begin Marker.DisposeOf; end; procedure TMapsForm.Switch1Switch(Sender: TObject); begin LocationSensor1.Active := Switch1.IsChecked; end; procedure TMapsForm.ShowShareSheetAction1BeforeExecute(Sender: TObject); begin ShowShareSheetAction1.Bitmap.Assign(Image1.Bitmap); end; procedure TMapsForm.SnapShotReady(const Bitmap: TBitmap); begin Image1.Bitmap.Assign(Bitmap); end; procedure TMapsForm.btnScreenshotClick(Sender: TObject); begin MapView1.Snapshot(SnapshotReady); end; { TLocationCoord2DHelper } function TLocationCoord2DHelper.Distance(const NewCoord: TLocationCoord2D): Double; begin Result := Sqrt(Sqr(Abs(Self.Latitude - NewCoord.Latitude)) + Sqr(Abs(Self.Longitude - NewCoord.Longitude))); end; end.
unit uBalloon; (* Образцы кода взяты из Delphi Russian Knowledge Base from Vit Version 2.2 *) interface uses { Какие библиотеки используем } Windows, ShellAPI, SysUtils, Classes, SyncObjs, Messages,// Dialogs, DataHelper, OSFuncHelper; const cs_CantCreateObject = 'Не вдалося створити об''єкт'; cs_CantSetEvent = 'Не вдалося встановити сигнал'; cs_CantResetEvent = 'Не вдалося вимкнути сигнал'; cs_CantCloseObject = 'Не вдалося закрити об''єкт'; cs_OfTerminateTBaloonMessengerEvent = ' події завершення роботи TBaloonMessenger... '; cs_OfNewBaloonMessageEvent = ' події надходження повідомлення на відображення у треї... '; cs_OfChangeIconStateCommand = ' команди змінити стан значка у треї... '; cs_FailedToAddTaskbarIcon = ': не вдалося додати значок у трей...'; cs_FailedToChangeTaskbarIcon = ': не вдалося змінити значок у треї...'; cs_FailedToRemoveTaskbarIcon = ': не вдалося прибрати значок із трея...'; cs_FailedToShowBalloon = ': не вдалося показати кульку з повідомленням...'; cs_WaitForCommand = 'Очікування на команду'; cs_WaitForCommandBetweenBalloons = cs_WaitForCommand+ ' між відображеннями кульок'; cs_ReturnedUnknownResult = ' повернуло невідомий результат: '; cs_CallingBalloonEventException = 'при виклику обробника події відображення кульки виникло виключення'; cs_FromMessagesThread = '(із потока повідомлень)'; cs_WhenSynchronizedWithMain = '(синхронізованого з головним)'; //cs_OfIconRemoveCommand = // ' команди прибрати значок у треї... '; ci_ShowTimeAddition = 2000; // мс. Постійна частина часу відображення кульки // Типова кількість мілісекунд відображення повідомлення на один його // символ: ci_DefMillisecondsPerSymbol = 100; type TBalloonTimeout = 10..30{seconds}; TBalloonIconType = (bitNone, // нет иконки bitInfo, // информационная иконка (синяя) bitWarning, // иконка восклицания (жёлтая) bitError, // иконка ошибки (краснаа) bitNotSet); // иконка не определена PBalloonIconType = ^TBalloonIconType; TBalloonIconAndMessageBoxType = record BalloonIconType: TBalloonIconType; MessageBoxType: DWord; End; PBalloonIconAndMessageBoxType = ^TBalloonIconAndMessageBoxType; TBaloonMessenger = class; TOnBalloonProc = procedure(Sender:TBaloonMessenger; Const sBalloonMessageShown, sBalloonTitleShown:String; Const sMessageQueue:TStrings) of object; TBaloonHider = class(TThread) private //cHideThis: Boolean; cWindow: HWND; cIconID: Byte; cPauseBeforeHide: DWORD; cBalloonCriticalSection: TCriticalSection; protected procedure Execute; override; public property PauseBeforeHide: DWORD read cPauseBeforeHide write cPauseBeforeHide; Constructor Create(CreateSuspended: Boolean; const Window: HWND; const IconID: Byte; sPauseBeforeHide:DWORD; sBalloonCriticalSection:TCriticalSection); end; TBaloonIconTypesList = class(Classes.TList) protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; function Get(Index: Integer): TBalloonIconAndMessageBoxType; procedure Put(Index: Integer; Const Item: TBalloonIconAndMessageBoxType); public function Add(Const Item: TBalloonIconAndMessageBoxType): Integer; procedure Clear; override; procedure Delete(Index: Integer); function Remove(Item: TBalloonIconAndMessageBoxType): Integer; function Extract(Const Item: TBalloonIconAndMessageBoxType): TBalloonIconAndMessageBoxType; function ExtractByNum(Index: Integer): TBalloonIconAndMessageBoxType; function First: TBalloonIconAndMessageBoxType; function ExtractFirst: TBalloonIconAndMessageBoxType; procedure Insert(Index: Integer; Const Item: TBalloonIconAndMessageBoxType); function Last: TBalloonIconAndMessageBoxType; function ExtractLast: TBalloonIconAndMessageBoxType; // Виконує пошук у списку... знаходить перший елемент, що // рівний поданому значенню: function IndexOf(Const Item: TBalloonIconAndMessageBoxType): Integer; property Items[Index: Integer]: TBalloonIconAndMessageBoxType read Get write Put; default; end; TBaloonMessenger = class(TThread) private //cHideThis: Boolean; // Власне вікно потока. // Використовується для MessageBox як батьківське, // і отримує повідомлення про події значка: FWnd:HWND; // Вікно, якому перенадсилаються повідомлення про події значка трея: cWindow: HWND; //, cNewWindow cuCallbackMessage, cNewuCallbackMessage:UInt; cIconID, cNewIconID: Byte; chIcon: HICON; //, cNewhIcon cDefPauseBeforeHide:DWord;//, cPauseBeforeNext: DWORD; cNoSystemBalloonSound: Boolean; cBalloonCriticalSection, cCallingEventProcSection: TCriticalSection; cBaloonMessageQueue, cBalloonTitleQueue: TStrings; cBaloonIconQueue:TBaloonIconTypesList; cShowPauseQueue: TUIntList; // Спливаючий підпис значка в треї. // Не має черги. Змінюється потоком відразу при виклику команди // ShowTrayIcon (ProcShowTrayIcon): cHint: String; cHideIconOnLastMessageShown:Boolean; cTerminateEvent, // cMessageQueuedEvent, cChangeIconStateCommand: THandle; cLogFile:TLogFile; cIconVisible, cToShowIcon:Boolean; //cLastMessage: String; cRaiseExceptions:Boolean; // Обробники подій: cEvtAfterBalloon, // cBalloonEvtToCall використовується щоб запам'ятати обробник що треба // викликати на час коли потік вийде із критичної серкції // охорони своїх даних (cBalloonCriticalSection) і зайде // у секцію охорони даних виклику обробника (cCallingEventProcSection). // В цей час головний потік може затерти cEvtAfterBalloon чи інші // обробники іншими значеннями доки цей потік чекатиме // поки головний потік виконає свою поточну роботу: cBalloonEvtToCall: TOnBalloonProc; // Режим виклику із потока обробників подій: cSynchronizeEvents: Boolean; cCurMessage, cCurTitle: String; Procedure SetHostingWindow(Value: HWND); Procedure SetCallbackMessage(Value: UInt); Procedure SetIconID(Value: Byte); Procedure SetIcon(Value: HICON); Procedure SetNoSystemBalloonSound(Value: Boolean); Procedure SetIconHint(Value: String); Procedure SetDefPauseBeforeHide(Value: DWORD); //Procedure SetPauseBeforeNext(Value: DWORD); Procedure SetHideIconOnLastMessageShown(Value: Boolean); Procedure SetAfterBalloon(Value: TOnBalloonProc); Procedure SetSynchronizeEvents(Value: Boolean); Function AddTrayIcon(const Hint: String = ''):Boolean; Function ChangeTrayIcon(const Hint: String = ''):Boolean; Function RemoveTrayIcon:Boolean; Function ProcShowBalloon(const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; sPauseBeforeHide:Cardinal; sNoSystemSound:Boolean):Boolean; // Рекурсивна процедура додавання повідомлення в чергу із // поділом його на частини що можна відобразити: Procedure ProcAddMessageToQueue(const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; Const sMessageBoxType: DWORD; sPauseBeforeHide:Cardinal); function CheckSelfExitCode:DWord; Procedure CallAfterBalloonShow(Const sMessage, sTitle: String; Const sBaloonMessageQueue:TStrings); // Викликається синхронізованою із головним потоком // коли cSynchronizeEvents = True: Procedure SynchronizedCallBalloonEventProc; protected procedure Execute; override; procedure WindowProc(var sMessage: Messages.TMessage); Procedure ProcessMessages; // Процедури, що посилають команди потокові: procedure ProcHideTrayIcon; procedure ProcShowTrayIcon(const Hint: String = ''); procedure ProcQueueBalloon(const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; Const sMessageBoxType: DWORD; sPauseBeforeHide: Cardinal = 0); public property Window: HWND read cWindow write SetHostingWindow; property SelfWindow: HWND read FWnd; property IconID: Byte read cIconID write SetIconID; property hIcon: HICON read chIcon write SetIcon; property uCallbackMessage: UInt read cuCallbackMessage write SetCallbackMessage; // NoSystemBalloonSound = True вимикає системний звук відображення // кульки із повідомленням. // Правда, для Windows Vista і вище (по Windows 8.1 принаймні) // існує баг, і системний звук // НЕ відтворюєтсья ніколи поки вручну не записати відомості // про медіафайл у потрібному розділі реєстру: // Windows Registry Editor Version 5.00 // [HKEY_CURRENT_USER\AppEvents\Schemes\Apps\Explorer\SystemNotification\.current] // @="C:\\Windows\\Media\\Windows Balloon.wav" // Про це писали тут...: // http://winaero.com/blog/fix-windows-plays-no-sound-for-tray-balloon-tips-notifications/ // Якщо ж система налаштована вірно щоб відтворювати цей звук // то при NoSystemBalloonSound = False вона відтворюватиме: property NoSystemBalloonSound: Boolean read cNoSystemBalloonSound write SetNoSystemBalloonSound; property IconHint: String read cHint write SetIconHint; property DefPauseBeforeHide: DWORD read cDefPauseBeforeHide write SetDefPauseBeforeHide; //property PauseBeforeNext: DWord read cPauseBeforeNext // write SetPauseBeforeNext; // Чи прибирати значок у треї після відображення останнього // повідомлення з черги: property HideIconOnLastMessageShown:Boolean read cHideIconOnLastMessageShown write SetHideIconOnLastMessageShown; // Чи піднімати виключення коли не вдається записати // повідомлення про помилку у cLogFile: property RaiseExceptions:Boolean read cRaiseExceptions write cRaiseExceptions; property IconVisible: Boolean read cIconVisible; // Обробники подій відображення повідомлень. // Викликаються із цього потока відображення повідомлень у кульках. // У разі SynchronizeEvents = True їх виклик синхронізується із // головним потоком програми, інакше викликається без синхронізації // в контексті критичної секції використання даних потоком. // Обробник не повинен займати надто багато часу так як він // виконується разом із відображенням повідомлень: property AfterBalloon: TOnBalloonProc read cEvtAfterBalloon write SetAfterBalloon; // Режим виклику із потока обробників подій. // У разі SynchronizeEvents = True їх виклик синхронізується із // головним потоком програми. В цьому режимі можна звертатися до // будь-яких даних головного потока програми. Проте перед викликом // потік відображення кульок чекає доки потік головної програми // буде не занйятий. // При SynchronizeEvents = False викликається без синхронізації // в контексті критичної секції використання даних потоком. // Головний потік може бути зайнятий іншою роботою. В цей час обробник // може виконувати потрібні йому дії, проте використовувати дані // головного потока має з думкою про те що він таким чином втручається // в роботу головного потока і може поламати її якщо змінюватиме дані, // або розгубитися сам якщо дані неочікувано змінить головний потік. // Тобто для доступу до даних головного потока може бути потрібна // додаткова синхонізація (наприклад додаткові критичні секції)...: property SynchronizeEvents: Boolean read cSynchronizeEvents write SetSynchronizeEvents; // Показує значок в треї із спливаючим поясненням, // якщо він ще не показаний. // Інакше тільки міняє пояснення: Procedure ShowTrayIcon(const Hint: String = ''); // Додає повідомлення в чергу на відображення. // Якщо повідомлень у черзі немає то повідомлення відображається // відразу. // Якщо довжина повідомлення p_Message завелика щоб показати його // у кульці трея то ділить повідомлення на декілька і додає їх у чергу. // При цьому повідомлення ділиться по рядкам. Якщо один рядок // всеодно задовгий то він ділиться по словам по пробілам. Якщо // слово надто довге то ділить його за максимальною довжиною що можна // вмістити. // Якщо sPauseBeforeHide не рівна нулю то змінює час відображення // кульки PauseBeforeHide (у мілісекундах) після відображення // останнього повідомлення. // Якщо значок у треї не відображається (не було // виклику ShowIcon), то показує його із спливаючою підказкою // p_Header. // Якщо HideIconOnLastMessageShown=True то після відображення // всіх повідомлень автоматично прибирає значок (без виклику // HideIcon). // BalloonIconType - тип значка в повідомленні-кульці. // Якщо не задана (рівна bitNotSet) то визначається за sMessageBoxType. // Якщо sMessageBoxType теж не задано то приймається як bitInfo; // sMessageBoxType - тип кнопок, значка і параметри вікна // MessageBox, яке може бути відображено замість кульки якщо кульку // не вдасться показати. Якщо не задано то визначається // за BalloonIconType. procedure ShowBalloon(p_Message, p_Header: String; sPauseBeforeHide: Integer = 0; BalloonIconType: TBalloonIconType = bitNotSet; sMessageBoxType: DWORD = High(DWORD)); // Прибирає значок із трея. Якщо у черзі ще є // непоказані повідомлення то значок не прибирається // доки всі вони не будуть показані. Якщо протягом цього часу // буде викликано ShowIcon то значок не буде прибраний і // після показу всіх повідомлень (тобто цей виклик не матиме тоді // ефекту): Procedure HideTrayIcon; // Якщо вказано sLogFile то об'єкт буде записувати у цей файл // повідомлення про виключення і копії повідомлень, що // відображаються. // Вказаний sLogFile має існувати доки існує цей об'єкт...: Constructor Create(CreateSuspended: Boolean; sFreeOnTerminate: Boolean; const Window: HWND; const IconID: Byte; sDefPauseBeforeHide:DWORD; sLogFile:TLogFile = Nil; suCallbackMessage:UInt = 0); destructor Destroy; override; procedure Terminate; virtual; // override; тут, на жаль, не можна override, бо у TThread Terminate не є віртуальною... procedure LogMessage(sMessage:String; sThisIsAnError:Boolean = False); procedure LogLastOSError(sCommentToError:String); overload; procedure LogLastOSError(sCommentToError:String; LastError: Integer); overload; // Не робить нічого якщо викликається не із потока цього // об'єкта і потік ще не завершений. Інакше - ховає значок...: Procedure CleanUpAfterWork; Class Function ConvertBalloonIconTypeToMessageBoxWithOkButtonType( BalloonIconType:TBalloonIconType):DWORD; static; Class Function ConvertMessageBoxTypeToBalloonIconType(suType:DWORD): TBalloonIconType; static; end; function DZAddTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String = ''; const suCallbackMessage:UInt = 0): Boolean; function DZChangeTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String = ''): Boolean; function DZRemoveTrayIcon(const Window: HWND; const IconID: Byte): Boolean; function DZBalloonTrayIcon(const Window: HWND; const IconID: Byte; const Timeout: TBalloonTimeout; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; sNoSystemSound:Boolean = False): Boolean; overload; function DZBalloonTrayIcon(const Window: HWND; const IconID: Byte; const Timeout: UINT; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; sNoSystemSound:Boolean = False): Boolean; overload; implementation const NIF_INFO = $00000010; NIIF_NONE = $00000000; NIIF_INFO = $00000001; NIIF_WARNING = $00000002; NIIF_ERROR = $00000003; NIIF_NOSOUND = $00000010; aBalloonIconTypes : array[TBalloonIconType] of Byte = (NIIF_NONE, NIIF_INFO, NIIF_WARNING, NIIF_ERROR, NIIF_NONE); // якщо bitNotSet то не показується значок (NIIF_NONE) Var ci_MaxTrayTipLen, ci_MaxTrayBaloonInfoLen, ci_MaxTrayBaloonTitleLen: Integer; {type NotifyIconData_50 = record // определённая в shellapi.h cbSize: DWORD; Wnd: HWND; uID: UINT; uFlags: UINT; uCallbackMessage: UINT; hIcon: HICON; szTip: array[0..MAXCHAR] of AnsiChar; dwState: DWORD; dwStateMask: DWORD; szInfo: array[0..MAXBYTE] of AnsiChar; uTimeout: UINT; // union with uVersion: UINT; szInfoTitle: array[0..63] of AnsiChar; dwInfoFlags: DWORD; end; //record} /////////////////////////////////////////////////////////////////////// {добавление иконки } //Взято с Исходников.ru http://www.sources.ru function DZAddTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String = ''; const suCallbackMessage:UInt = 0): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; if Hint = '' then begin uFlags := NIF_ICON; end{if} else begin uFlags := NIF_ICON or NIF_TIP; //StrPCopy(szTip, Hint); //StrCopy(szTip, PChar(Hint)); StrLCopy(szTip, PChar(Hint), SizeOf(szTip) - 1); end{else}; if suCallbackMessage <> 0 then Begin uCallbackMessage:= suCallbackMessage; uFlags:= uFlags or NIF_MESSAGE; End; hIcon := Icon; end{with}; Result := Shell_NotifyIcon(NIM_ADD, @NID); end; function DZChangeTrayIcon(const Window: HWND; const IconID: Byte; const Icon: HICON; const Hint: String = ''): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; if Hint = '' then begin uFlags := NIF_ICON; end{if} else begin uFlags := NIF_ICON or NIF_TIP; StrLCopy(szTip, PChar(Hint), SizeOf(szTip) - 1); end{else}; hIcon := Icon; end{with}; Result := Shell_NotifyIcon(NIM_MODIFY, @NID); end; /////////////////////////////////////////////////////////////////////// {удаляет иконку} //Взято с Исходников.ru http://www.sources.ru function DZRemoveTrayIcon(const Window: HWND; const IconID: Byte): Boolean; var NID : NotifyIconData; begin FillChar(NID, SizeOf(NotifyIconData), 0); with NID do begin cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; end{with}; Result := Shell_NotifyIcon(NIM_DELETE, @NID); end; /////////////////////////////////////////////////////////////////////// {Показывает баллон} //Взято с Исходников.ru http://www.sources.ru /////////////////////////////////////////////////////////////////////// function DZBalloonTrayIcon(const Window: HWND; const IconID: Byte; const Timeout: TBalloonTimeout; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; sNoSystemSound:Boolean): Boolean; //const // aBalloonIconTypes : array[TBalloonIconType] of Byte = (NIIF_NONE, NIIF_INFO, NIIF_WARNING, NIIF_ERROR); //var // NID_50 : NotifyIconData; //NotifyIconData_50; begin Result:= DZBalloonTrayIcon(Window, IconID, UINT(Timeout*1000), BalloonText, BalloonTitle, BalloonIconType, sNoSystemSound); end; function DZBalloonTrayIcon(const Window: HWND; const IconID: Byte; const Timeout: UINT; const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; sNoSystemSound:Boolean): Boolean; var NID_50 : NotifyIconData; //NotifyIconData_50; ccdwInfoFlags:DWord; begin //FillChar(NID_50, SizeOf(NotifyIconData_50), 0); FillChar(NID_50, SizeOf(NotifyIconData), 0); with NID_50 do begin //cbSize := SizeOf(NotifyIconData_50); cbSize := SizeOf(NotifyIconData); Wnd := Window; uID := IconID; uFlags := NIF_INFO; //StrPCopy(szInfo, AnsiString(BalloonText)); //StrCopy(szInfo, PChar(BalloonText)); StrLCopy(szInfo, PChar(BalloonText), SizeOf(szInfo) - 1); uTimeout := Timeout; //StrPCopy(szInfoTitle, AnsiString(BalloonTitle)); //StrCopy(szInfoTitle, PChar(BalloonTitle)); StrLCopy(szInfoTitle, PChar(BalloonTitle), SizeOf(szInfoTitle) - 1); ccdwInfoFlags:= aBalloonIconTypes[BalloonIconType]; if sNoSystemSound then ccdwInfoFlags:= ccdwInfoFlags or NIIF_NOSOUND; dwInfoFlags := ccdwInfoFlags; end{with}; Result := Shell_NotifyIcon(NIM_MODIFY, @NID_50); end; Constructor TBaloonHider.Create(CreateSuspended: Boolean; const Window: HWND; const IconID: Byte; sPauseBeforeHide:DWORD; sBalloonCriticalSection:TCriticalSection); Begin Inherited Create(True); Self.cWindow:= Window; Self.cIconID:= IconID; Self.cPauseBeforeHide:= sPauseBeforeHide; Self.cBalloonCriticalSection:= sBalloonCriticalSection; Self.FreeOnTerminate:= True; // звільняти об'єкт не будемо, хай сам.. if Not(CreateSuspended) then Self.Resume; End; procedure TBaloonHider.Execute; Begin if Not(Self.Terminated) then Begin Windows.Sleep(Self.cPauseBeforeHide); Self.cBalloonCriticalSection.Enter; try DZRemoveTrayIcon(Self.cWindow, Self.cIconID); finally Self.cBalloonCriticalSection.Leave; end; End; End; {Хотів зробити щоб кулька не ховалася швидко якщо в ній з'явився новий текст.. але тоді треба слідкувати за важелем вікна, чи воно не змінилося, чи не з'явилася нова кулька... procedure TBaloonHider.Execute; Var cCurPause: DWord; Begin While Not(Self.Terminated) do Begin if Not(Self.cHideThis) then Begin Self.Suspend; Continue; End; Self.cBalloonCriticalSection.Enter; try cCurPause:= Self.cPauseBeforeHide; Self.cPauseBeforeHide:= 0; // скидаємо ту паузу, яку виконаємо Self.cHideThis:= False; // скидаємо команду "зховати кульку тексту", бо її виконаємо finally Self.cBalloonCriticalSection.Leave; end; Windows.Sleep(cCurPause); // Якщо за час паузи знову прийшла команда зховати повідомлення після паузи // (і задана нова пауза) - то не ховаємо повідомлення, чекаємо ще той час який задали: if Self.cHideThis then Continue; Self.cBalloonCriticalSection.Enter; try DZRemoveTrayIcon(Self.cWindow, Self.cIconID); finally Self.cBalloonCriticalSection.Leave; end; End; End;} Constructor TBaloonMessenger.Create(CreateSuspended: Boolean; sFreeOnTerminate: Boolean; const Window: HWND; const IconID: Byte; sDefPauseBeforeHide:DWORD; sLogFile:TLogFile = Nil; suCallbackMessage:UInt = 0); Begin Inherited Create(True); Self.cLogFile:= sLogFile; // Своє вікно ще не створене, його створить потік коли буде запущений: Self.FWnd:= 0; Self.cWindow:= Window; //Self.cNewWindow:= Self.cWindow; Self.cuCallbackMessage:= suCallbackMessage; Self.cNewuCallbackMessage:= Self.cuCallbackMessage; Self.cIconID:= IconID; Self.cNewIconID:= Self.cIconID; Self.cDefPauseBeforeHide:= sDefPauseBeforeHide; // // Типово пауза перед наступним повідомленням рівна паузі // // перед хованням кульки: //Self.cPauseBeforeNext:= Self.cDefPauseBeforeHide; // Типове зображення для значка в треї: Self.chIcon:= Windows.LoadIcon(0, IDI_APPLICATION); // Якщо на сповіщення у кульці встановлений системний звук то // типово він відтворюється. // Правда, для Windows Vista і вище (по Windows 8.1 принаймні) існує баг, // і системний звук // не відтворюєтсья поки вручну не записати відомості про медіафайл // у потрібному розділі реєстру: // Windows Registry Editor Version 5.00 // [HKEY_CURRENT_USER\AppEvents\Schemes\Apps\Explorer\SystemNotification\.current] // @="C:\\Windows\\Media\\Windows Balloon.wav" // Про це писали тут...: // http://winaero.com/blog/fix-windows-plays-no-sound-for-tray-balloon-tips-notifications/ // Проте якщо система може відтворювати звук, то типово вона відтворює: Self.cNoSystemBalloonSound:= False; //Self.cNewhIcon:= Self.chIcon; Self.cBalloonCriticalSection:= TCriticalSection.Create; Self.cCallingEventProcSection:= TCriticalSection.Create; // Черга повідомлень для відображення. // Якщо в ній накопичується більше одного повідомлення то // всі вони відображаються через паузу : Self.cBaloonMessageQueue:= TStringList.Create; // частина черги - черга заголовків повідомлень: Self.cBalloonTitleQueue:= TStringList.Create; Self.cBaloonIconQueue:= TBaloonIconTypesList.Create; Self.cShowPauseQueue:= TUIntList.Create; // Вмикає прибирання значка із трея після відображення // усіх повідомлень із черги. Тоді при надходженні нових // повідомлень значок знову додається. // При завершенні роботи цього об'єкта значок прибирається // незалежно від цього параметра: Self.cHideIconOnLastMessageShown:= True; // Цей об'єкт готовий приймати на відображення і відображати // повідомлення в Baloon доки його не звільнять. // Тому сам не звільняється навіть якщо потік // закінчить роботу через якусь неочікувану ситуацію: Self.FreeOnTerminate:= sFreeOnTerminate; Self.cTerminateEvent:= OsFuncHelper.ProcCreateEvent( cs_CantCreateObject+cs_OfTerminateTBaloonMessengerEvent + c_SystemSays, True, // після виникнення скидається вручну False, // спочатку подія не відбувалася Nil, // подія не має імені (воно не треба, бо інші процеси цю подію не використовують і її важіль не успадковують) Self.cLogFile); {Self.cMessageQueuedEvent:= OsFuncHelper.ProcCreateEvent( cs_CantCreateObject+cs_OfNewBaloonMessageEvent + c_SystemSays, True, // після виникнення скидається вручну False, // спочатку подія не відбувалася Nil, // подія не має імені (воно не треба, бо інші процеси цю подію не використовують і її важіль не успадковують) Self.cLogFile);} Self.cChangeIconStateCommand:= OsFuncHelper.ProcCreateEvent( cs_CantCreateObject+cs_OfChangeIconStateCommand + c_SystemSays, True, // після виникнення скидається вручну False, // спочатку подія не відбувалася Nil, // подія не має імені (воно не треба, бо інші процеси цю подію не використовують і її важіль не успадковують) Self.cLogFile); // Вважаємо що спочатку немає значка...: Self.cIconVisible:= False; Self.cToShowIcon:= False; // команди показати значок ще не було // Обробники подій спочатку не задані: Self.cEvtAfterBalloon:= Nil; Self.cBalloonEvtToCall:= Nil; cCurMessage:= ''; cCurTitle:= ''; if Not(CreateSuspended) then Self.Resume; End; procedure TBaloonMessenger.Terminate; Begin // Спочатку встановлюємо помітку про те що треба завершувати роботу: Inherited Terminate; // А потім уже подаємо про те сигнал: // Встановлюємо сигнал про те що треба завершити процедуру (потік): OSFuncHelper.ProcSetEvent(Self.cTerminateEvent, cs_CantSetEvent+cs_OfTerminateTBaloonMessengerEvent + c_SystemSays, Self.cLogFile); End; destructor TBaloonMessenger.Destroy; var cc_ThreadExitCode:DWord; Begin cc_ThreadExitCode:= Self.CheckSelfExitCode; // Чекаємо завершення потока тільки якщо він ще дійсно // працює (не завершився і його ніхто не перервав...): if cc_ThreadExitCode = STILL_ACTIVE then Begin if Not(Self.Finished) then Begin Self.Terminate; while Self.Suspended and (cc_ThreadExitCode = STILL_ACTIVE) do Begin Self.Resume; cc_ThreadExitCode:= Self.CheckSelfExitCode; End; if cc_ThreadExitCode = STILL_ACTIVE then Self.WaitFor; // if Not(Self.Finished) then // Windows.Sleep(c_EmergencySleepTime); End; End; Self.cEvtAfterBalloon:= Nil; Self.cBalloonEvtToCall:= Nil; {OSFuncHelper.ProcCloseHandle(Self.cMessageQueuedEvent, cs_CantCloseObject+cs_OfNewBaloonMessageEvent + c_SystemSays, Self.cLogFile);} OSFuncHelper.ProcCloseHandle(Self.cTerminateEvent, cs_CantCloseObject+cs_OfTerminateTBaloonMessengerEvent + c_SystemSays, Self.cLogFile); OSFuncHelper.ProcCloseHandle(Self.cChangeIconStateCommand, cs_CantCloseObject+cs_OfChangeIconStateCommand + c_SystemSays, Self.cLogFile); SysUtils.FreeAndNil(Self.cBaloonMessageQueue); SysUtils.FreeAndNil(Self.cBalloonTitleQueue); SysUtils.FreeAndNil(Self.cBaloonIconQueue); SysUtils.FreeAndNil(Self.cShowPauseQueue); SysUtils.FreeAndNil(Self.cCallingEventProcSection); SysUtils.FreeAndNil(Self.cBalloonCriticalSection); Inherited Destroy; End; procedure TBaloonMessenger.LogLastOSError(sCommentToError:String); var ccDoIt:Boolean; Begin ccDoIt:= Self.cRaiseExceptions; if System.Assigned(Self.cLogFile) then Begin if Self.cLogFile.Opened then ccDoIt:= True; End; if ccDoIt then OSFuncHelper.LogLastOsError(sCommentToError, Self.cLogFile); End; procedure TBaloonMessenger.LogMessage(sMessage:String; sThisIsAnError:Boolean = False); var ccDoIt:Boolean; Begin ccDoIt:= Self.cRaiseExceptions and sThisIsAnError; if System.Assigned(Self.cLogFile) then Begin if Self.cLogFile.Opened or ccDoIt then Begin Self.cLogFile.WriteMessage(sMessage); End; End else if ccDoIt then Begin Raise Exception.Create(sMessage); End; End; procedure TBaloonMessenger.LogLastOSError(sCommentToError:String; LastError: Integer); var ccDoIt:Boolean; Begin ccDoIt:= Self.cRaiseExceptions; if System.Assigned(Self.cLogFile) then Begin if Self.cLogFile.Opened then ccDoIt:= True; End; if ccDoIt then OSFuncHelper.LogLastOsError(sCommentToError, LastError, Self.cLogFile); End; Function TBaloonMessenger.AddTrayIcon(const Hint: String = ''):Boolean; const cs_ProcName = 'TBaloonMessenger.AddTrayIcon'; Begin Result:= DZAddTrayIcon(Self.FWnd, //Self.cNewWindow, Self.cNewIconID, Self.chIcon, Hint, Self.cNewuCallbackMessage); if Result then Begin //Self.cWindow:= Self.cNewWindow; Self.cIconID:= Self.cNewIconID; Self.cuCallbackMessage:= Self.cNewuCallbackMessage; Self.cIconVisible:= True; End Else Self.LogMessage(cs_ProcName + cs_FailedToAddTaskbarIcon, True); End; Function TBaloonMessenger.ChangeTrayIcon(const Hint: String = ''):Boolean; const cs_ProcName = 'TBaloonMessenger.ChangeTrayIcon'; Begin Result:= DZChangeTrayIcon(Self.FWnd, Self.IconID, Self.chIcon, Hint); if Not(Result) then Begin Self.LogMessage(cs_ProcName + cs_FailedToChangeTaskbarIcon, True); End; End; Function TBaloonMessenger.RemoveTrayIcon:Boolean; const cs_ProcName = 'TBaloonMessenger.RemoveTrayIcon'; Begin Result:= DZRemoveTrayIcon(Self.FWnd, Self.IconID); // Чи вдалося заховати значок чи ні - вважаємо що він не відображається, бо // якщо контролювати його не виходить то і робити з ним нічого не можливо // більше. І система швидше за все його прибрала вже, вона прибирає значки // чиї вікна вже не існують, коли над ними з'являється мишка: Self.cIconVisible:= False; if Not(Result) then Self.LogMessage(cs_ProcName + cs_FailedToRemoveTaskbarIcon, True); End; Function TBaloonMessenger.ProcShowBalloon(const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; sPauseBeforeHide:Cardinal; sNoSystemSound:Boolean):Boolean; const cs_ProcName = 'TBaloonMessenger.ProcShowBalloon'; Begin Result:= DZBalloonTrayIcon(Self.FWnd, Self.IconID, sPauseBeforeHide, BalloonText, BalloonTitle, BalloonIconType, sNoSystemSound); if Not(Result) then Begin Self.LogMessage(cs_ProcName + cs_FailedToShowBalloon, True); End; End; // Процедури, що посилають команди потокові: procedure TBaloonMessenger.ProcHideTrayIcon; const sc_ProcName='TBaloonMessenger.ProcHideTrayIcon: '; Begin Self.cBalloonCriticalSection.Enter; try Self.cToShowIcon:= False; // треба приховати значок finally Self.cBalloonCriticalSection.Leave; end; OSFuncHelper.ProcSetEvent(Self.cChangeIconStateCommand, sc_ProcName + cs_CantSetEvent + cs_OfChangeIconStateCommand + c_SystemSays, Self.cLogFile); //Begin While Self.Suspended do Self.Resume; //End; End; Procedure TBaloonMessenger.HideTrayIcon; Begin Self.ProcHideTrayIcon; End; procedure TBaloonMessenger.ProcShowTrayIcon(const Hint: String = ''); const sc_ProcName='TBaloonMessenger.ProcShowTrayIcon: '; Begin //if (Self.IconHint<>Hint) then // це перевіряється у SetIconHint Self.cBalloonCriticalSection.Enter; try Self.IconHint:= Hint; Self.cToShowIcon:= True; // треба показати значок finally Self.cBalloonCriticalSection.Leave; end; OSFuncHelper.ProcSetEvent(Self.cChangeIconStateCommand, sc_ProcName + cs_CantSetEvent + cs_OfChangeIconStateCommand + c_SystemSays, Self.cLogFile); While Self.Suspended do Self.Resume; End; Procedure TBaloonMessenger.ShowTrayIcon(const Hint: String = ''); Begin Self.ProcShowTrayIcon(Hint); End; procedure TBaloonMessenger.ProcQueueBalloon(const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; Const sMessageBoxType: DWORD; sPauseBeforeHide: Cardinal = 0); const sc_ProcName='TBaloonMessenger.ProcQueueBalloon: '; Begin Self.cBalloonCriticalSection.Enter; try Self.ProcAddMessageToQueue(BalloonText, BalloonTitle, BalloonIconType, sMessageBoxType, sPauseBeforeHide); // Щоб показати повідомлення треба створити значок. // Система може показувати його або приховувати, // та він має бути: Self.cToShowIcon:= True; finally Self.cBalloonCriticalSection.Leave; end; OSFuncHelper.ProcSetEvent(Self.cChangeIconStateCommand, sc_ProcName + cs_CantSetEvent + cs_OfChangeIconStateCommand + c_SystemSays, Self.cLogFile); While Self.Suspended do Self.Resume; End; Class Function TBaloonMessenger.ConvertBalloonIconTypeToMessageBoxWithOkButtonType( BalloonIconType:TBalloonIconType):DWORD; Begin Result:= ci_DefOkMsgBoxType; // MessageBox із кнопкою OK поверх всіх вікон case BalloonIconType of bitNone:; // без значка у вікні із повідомленням bitInfo: Result:= Result or MB_ICONINFORMATION; bitWarning: Result:= Result or MB_ICONWARNING; bitError: Result:= Result or MB_ICONERROR; bitNotSet: ; end; End; Class Function TBaloonMessenger.ConvertMessageBoxTypeToBalloonIconType(suType:DWORD): TBalloonIconType; Var ccMsgBoxIconType:DWORD; Begin ccMsgBoxIconType:= suType and MB_AllMessageBoxIconsMask; //MB_AllMessageBoxButtonsMask case ccMsgBoxIconType of MB_ICONINFORMATION:Result:= bitInfo; MB_ICONERROR:Result:= bitError; MB_ICONWARNING:Result:= bitWarning; MB_ICONQUESTION:Result:= bitWarning; else Result:= bitNone; end; End; procedure TBaloonMessenger.ShowBalloon(p_Message, p_Header: String; sPauseBeforeHide: Integer = 0; BalloonIconType: TBalloonIconType = bitNotSet; sMessageBoxType: DWORD = High(DWORD)); Begin {if sPauseBeforeHide > 0 then Begin Self.PauseBeforeHide:= sPauseBeforeHide; End;} // Якщо sMessageBoxType не задано то: if sMessageBoxType = High(DWORD) then Begin // Якщо BalloonIconType теж не задано: if BalloonIconType >= bitNotSet then Begin BalloonIconType:= bitInfo; End; sMessageBoxType:= Self.ConvertBalloonIconTypeToMessageBoxWithOkButtonType(BalloonIconType); End Else Begin // Якщо BalloonIconType не задано: if BalloonIconType >= bitNotSet then Begin BalloonIconType:= Self.ConvertMessageBoxTypeToBalloonIconType(sMessageBoxType); End; End; Self.ProcQueueBalloon(p_Message, p_Header, BalloonIconType, sMessageBoxType, sPauseBeforeHide); End; Procedure TBaloonMessenger.SetHostingWindow(Value: HWND); Begin // Якщо вже командували поміняти вікно на вказане то // нічого робити не треба, потік це виконає: //if Self.cNewWindow = Value then Exit; if Self.cWindow = Value then Exit; Self.cBalloonCriticalSection.Enter; try //Self.cNewWindow:= Value; Self.cWindow:= Value; // Потік використовує своє вікно для отримання повідомлень від значка, //тому тут показувати значок із новим вікном не треба. //Після виходу із секції cBalloonCriticalSection //процедура WindowProc буде пересилати повідомлення значка //новому вікну Self.cWindow. // // Якщо на момент заміни вікна значок треба відображати // // (і/або показувати повідомлення), то // // командуємо прибрати значок із трея (від староно вікна) // // і показати (від нового вікна), без очікування на виконання команди. // // Якщо значок відображається то потік заховає його від старого вікна. // // Далі покаже від нового: //if Self.cToShowIcon then // Self.ProcShowTrayIcon(Self.IconHint); finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetCallbackMessage(Value: UInt); Begin if Self.cuCallbackMessage = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cNewuCallbackMessage:= Value; // Якщо на момент заміни вікна значок треба відображати // (і/або показувати повідомлення), то // командуємо прибрати значок із трея (від староно вікна) // і показати (від нового вікна), без очікування на виконання команди. // Якщо значок відображається то потік заховає його і покаже // із новим номером повідомлення-відгуку: if Self.cToShowIcon then Self.ProcShowTrayIcon(Self.IconHint); finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetIconID(Value: Byte); Begin // Якщо вже командували поміняти вікно на вказане то // нічого робити не треба, потік це виконає: if Self.cNewIconID = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cNewIconID:= Value; // Командуємо прибрати старий значок із трея // і показати новий, без очікування на виконання команди: // Якщо значок відображається то потік заховає його. // Далі покаже з новим ідентифікатором (номером): if Self.cToShowIcon then Self.ProcShowTrayIcon(Self.IconHint); finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetIcon(Value: HICON); Begin // Якщо цей значок вже заданий то нічого не командуємо: if Self.chIcon = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.chIcon:= Value; // Командуємо показати значок із новими параметрами. //Якщо значок не відображається то потік запустить //DZAddTrayIcon. Якщо він уже відображається то потік запустить його //заміну (DZChangeTrayIcon). if Self.cToShowIcon then Self.ProcShowTrayIcon(Self.IconHint); finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetNoSystemBalloonSound(Value: Boolean); Begin if Self.cNoSystemBalloonSound = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cNoSystemBalloonSound:= Value; finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetIconHint(Value: String); Begin if Self.cHint = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cHint:= Value; // Командуємо показати значок із новими параметрами. //Якщо значок не відображається то потік запустить //DZAddTrayIcon. Якщо він уже відображається то потік запустить його //правку (DZChangeTrayIcon). if Self.cToShowIcon then Self.ProcShowTrayIcon(Self.IconHint); finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetDefPauseBeforeHide(Value: DWORD); Begin if Self.cDefPauseBeforeHide = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cDefPauseBeforeHide:= Value; finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetAfterBalloon(Value: TOnBalloonProc); Begin if Addr(Self.cEvtAfterBalloon) = Addr(Value) then Exit; Self.cBalloonCriticalSection.Enter; try Self.cEvtAfterBalloon:= Value; finally Self.cBalloonCriticalSection.Leave; end; End; Procedure TBaloonMessenger.SetSynchronizeEvents(Value: Boolean); Begin if Self.cSynchronizeEvents = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cSynchronizeEvents:= Value; finally Self.cBalloonCriticalSection.Leave; end; End; {Procedure TBaloonMessenger.SetPauseBeforeNext(Value: DWORD); Begin if Self.cPauseBeforeNext = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cPauseBeforeNext:= Value; finally Self.cBalloonCriticalSection.Leave; end; End;} Procedure TBaloonMessenger.SetHideIconOnLastMessageShown(Value: Boolean); const sc_ProcName = 'TBaloonMessenger.SetHideIconOnLastMessageShown'; Begin if Self.cHideIconOnLastMessageShown = Value then Exit; Self.cBalloonCriticalSection.Enter; try Self.cHideIconOnLastMessageShown:= Value; finally Self.cBalloonCriticalSection.Leave; end; // Тільки якщо треба сховати значок після відображення повідомлень: if Value then Begin // Будимо потік щоб він сховав значок, якщо його треба сховати // після відображення повідомлень, і всі вони вже відображені: OSFuncHelper.ProcSetEvent(Self.cChangeIconStateCommand, sc_ProcName + cs_CantSetEvent + cs_OfChangeIconStateCommand + c_SystemSays, Self.cLogFile); While Self.Suspended do Self.Resume; End; End; Procedure TBaloonMessenger.SynchronizedCallBalloonEventProc; const cs_ProcName = 'TBaloonMessenger.SynchronizedCallBalloonEventProc'; Begin try Self.cBalloonEvtToCall(Self, Self.cCurMessage, Self.cCurTitle, Self.cBaloonMessageQueue); except on E:Exception do Begin Self.LogMessage(cs_ProcName + c_DoubleDot + c_Space + cs_CallingBalloonEventException+ c_Space+ cs_WhenSynchronizedWithMain + c_DoubleDot + c_Space+ E.Message, True); End; end; End; // Викликається із потока відображення повідомлень після відображення // повідомлення (при відображенні у кульці - відразу після відображення // кульки; якщо кульку неможливо показати то після відображення і // закривання вікна з повідомленням MessageBox): Procedure TBaloonMessenger.CallAfterBalloonShow(Const sMessage, sTitle: String; Const sBaloonMessageQueue:TStrings); const cs_ProcName = 'TBaloonMessenger.CallAfterBalloonShow'; Var ccSynchronizeEvents: Boolean; ccAfterBalloonShow: TOnBalloonProc; Begin ccSynchronizeEvents:= Self.cSynchronizeEvents; ccAfterBalloonShow:= Self.cEvtAfterBalloon; if System.Assigned(ccAfterBalloonShow) then Begin if ccSynchronizeEvents then Begin Self.cBalloonCriticalSection.Leave; try Self.cCallingEventProcSection.Enter; try Self.cBalloonEvtToCall:= ccAfterBalloonShow; Self.cCurMessage:= sMessage; Self.cCurTitle:= sTitle; Self.Synchronize(Self.SynchronizedCallBalloonEventProc); finally Self.cCallingEventProcSection.Leave; end; finally Self.cBalloonCriticalSection.Enter; end; End Else // якщо не треба синхронізувати із головним потоком: Begin try ccAfterBalloonShow(Self, sMessage, sTItle, Self.cBaloonMessageQueue); except on E:Exception do Begin Self.LogMessage(cs_ProcName + c_DoubleDot + c_Space + cs_CallingBalloonEventException + c_Space+ cs_FromMessagesThread + c_DoubleDot + c_Space+ E.Message, True); End; end; End; End; End; // WindowProc. Процедура реагування на повідомлення до вікна. // Потрібна через те що потік може показувати повідомлення у // MessageBox, що є вікном (хоч і малюється системою). // Для MessageBox потрібне батьківське вікно, яке приймає на себе // повідомлення, бо коли немає кнопки Пуск, не запущений explorer.exe то // MessageBox без батьківського вікна часом не відображається, або // відображається і не відповідає. Так як батьківське вікно має бути із // того ж потока то потік повідомлень створює пусте вікно і приймає на нього // повідомлення. procedure TBaloonMessenger.WindowProc(var sMessage: Messages.TMessage); Var ccCallBackMessageId:UInt; ccWindowToInform: HWND; Begin Self.cBalloonCriticalSection.Enter; try ccCallBackMessageId:= Self.cuCallbackMessage; ccWindowToInform:= Self.cWindow; finally Self.cBalloonCriticalSection.Leave; end; if sMessage.Msg = ccCallBackMessageId then Begin sMessage.Result:= Windows.SendMessage(ccWindowToInform, sMessage.Msg, sMessage.WParam, sMessage.LParam); End Else sMessage.Result:= Windows.DefWindowProc(Self.FWnd, sMessage.Msg, sMessage.WParam, sMessage.LParam); End; procedure TBaloonMessenger.ProcessMessages; Var ccMessage:Windows.TMsg; Begin while Windows.PeekMessage(ccMessage, 0, // читаються всі повідомлення для всіхз вікон і ті що послані із PostThreadMessage 0, // wMsgFilterMin, без ранжування по типам повідомлень 0, // wMsgFilterMax, без ранжування по типам повідомлень Windows.PM_REMOVE) do Begin Windows.TranslateMessage(ccMessage); Windows.DispatchMessage(ccMessage); End; End; procedure TBaloonMessenger.Execute; const c_EventCount = 2; c_ChangeStateCommandIndex = 0; c_TerminateCommandIndex = 1; cs_ProcNameStart = 'Потік TBaloonMessenger.Execute'; Var ccBalloonShowMoment, ccLastMoment, ccCurMoment: Cardinal; // момент останнього відображення значка (мс) ccHandleArray: array [0..c_EventCount - 1] of THandle; cSignal: DWord; //cLastOSError, cs_ProcName:String; cc_ThreadID:THandle; ccPausePendingBeforeNext, ccWaitCommandTimeout:Cardinal; ccMsgBoxNum: Cardinal; //ccICanSleep: Boolean; //ccThisThreadWindow:HWND; Procedure ProcShowOneBalloon(Var sdPauseBeforeNextPending:Cardinal; Var dSuccessful, dMessagesRemained:Boolean); Var ccMessage, ccTitle: String; ccIconType:TBalloonIconAndMessageBoxType; ccShowPause:Cardinal; ccMBoxResult: Integer; ccNoSysSound: Boolean; //ccMessageBoxWindow:HWND; Procedure ProcMessageSuccessful; Begin Self.cBaloonMessageQueue.Delete(0); Self.cBalloonTitleQueue.Delete(0); Self.cBaloonIconQueue.Delete(0); Self.cShowPauseQueue.Delete(0); dSuccessful:= True; sdPauseBeforeNextPending:= ccShowPause; dMessagesRemained:= Self.cBaloonMessageQueue.Count > 0; ccBalloonShowMoment:= Windows.GetTickCount; ccLastMoment:= ccBalloonShowMoment; Self.CallAfterBalloonShow(ccMessage, ccTitle, Self.cBaloonMessageQueue); End; Begin dSuccessful:= False; //dPauseBeforeNext:= 0; if Self.cBaloonMessageQueue.Count > 0 then Begin dMessagesRemained:= True; // Якщо витримана пауза для відображення кульки: if sdPauseBeforeNextPending = 0 then Begin ccMessage:= Self.cBaloonMessageQueue[0]; ccTitle:= Self.cBalloonTitleQueue[0]; ccIconType:= Self.cBaloonIconQueue[0]; ccShowPause:= Self.cShowPauseQueue[0]; ccNoSysSound:= Self.cNoSystemBalloonSound; {Спробую як працюють MessageBox коли насправді панель конпки Пуск запущена..: If Self.ProcShowBalloon(ccMessage, ccTitle, ccIconType.BalloonIconType, ccShowPause, ccNoSysSound) then Begin ProcMessageSuccessful; Self.LogMessage(cs_ProcName+ c_DoubleDot + c_Space+ ccMessage+'" ('+ccTitle+') Ok.', False); End else Begin Self.LogMessage(cs_ProcName+ c_DoubleDot + c_Space+ 'не вдалося показати кульку "'+ccMessage+'" ('+ ccTitle+')...', True); Self.RemoveTrayIcon; if Not(Self.AddTrayIcon(Self.IconHint)) then Begin} // Windows.MessageBox не повертається поки // вікно із повідомленням не закриється // (поки користувач не закриє чи не натисне Ok), // тому тут виходимо із секції роботи потока // щоб інші потоки (що слідкують за цією секцією) // в цей час могли надсилати нові повідомлення. // MessageBoxTimeOut теж не повертається доки вікно не // закриється, проте воно закривається і само якщо користувач // за відведену паузу не натиснув на ньому нічого і не закрив // його: Self.cBalloonCriticalSection.Leave; try //ccMessageBoxWindow:= Self.cNewWindow; // Dialogs.ShowMessage(); // ccMBoxResult:= Dialogs.TaskMessageDlg(ccTitle, ccMessage, // mtInformation, [mbOK], 0); Inc(ccMsgBoxNum); ccMBoxResult:= OsFuncHelper.MessageBoxTimeOut(Self.FWnd, //0, //ccMessageBoxWindow PWideChar(ccMessage), PWideChar(ccTitle // + ' #' + SysUtils.IntToStr(ccMessageBoxWindow) + ' #'+ SysUtils.IntToStr(ccMsgBoxNum) ), // тимчасово, для наладки, важіль батьківського вікна відображати поставив (ccIconType.MessageBoxType and (not MB_AllMessageBoxWndTypeMask)) or MB_TOPMOST, // ci_DefOkMsgBoxType, MB_OK or MB_TOPMOST, //MB_TASKMODAL, MB_SYSTEMMODAL, //MB_SETFOREGROUND не гарантує появу вікна поверх інших вікон.. воно тільки ставить його поверх інших вікон програми. І це не усуває глюк із повідомленнями при вводі пароля 1С7.7. 0, ccShowPause); //Windows.MessageBox(0, PWideChar(ccMessage), // PWideChar(ccTitle), MB_OK or MB_SETFOREGROUND); //MB_TOPMOST напевно не підходить. Вікно зависає або не відображається взагалі при вході в 1С7 коли відображається повідомлення про невірний пароль... finally Self.cBalloonCriticalSection.Enter; End; If ccMBoxResult = 0 then Begin Self.LogLastOSError(cs_ProcName+ c_DoubleDot + c_Space+ 'не вдалося показати кульку "'+ccMessage+'" ('+ ccTitle+')... '+c_SystemSays); Windows.Sleep(c_EmergencySleepTime); End Else Begin // Альтернативне вікно з повідомленням відображається // доки користувач не натисне кнопку Ok, // тут воно вже закрилося, тому паузи робити не треба, можна // показувати наступне повідомлення: ccShowPause:= 0; ProcMessageSuccessful; End; {End; End;} End; End Else dMessagesRemained:= False; End; procedure ProcCommands(); //var dRunOnceMore:Boolean var ccShowMoreMessagesPending, ccBaloonShown:Boolean; ccPause:Cardinal; ccTerminateEvent:THandle; Begin ccShowMoreMessagesPending:= False; ccBaloonShown:= False; //ccCurMoment:= Windows.GetTickCount; // Оновлення паузи яку ще слід чекати: ccPause:= ccCurMoment - ccBalloonShowMoment; if ccPause > ccPausePendingBeforeNext then ccPausePendingBeforeNext:= 0 Else ccPausePendingBeforeNext:= ccPausePendingBeforeNext - ccPause; // Якщо була команда показати чи заховати значок: if Self.cToShowIcon then Begin if Not(Self.cIconVisible) then Begin Self.AddTrayIcon(Self.IconHint); End else Begin // Якщо задано новий ідентифікатор значка або // ідентифікатор повідомлення про натискання на значок // то намагаємося спочатку сховати старий значок, бо з новими // ідентифікатораим буде новий: if (Self.cNewIconID<>Self.cIconID) //(Self.cNewWindow<>Self.cWindow) or or (Self.cNewuCallbackMessage<>Self.cuCallbackMessage) then Begin Self.RemoveTrayIcon; Self.AddTrayIcon(Self.IconHint); End Else // якщо важелі значка ті самі: Begin // запускаємо оновлення значка: if Not(Self.ChangeTrayIcon(Self.IconHint)) then // якщо змінити не можна - може значок система видалила через те що вікно закрилося... Спробуємо показати знову: Begin Self.RemoveTrayIcon; Self.AddTrayIcon(Self.IconHint); End; End; End; // Навіть якщо значок не вдалося показати - намагаємося // показати повідомлення. В значку це не можливо, та ProcShowOneBalloon // покаже альтернативним методом, бо було задано показати: //if Self.cIconVisible then // якщо значок відображається: //Begin ProcShowOneBalloon(ccPausePendingBeforeNext, ccBaloonShown, ccShowMoreMessagesPending); //ccPause // // Якщо повідомлення успішно показано то беремо паузу почекати // // перед відображенням наступного: //if ccBaloonShown then // ccPause:= Self.cPauseBeforeNext; //End; End // Якщо показувати значок не треба проте він не захований: Else if Self.cIconVisible then Begin Self.RemoveTrayIcon; End; if ccShowMoreMessagesPending then // якщо є ще повідомлення: Begin //if ccBaloonShown then // якщо відобразили кульку то треба зробити паузу: //Begin // Витримування паузи перед відображенням наступного повідомлення: if ccPausePendingBeforeNext > 0 then Begin ccTerminateEvent:= Self.cTerminateEvent; Self.cBalloonCriticalSection.Leave; try //cSignal:= Windows.WaitForSingleObject(Self.cTerminateEvent, // ccPausePendingBeforeNext); cSignal:= Windows.MsgWaitForMultipleObjects(1, ccTerminateEvent, False, ccPausePendingBeforeNext, QS_ALLINPUT); finally Self.cBalloonCriticalSection.Enter; end; ccCurMoment:= Windows.GetTickCount; if cSignal = Windows.WAIT_FAILED then begin Self.LogLastOSError(cs_ProcName + c_DoubleDot + c_Space + cs_WaitForCommandBetweenBalloons + cs_ReportedAnError + c_SystemSays); Windows.Sleep(c_EmergencySleepTime); // якщо очікування не вдається - то принаймні не завантажуємо процесора і очікуємо приходу кращого часу... end else // обробляємо повідомлення для потока і його вікон якщо такі були: Self.ProcessMessages; End; End Else // якщо повідомлень у черзі немає то команди оброблені: Begin OSFuncHelper.ProcResetEvent(Self.cChangeIconStateCommand, cs_ProcName + cs_CantResetEvent + cs_OfChangeIconStateCommand + c_SystemSays, Self.cLogFile); End; End; Begin cc_ThreadID:= Windows.GetCurrentThreadId; // Якщо процедуру запустили насправді не від того потока що // записано в об'єкті (з якихось причин...): if Self.ThreadID<>cc_ThreadID then Begin cs_ProcName:= cs_ProcNameStart+' (ID='+SysUtils.IntToStr(Self.ThreadID)+ '<>'+SysUtils.IntToStr(cc_ThreadID)+')'; Self.LogMessage(cs_ProcName + ' запущено від іншого потока із ID='+ SysUtils.IntToStr(cc_ThreadID)+'!..', True); End Else cs_ProcName:= cs_ProcNameStart+' (ID='+SysUtils.IntToStr(Self.ThreadID)+')'; ccPausePendingBeforeNext:= 0; try Self.LogMessage(cs_ProcName + sc_StartsItsWork, False); ccBalloonShowMoment:= 0; ccLastMoment:= 0; ccMsgBoxNum:= 0; // Створюємо вікно для цього потока і вказуємо процедуру для // обробки повідомлень що приходитимуть до вікна: Self.FWnd:= Classes.AllocateHWnd(Self.WindowProc); ccCurMoment:= Windows.GetTickCount; Self.cBalloonCriticalSection.Enter; try while Not(Self.Terminated) do Begin if ccPausePendingBeforeNext = 0 then Begin if Self.cDefPauseBeforeHide = 0 then ccWaitCommandTimeout:= c_EmergencySleepTime Else ccWaitCommandTimeout:= Self.cDefPauseBeforeHide; End Else Begin ccWaitCommandTimeout:= ccPausePendingBeforeNext; End; // Очікування команд: // Масив подій, на які треба очікувати: ccHandleArray[c_ChangeStateCommandIndex]:= Self.cChangeIconStateCommand; // подія подачі команди на виконання ccHandleArray[c_TerminateCommandIndex]:= Self.cTerminateEvent; // команда для потока (завершити роботу) Self.cBalloonCriticalSection.Leave; try // Очікуємо одну із можливих подій, але не довше за час до // ховання кульки з повідомленням: cSignal:= Windows.MsgWaitForMultipleObjects(c_EventCount, ccHandleArray, False, ccWaitCommandTimeout, QS_ALLINPUT); finally Self.cBalloonCriticalSection.Enter; end; // Обробляємо команди які були дані: ccCurMoment:= Windows.GetTickCount; if cSignal = Windows.WAIT_FAILED then begin Self.LogLastOSError(cs_ProcName + c_DoubleDot + c_Space + cs_WaitForCommand + cs_ReportedAnError + c_SystemSays); Windows.Sleep(c_EmergencySleepTime); // якщо очікування не вдається - то принаймні не завантажуємо процесора і очікуємо приходу кращого часу... end else if cSignal = Windows.WAIT_TIMEOUT then // якщо дочекалися до ccWaitCommandTimeout: Begin if (ccCurMoment - ccLastMoment >= ccPausePendingBeforeNext) then Begin if Self.cHideIconOnLastMessageShown and Self.cIconVisible then Self.RemoveTrayIcon; ccPausePendingBeforeNext:= 0; End else // виявляється, буває що і при таймауті після очікування // ccWaitCommandTimeout = ccPausePendingBeforeNext // GetTickCount показує що пройшло на одну (чи декілька) // мілісекунд менше за ту паузу що витримана у // WaitForMultipleObjects. Можливо, різні таймери, в них // похибка... // Тому поправляємо і чекаємо ще той час який не дочекали...: Begin ccPausePendingBeforeNext:= ccPausePendingBeforeNext - (ccCurMoment - ccLastMoment); ccLastMoment:= ccCurMoment; End; if ccPausePendingBeforeNext = 0 then Begin // Більше чекати нічого крім команд. При подачі команд // потік мають розбудити. Тому потік може спати: Self.cBalloonCriticalSection.Leave; try Self.Suspend; finally Self.cBalloonCriticalSection.Enter; end; End; End else if cSignal = Windows.WAIT_OBJECT_0 + c_TerminateCommandIndex then // якщо треба завершувати роботу: Begin Continue; // перевіряємо помітку про завершення роботи і виходимо End else if cSignal = Windows.WAIT_OBJECT_0 + c_ChangeStateCommandIndex then // якщо є команда: Begin ProcCommands; End Else if cSignal >= WAIT_ABANDONED_0 then Begin Self.LogMessage(cs_ProcName + c_DoubleDot + c_Space + cs_WaitForCommand + cs_ReturnedUnknownResult + SysUtils.IntToStr(cSignal) + c_Space + sc_TriSpot, True); Windows.Sleep(c_EmergencySleepTime); End // Якщо це не ті об'єкти які замовляли чекати і не повідомлення // "WAIT_ABANDONED", і не таймаут, то є повідомлення для вікон потока: Else // оброблюємо всі повідомлення вікнам потока, що є у черзі: Begin Self.ProcessMessages; End; End; // Якщо вкінці роботи потока значок не прибраний то прибираємо його: Self.CleanUpAfterWork; finally Self.cBalloonCriticalSection.Leave; // Звільняємо пусте вікно, що створене було для цього потока: Classes.DeallocateHWnd(Self.FWnd); Self.FWnd:= 0; end; Self.LogMessage(cs_ProcName+sc_FinishedItsWork, False); except on E:Exception do begin Self.cLogFile.WriteMessage(cs_ProcName + sc_FallenOnError+ E.Message); end; end; End; function TBaloonMessenger.CheckSelfExitCode:DWord; const cs_ProcName = 'TBaloonMessenger.CheckSelfExitCode'; Begin Result:= High(Result); if Not(Windows.GetExitCodeThread(Self.Handle, Result)) then Begin Self.LogLastOSError(cs_ProcName+c_DoubleDot+ c_Space + 'GetExitCodeThread'+ cs_ReportedAnError+c_SystemSays); End; End; Procedure TBaloonMessenger.CleanUpAfterWork; const cs_ProcName = 'TBaloonMessenger.CleanUpAfterWork'; var cc_ThreadExitCode:DWord; Procedure ProcCleanUp; Begin if Self.cIconVisible then Self.RemoveTrayIcon; End; Begin if Self.ThreadID = Windows.GetCurrentThreadId then Begin ProcCleanUp; End Else Begin cc_ThreadExitCode:= Self.CheckSelfExitCode; if cc_ThreadExitCode<>STILL_ACTIVE then Begin if Self.IconVisible then Begin Self.LogMessage(cs_ProcName+c_DoubleDot+ c_Space + 'потік BalloonMessenger (ID='+ SysUtils.IntToStr(Self.ThreadID)+ ') УЖЕ не запущений, повернув код='+ SysUtils.IntToStr(cc_ThreadExitCode)+ ', проте значок не захований...', True); ProcCleanUp; End; End; End; End; //------------- Поділ повідомлення на частини -------------- Procedure CutShowTime(sFullTime:Cardinal; sCuttedLen, sFullLength:Integer; //, sRemainedLen Var dCuttedTime:Cardinal); var ccCuttedLen, ccFullTime, ccFullLen:UInt64; //ccFullLen //ccFullTime, //ccRemainedLen Begin //ci_ShowTimeAddition //ccFullLen:= sCuttedLen+sRemainedLen; //ccFullTime:= sFullTime; //ccRemainedLen:= sRemainedLen; if sFullLength = 0 then Begin dCuttedTime:= sFullTime + ci_ShowTimeAddition; //dRemainedTime:= 0; End Else Begin ccCuttedLen:= sCuttedLen; ccFullTime:= sFullTime; ccFullLen:= sFullLength; //dRemainedTime:= (ccFullTime*ccRemainedLen) div ccFullLen; dCuttedTime:= (ccFullTime*ccCuttedLen) div ccFullLen; // До відкушеного часу додаємо мінімальний гарантований час відображення // кульки. Кулька відображатиметься протягом цього часу і ще // протягом поправки на довжину тексту, яка тут відкушена: dCuttedTime:= dCuttedTime + ci_ShowTimeAddition; End; { dCuttedTime/dRemainedTime = sCuttedLen / sRemainedLen, dCuttedTime+dRemainedTime = sFullTime; dRemainedTime = dCuttedTime/(sCuttedLen / sRemainedLen); dRemainedTime = dCuttedTime*sRemainedLen/sCuttedLen; dCuttedTime+dCuttedTime*sRemainedLen/sCuttedLen = sFullTime; dCuttedTime*(1+sRemainedLen/sCuttedLen) = sFullTime; dCuttedTime = sFullTime/(1+sRemainedLen/sCuttedLen); dCuttedTime = sFullTime*sCuttedLen/(sCuttedLen+sRemainedLen); dRemainedTime = (sFullTime/(1+sRemainedLen/sCuttedLen))*sRemainedLen/sCuttedLen; dRemainedTime = (sFullTime*sRemainedLen/((1+sRemainedLen/sCuttedLen)*sCuttedLen)); dRemainedTime = sFullTime*sRemainedLen/(sCuttedLen+sRemainedLen); dRemainedTime = sFullTime/(sCuttedLen/sRemainedLen+1); } End; Function TryToCut( Const sSuffix: String; Var sdCutPiece: String; Const sMessage: String; Var sdStartPos: Integer; //Var sdRemainedString:String; sMaxLen:Integer; sCutAllIfFits:Boolean = True):Boolean; Var ccLength, ccFullCutLength:Integer; ccCutPiece:String; ccStartPos, ccNewStartPos: Integer; Begin Result:= False; ccLength:= System.Length(sMessage) - sdStartPos + 1; //ccFullCutLength:= System.Length(sdCutPiece); if sCutAllIfFits then // якщо можна не кусати коли все вміщається: Begin //ccLength:= System.Length(sMessage) - sdStartPos + 1; ccFullCutLength:= System.Length(sdCutPiece) + ccLength; Result:= (ccLength > 0) and (ccFullCutLength <= sMaxLen); End; if Result then // якщо й так все вміщається і нічого кусати не треба: Begin sdCutPiece:= sdCutPiece + System.Copy(sMessage, sdStartPos, ccLength); sdStartPos:= sdStartPos + ccLength; End Else Begin ccStartPos:= sdStartPos; DataHelper.PrepareToCutFromPosToSuffix(sMessage, sSuffix, ccStartPos, ccLength, ccNewStartPos, False, True); // суфікс відкушується разом із відкушеним //ccCutPiece:= DataHelper.CutFromPosToSuffix(sMessage, sSuffix, // ccStartPos, // False, True); //ccLength:= System.Length(ccCutPiece); ccFullCutLength:= System.Length(sdCutPiece) + ccLength; Result:= (ccLength > 0) and // якщо підрядки sSuffix є і щось відкусили (ccFullCutLength <= sMaxLen); // і відкушене вміщається if Result then // якщо вміщається - додаємо до відкушеного: Begin ccCutPiece:= System.Copy(sMessage, ccStartPos, ccLength); sdCutPiece:= sdCutPiece + ccCutPiece; sdStartPos:= ccNewStartPos; End; End; End; // Рекурсивна процедура додавання повідомлення в чергу із // поділом його на частини що можна відобразити: // Якщо довжина повідомлення p_Message завелика щоб показати його // у кульці трея то ділить повідомлення на декілька і додає їх у чергу. // При цьому повідомлення ділиться по рядкам. Якщо один рядок // всеодно задовгий то він ділиться по словам по пробілам. Якщо // слово надто довге то ділить його за максимальною довжиною що можна // вмістити. // Якщо sPauseBeforeHide не рівна нулю то змінює час відображення // кульки PauseBeforeHide (у мілісекундах) після відображення // останнього повідомлення. Procedure TBaloonMessenger.ProcAddMessageToQueue(const BalloonText, BalloonTitle: String; const BalloonIconType: TBalloonIconType; Const sMessageBoxType: DWORD; sPauseBeforeHide:Cardinal); Var ccLength, ccRemainedPos, ccFullLength:Integer; ccCutString: String; //, ccRemainedString ccCutted, ccRowsCutted, ccWordsCutted:Boolean; ccShowTimeCutted: Cardinal; //, ccShowTimeRemained ccBalloonIconAndMsgBoxType: TBalloonIconAndMessageBoxType; Begin {ccLength:= System.Length(BalloonText); if ccLength > ci_MaxTrayBaloonInfoLen then Begin} //ccRemainedString:= BalloonText; ccRemainedPos:= 1; ccFullLength:= System.Length(BalloonText); if sPauseBeforeHide = 0 then Begin if ccFullLength = 0 then sPauseBeforeHide:= Self.DefPauseBeforeHide else sPauseBeforeHide:= ccFullLength * ci_DefMillisecondsPerSymbol; End; //ccShowTimeRemained:= sPauseBeforeHide; repeat ccRowsCutted:= False; ccWordsCutted:= False; ccCutString:= ''; ccShowTimeCutted:= 0; repeat // відкушуємо і додаємо до відкушеного доки вміщається: // Поділ на рядки: ccCutted:= TryToCut(c_CR+c_LF, ccCutString, BalloonText, ccRemainedPos, ci_MaxTrayBaloonInfoLen); if ccCutted then ccRowsCutted:= True Else Begin // якщо поділів c_CR+c_LF нема ccCutted:= TryToCut(c_CR, ccCutString, BalloonText, ccRemainedPos, ci_MaxTrayBaloonInfoLen); if ccCutted then ccRowsCutted:= True Else Begin // якщо поділів c_CR нема ccCutted:= TryToCut(c_LF, ccCutString, BalloonText, ccRemainedPos, ci_MaxTrayBaloonInfoLen); if ccCutted then ccRowsCutted:= True // Слова кусаємо тільки якщо не відкусився ні один рядок: Else if Not(ccRowsCutted) then Begin // якщо поділів c_LF нема ccCutted:= TryToCut(c_Space, ccCutString, BalloonText, ccRemainedPos, ci_MaxTrayBaloonInfoLen); if ccCutted then ccWordsCutted:= True // Якщо нічого не відкушується, то вставляємо // скільки вміщається по довжині: Else if Not(ccRowsCutted or ccWordsCutted) then Begin ccCutString:= System.Copy(BalloonText, ccRemainedPos, ci_MaxTrayBaloonInfoLen); ccLength:= System.Length(ccCutString); ccRemainedPos:= ccRemainedPos + ccLength; // CutShowTime(sPauseBeforeHide, ccLength, // System.Length(ccRemainedString), // ccShowTimeCutted, ccShowTimeRemained); End; End; End; End; until Not(ccCutted); CutShowTime(sPauseBeforeHide, System.Length(ccCutString), ccFullLength, ccShowTimeCutted); {CutShowTime(sPauseBeforeHide, , ccFullLength - ccRemainedPos + 1, ccShowTimeCutted, ccShowTimeRemained);} ccBalloonIconAndMsgBoxType.BalloonIconType:= BalloonIconType; ccBalloonIconAndMsgBoxType.MessageBoxType:= sMessageBoxType; Self.cBaloonMessageQueue.Add(ccCutString); Self.cBalloonTitleQueue.Add(BalloonTitle); Self.cBaloonIconQueue.Add(ccBalloonIconAndMsgBoxType); Self.cShowPauseQueue.Add(ccShowTimeCutted); // Якщо якась частина повідомлення не вмістилася то // ділимо її при потребі і додаємо далі в чергу, // з тим самим заголовком і значком кульки: //але робимо це звичайним циклои repeat, а не рекурсією: //if ccRemainedString <> '' then //Begin // Self.ProcAddMessageToQueue(ccRemainedString, BalloonTitle, // BalloonIconType, ccShowTimeRemained); //End; until ccRemainedPos > ccFullLength; { End Else Begin Self.cBaloonMessageQueue.Add(BalloonText); Self.cBalloonTitleQueue.Add(BalloonTitle); Self.cBaloonIconQueue.Add(BalloonIconType); End;} End; //------------- TBaloonIconTypesList -------------- Function ReadBaloonIconAndMsgBoxType(sPnt:PBalloonIconAndMessageBoxType):TBalloonIconAndMessageBoxType; Begin Result:= sPnt^; End; Function WriteBaloonIconAndMsgBoxType(sType:TBalloonIconAndMessageBoxType):PBalloonIconAndMessageBoxType; Begin //Result:= Nil; System.New(Result); Result^:= sType; End; Procedure FreeAndNilBaloonIconAndMsgBoxType(Var sPnt:PBalloonIconAndMessageBoxType); Begin if sPnt <> Nil then Begin System.Dispose(sPnt); //System.FreeMem(sBuf); sPnt:= Nil; End; End; procedure TBaloonIconTypesList.Notify(Ptr: Pointer; Action: TListNotification); Begin End; function TBaloonIconTypesList.Get(Index: Integer): TBalloonIconAndMessageBoxType; Begin Result:= ReadBaloonIconAndMsgBoxType(Inherited Get(Index)); End; procedure TBaloonIconTypesList.Put(Index: Integer; Const Item: TBalloonIconAndMessageBoxType); Begin Inherited Put(Index, WriteBaloonIconAndMsgBoxType(Item)); End; function TBaloonIconTypesList.Add(Const Item: TBalloonIconAndMessageBoxType): Integer; Begin Add:= Inherited Add(WriteBaloonIconAndMsgBoxType(Item)); End; procedure TBaloonIconTypesList.Clear; Begin // Перед очисткою списка звільняємо пам'ять від усіх елементів, що у ньому: while Self.Count > 0 do Self.Delete(0); Inherited Clear; End; procedure TBaloonIconTypesList.Delete(Index: Integer); Var cItem:PBalloonIconAndMessageBoxType; Begin cItem:= Inherited Get(Index); Self.List^[Index]:=Nil; Inherited Delete(Index); if cItem <> Nil then Begin Self.Notify(cItem, Classes.lnDeleted); FreeAndNilBaloonIconAndMsgBoxType(cItem); End; End; function TBaloonIconTypesList.Remove(Item: TBalloonIconAndMessageBoxType): Integer; Begin Result := IndexOf(Item); if Result >= 0 then Self.Delete(Result); End; function TBaloonIconTypesList.Extract(Const Item: TBalloonIconAndMessageBoxType): TBalloonIconAndMessageBoxType; Var cIndex: Integer; Begin cIndex:= Self.IndexOf(Item); if cIndex >= 0 then Result:= Self.ExtractByNum(cIndex) Else Begin Result.BalloonIconType:= bitNone; //''; Result.MessageBoxType:= ci_DefOkMsgBoxType; End; End; function TBaloonIconTypesList.ExtractByNum(Index: Integer): TBalloonIconAndMessageBoxType; Var cItem:PBalloonIconAndMessageBoxType; Begin cItem:= Inherited Get(Index); Result:= ReadBaloonIconAndMsgBoxType(cItem); Self.List^[Index]:=Nil; Inherited Delete(Index); Self.Notify(cItem, Classes.lnExtracted); FreeAndNilBaloonIconAndMsgBoxType(cItem); End; function TBaloonIconTypesList.First: TBalloonIconAndMessageBoxType; Begin First:= ReadBaloonIconAndMsgBoxType(Inherited First); End; function TBaloonIconTypesList.ExtractFirst: TBalloonIconAndMessageBoxType; Begin ExtractFirst:= Self.ExtractByNum(0); End; Procedure TBaloonIconTypesList.Insert(Index: Integer; Const Item: TBalloonIconAndMessageBoxType); Begin Inherited Insert(Index, WriteBaloonIconAndMsgBoxType(Item)); End; function TBaloonIconTypesList.Last: TBalloonIconAndMessageBoxType; Begin Last:= ReadBaloonIconAndMsgBoxType(Inherited Last); End; function TBaloonIconTypesList.ExtractLast: TBalloonIconAndMessageBoxType; Begin ExtractLast:= Self.ExtractByNum(Self.Count - 1); End; // Виконує пошук у списку...: function TBaloonIconTypesList.IndexOf(Const Item: TBalloonIconAndMessageBoxType): Integer; var LCount: Integer; cItem, cSourceItem: TBalloonIconAndMessageBoxType; begin LCount := Self.Count; cSourceItem:= Item; for Result := 0 to LCount - 1 do // new optimizer doesn't use [esp] for Result Begin cItem:= Self.Get(Result); if (cItem.BalloonIconType = cSourceItem.BalloonIconType) and (cItem.MessageBoxType = cSourceItem.MessageBoxType) then Begin Exit; End; End; Result := -1; end; // Ініціалізація констант про довжину рядків у NotifyIconData. // Не вдалося зробити це в оголошенні констант. Procedure ReadNotifyIconDataStringsLength; Var ccDummyData: NotifyIconData; Begin // -1 - з поправкою на нуль-символ, бо рядки там з нулями вкінці: ci_MaxTrayTipLen:= System.Length(ccDummyData.szTip) - 1; ci_MaxTrayBaloonInfoLen:= System.Length(ccDummyData.szInfo) - 1; ci_MaxTrayBaloonTitleLen:= System.Length(ccDummyData.szInfoTitle) - 1; End; initialization ReadNotifyIconDataStringsLength; end.
unit UFrameAnalog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Buttons, UTreeItem, IniFiles, UFrameKP; type TItemAnalog = class; TFrameAnalog = class(TFrame) Panel: TPanel; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label7: TLabel; Label6: TLabel; BtnChange: TButton; cbOn: TCheckBox; stStatus: TStaticText; edR: TEdit; edIa: TEdit; edIb: TEdit; edXa: TEdit; edXb: TEdit; edXmin: TEdit; procedure BtnChangeClick(Sender: TObject); procedure cbOnClick(Sender: TObject); private { Private declarations } Analog:TItemAnalog; public { Public declarations } end; TItemAnalog = class(TTreeItem) public KP:TItemKP; NetNumber:Integer; CoeffR,CoeffIa,CoeffIb,CoeffXa,CoeffXb,CoeffXmin:Double; isSensorOn:Boolean; FA:TFrameAnalog; DataList:TStringList; CntX,CntE,LCntX,LCntE:Integer; FreshDataTimer:Integer; SumX,X:Double; EMsg:String; constructor Load(Nodes:TTreeNodes; ParentNode:TTreeNode; Ini,Cfg:TIniFile; const Section:String); function Enter(Owner:TComponent):TFrame;override; function Leave:Boolean;override; function Validate:Boolean;override; procedure SaveCfg(Cfg:TIniFile);override; procedure TimerProc;override; procedure RefreshFrame; procedure GetX(const SrcData; var X:Single); private CoeffK,CoeffB:Double; procedure CalcKB; end; implementation uses Misc, SensorTypes; {$R *.DFM} procedure TFrameAnalog.BtnChangeClick(Sender: TObject); begin Analog.ChangeData(BtnChange,Panel); end; { TItemAnalog } function TItemAnalog.Enter(Owner:TComponent): TFrame; begin FA:=TFrameAnalog.Create(Owner); FA.Analog:=Self; FA.Name:=''; FA.cbOn.Caption:='Канал №'+IntToStr(NetNumber); FA.cbOn.Checked:=isSensorOn; FA.edR.Text:=Format('%g',[CoeffR]); FA.edIa.Text:=Format('%g',[CoeffIa]); FA.edXa.Text:=Format('%g',[CoeffXa]); FA.edIb.Text:=Format('%g',[CoeffIb]); FA.edXb.Text:=Format('%g',[CoeffXb]); FA.edXmin.Text:=Format('%g',[CoeffXmin]); RefreshFrame; Result:=FA; end; function TItemAnalog.Leave: Boolean; begin FA.Free; FA:=nil; Result:=True; end; constructor TItemAnalog.Load(Nodes:TTreeNodes; ParentNode:TTreeNode; Ini,Cfg: TIniFile; const Section: String); begin inherited; Self.Section:=Section; KP:=TObject(ParentNode.Data) as TItemKP; Node:=Nodes.AddChildObject(ParentNode,Section,Self); NetNumber:=Ini.ReadInteger(Section,'NetNumber',0); isSensorOn:=Cfg.ReadBool(Section,'On',True); CoeffR:=Cfg.ReadFloat(Section,'R',124); CoeffIa:=Cfg.ReadFloat(Section,'Ia',0.004); CoeffXa:=Cfg.ReadFloat(Section,'Xa',0); CoeffIb:=Cfg.ReadFloat(Section,'Ib',0.020); CoeffXb:=Cfg.ReadFloat(Section,'Xb',Cfg.ReadFloat(Section,'P',60)); CoeffXmin:=Cfg.ReadFloat(Section,'Xmin',-1); CalcKB; end; procedure TItemAnalog.TimerProc; begin if CntX>0 then begin LCntE:=0; X:=SumX/CntX; LCntX:=CntX; end else begin LCntX:=0; if CntE>0 then LCntE:=CntE; end; if FA<>nil then RefreshFrame; if FreshDataTimer>0 then Dec(FreshDataTimer); SumX:=0; CntX:=0; CntE:=0; end; function TItemAnalog.Validate: Boolean; var CR,CIa,CXa,CIb,CXb,CXmin:Double; begin try CheckMinMax(CR, 1, 999, FA.edR ); CheckMinMax(CIa, 0.00, 1, FA.edIa ); CheckMinMax(CXa, -1E38, 1E38, FA.edXa ); CheckMinMax(CIb, 0.00, 1, FA.edIb ); CheckMinMax(CXb, -1E38, 1E38, FA.edXb ); CheckMinMax(CXmin,-1E38, 1E38, FA.edXmin); CoeffR :=CR; CoeffIa :=CIa; CoeffXa :=CXa; CoeffIb :=CIb; CoeffXb :=CXb; CoeffXmin:=CXmin; CalcKB; Result:=True; except Result:=False; end; end; procedure TItemAnalog.SaveCfg(Cfg: TIniFile); begin // Ini.WriteInteger(Section,'NetNumber',NetNumber); Cfg.WriteBool( Section, 'On', isSensorOn); Cfg.WriteFloat(Section, 'R' , CoeffR ); Cfg.WriteFloat(Section, 'Ia', CoeffIa); Cfg.WriteFloat(Section, 'Xa', CoeffXa); Cfg.WriteFloat(Section, 'Ib', CoeffIb); Cfg.WriteFloat(Section, 'Xb', CoeffXb); Cfg.WriteFloat(Section,'Xmin',CoeffXmin); end; procedure TItemAnalog.RefreshFrame; begin if LCntX>0 then begin FA.stStatus.Caption:=Format('%3d | %7.3f ',[LCntX,X]); if FreshDataTimer>0 then FA.stStatus.Font.Color:=clLime else FA.stStatus.Font.Color:=clGreen; end else if (LCntE>0) and (EMsg<>'') then begin FA.stStatus.Caption:=Format('%3d:'+EMsg,[LCntE]); if FreshDataTimer>0 then FA.stStatus.Font.Color:=clRed else FA.stStatus.Font.Color:=clMaroon; end; FA.cbOn.Checked:=isSensorOn; end; procedure TItemAnalog.CalcKB; var Ua,Ub:Double; begin Ua:=CoeffIa*CoeffR; Ub:=CoeffIb*CoeffR; try CoeffK := (CoeffXb - CoeffXa) / (Ub - Ua); CoeffB := -CoeffK * Ua + CoeffXa; except CoeffK := 0; CoeffB := 0; end; end; procedure TItemAnalog.GetX(const SrcData; var X: Single); const fErrorFlag =$8000; fErrorComm =$4000; fErrorADCRange=$2000; fErrorInvData =$1000; fErrorInvResp =$0800; Prescale=2.5/32767; var AD:TAnalogData; Tmp:Word; begin FreshDataTimer:=1; Tmp:=0; move(SrcData,Tmp,2); if Tmp and fErrorFlag<>0 then begin // признак сбоя Inc(CntE); if EMsg='' then EMsg:=' __ __ __ '; if Tmp and (fErrorComm or fErrorInvData or fErrorInvResp)<>0 then begin SetErrADCComm(AD); EMsg[1]:='C'; EMsg[2]:='o'; EMsg[3]:='m'; end else if Tmp and fErrorADCRange<>0 then begin SetErrADCRange(AD); EMsg[5]:='R'; EMsg[6]:='n'; EMsg[7]:='g'; end else begin SetErrUnknown(AD); EMsg[9]:='E'; EMsg[10]:='r'; EMsg[11]:='r'; end; if not isSensorOn then SetSensorRepair(AD); end else begin EMsg:=''; AD.Value:=Tmp*Prescale*CoeffK+CoeffB; Inc(CntX); SumX:=SumX+AD.Value; if AD.Value < CoeffXmin then SetErrAnalog(AD); end; X:=AD.Value; end; procedure TFrameAnalog.cbOnClick(Sender: TObject); begin Analog.isSensorOn:=cbOn.Checked; end; end.
unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Registry, ComCtrls, StdCtrls, ShellAPI; type TfrmMain = class(TForm) btnClose: TButton; btnHelp: TButton; lvwItems: TListView; btnDelete: TButton; btnRefresh: TButton; procedure ReadItems(); procedure FormCreate(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnHelpClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} procedure TfrmMain.ReadItems(); var reg: TRegistry; values: TStringList; i: integer; item: TListItem; begin // cleaning the list lvwItems.Clear(); // initializing reader reg:=TRegistry.Create(); values:=TStringList.Create(); // reading the HKCU reg.RootKey:=HKEY_CURRENT_USER; if reg.OpenKeyReadOnly('\Software\Microsoft\Windows\CurrentVersion\Run') then begin reg.GetValueNames(values); if (values.Count>0) then begin for i:=0 to (values.Count-1) do begin if ((reg.GetDataType(values[i])=rdString) or (reg.GetDataType(values[i])=rdExpandString)) then begin item:=lvwItems.Items.AddItem(nil); item.SubItems.Add(values[i]); item.SubItems.Add(reg.ReadString(values[i])); item.SubItems.Add('HKCU'); end; end; end; reg.CloseKey(); end; // reading the HKLM reg.RootKey:=HKEY_LOCAL_MACHINE; if reg.OpenKeyReadOnly('\Software\Microsoft\Windows\CurrentVersion\Run') then begin reg.GetValueNames(values); if (values.Count>0) then begin for i:=0 to (values.Count-1) do begin if ((reg.GetDataType(values[i])=rdString) or (reg.GetDataType(values[i])=rdExpandString)) then begin item:=lvwItems.Items.AddItem(nil); item.SubItems.Add(values[i]); item.SubItems.Add(reg.ReadString(values[i])); item.SubItems.Add('HKLM'); end; end; end; reg.CloseKey(); end; // the end FreeAndNil(reg); FreeAndNil(values); end; procedure TfrmMain.FormCreate(Sender: TObject); begin // reading the data ReadItems(); end; procedure TfrmMain.btnCloseClick(Sender: TObject); begin Close(); end; procedure TfrmMain.btnRefreshClick(Sender: TObject); begin ReadItems(); end; procedure TfrmMain.btnDeleteClick(Sender: TObject); var reg: TRegistry; i: integer; begin // confirmation if (Application.MessageBox('Are you sure you want to delete selected items?'#10#13'WARNING: Deletion of unknown entries can cause your computer to fail! If you are not sure - click "No"!','Futuris Run Manager',MB_YESNO + MB_ICONQUESTION)=IDYES) then begin reg:=TRegistry.Create(); for i:=0 to (lvwItems.Items.Count-1) do begin if lvwItems.Items[i].Checked then begin if (lvwItems.Items[i].SubItems[2]='HKCU') then reg.RootKey:=HKEY_CURRENT_USER else reg.RootKey:=HKEY_LOCAL_MACHINE; if reg.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Run',false) then begin reg.DeleteValue(lvwItems.Items[i].SubItems[0]); reg.CloseKey(); end; end; end; FreeAndNil(reg); // rereading the data ReadItems(); end; end; procedure TfrmMain.btnHelpClick(Sender: TObject); begin ShellExecute(frmMain.Handle,'open',PChar(ExtractFilePath(Application.ExeName) + 'runm.chm'),nil,nil,SW_SHOWNORMAL); end; procedure TfrmMain.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then Close(); end; end.
{ Source Name: ToolTipApi Description: usefull functions for using windows tooltips Copyright (C) Martin Krämer <MartinKraemer@gmx.net> Source Forge Site https://sourceforge.net/projects/sharpe/ SharpE Site http://www.sharpenviro.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 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 ToolTipApi; interface uses SysUtils,Controls,Classes,Windows,Messages,Commctrl; function RegisterBallonWindow(Control : TWinControl) : hwnd; procedure AddBalloonWindowCallBack(BWnd : hwnd; Control : TWinControl; ID : Cardinal; Icon : integer; Titel : String; Rect : TRect); procedure SetBalloonPosition(BWnd : hwnd; X,Y : integer); procedure SetBalloonTracking(BWnd : hwnd; Control: TWinControl; ID : Cardinal;Activate : boolean); function RegisterToolTip(Control: TWinControl) : hwnd; procedure EnableToolTip(TipWnd : hwnd); procedure DisableToolTip(TipWnd : hwnd); procedure SetTipTitel(TipWnd : hwnd; Icon : integer; Titel : String); procedure AddToolTip(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Rect : TRect; Text : String); procedure AddToolTipByCallBack(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Rect : TRect); procedure DeleteToolTip(TipWnd : hwnd; Control: TWinControl; ID : Cardinal); procedure UpdateToolTipText(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Text : String); procedure UpdateToolTipTextByCallBack(TipWnd : hwnd; Control: TWinControl; ID : Cardinal); procedure UpdateToolTipRect(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Rect : TRect); const TTS_NOANIMATE = $10; TTS_NOFADE = $20; TTM_SETTITLE = (WM_USER + 32); implementation procedure SetBalloonPosition(BWnd : hwnd; X,Y : integer); begin SendMessage(BWnd, TTM_TRACKPOSITION, 0, MAKELONG(x,y)); end; procedure SetBalloonTracking(BWnd : hwnd; Control: TWinControl; ID : Cardinal; Activate : boolean); var ti: TToolInfo; begin ti.cbSize := SizeOf(ti); ti.hwnd := Control.Handle; ti.uId := Id; if Activate then SendMessage(BWnd, TTM_TRACKACTIVATE , 1, Integer(@ti)) else SendMessage(BWnd, TTM_TRACKACTIVATE , 0, Integer(@ti)); end; function RegisterBallonWindow(Control : TWinControl) : hwnd; var hWnd, hWndB: THandle; begin hWnd := Control.Handle; hWndB := CreateWindowEx(WS_EX_TOPMOST,TOOLTIPS_CLASS, nil, WS_POPUP or TTS_BALLOON or TTS_NOPREFIX or TTS_ALWAYSTIP or TTS_NOFADE or TTS_NOANIMATE, 0, 0, 0, 0, hWnd, 0, HInstance, nil); if hWndB <> 0 then SetWindowPos(hWndB, HWND_TOPMOST, 0, 0, 0, 0,SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE); result := hWndB; end; procedure AddBalloonWindowCallBack(BWnd : hwnd; Control : TWinControl; ID : Cardinal; Icon : integer; Titel : String; Rect : TRect); var ti: TToolInfo; P : PChar; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.lpszText := PChar(Titel); ti.uId := Id; ti.rect := Rect; P := PChar(Titel); SendMessage(BWnd, TTM_ADDTOOL, 0, Integer(@ti)); SendMessagE(BWnd, TTM_SETTITLE, 1, Integer(P)); end; procedure SetTipTitel(TipWnd : hwnd; Icon : integer; Titel : String); var P : PChar; begin P := PChar(Titel); SendMessagE(TipWnd, TTM_SETTITLE, Icon, Integer(P)); end; function RegisterToolTip(Control: TWinControl) : hwnd; var hWnd, hWndTip: THandle; begin hWnd := Control.Handle; hWndTip := CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, nil, WS_POPUP or TTS_NOPREFIX or TTS_ALWAYSTIP or TTS_NOFADE or TTS_NOANIMATE, 0, 0, 0, 0, hWnd, 0, HInstance, nil); if hWndTip <> 0 then SetWindowPos(hWndTip, HWND_TOPMOST, 0, 0, 0, 0,SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE); result := hWndTip; end; procedure UpdateToolTipTextByCallback(TipWnd : hwnd; Control: TWinControl; ID : Cardinal); var ti: TToolInfoW; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.lpszText := LPSTR_TEXTCALLBACKW; ti.uId := ID; SendMessage(TipWnd, TTM_UPDATETIPTEXT, 0, Integer(@ti)); end; procedure UpdateToolTipText(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Text : String); var ti: TToolInfo; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.lpszText := PChar(Text); ti.uId := ID; SendMessage(TipWnd, TTM_UPDATETIPTEXT, 0, Integer(@ti)); end; procedure UpdateToolTipRect(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Rect : TRect); var ti: TToolInfo; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.Rect := Rect; ti.uId := ID; SendMessage(TipWnd, TTM_NEWTOOLRECT, 0, Integer(@ti)); end; procedure AddToolTipByCallBack(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Rect : TRect); var ti: TToolInfoW; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.lpszText := LPSTR_TEXTCALLBACKW; ti.uId := ID; ti.rect := Rect; SendMessage(TipWnd, TTM_ADDTOOL, 0, Integer(@ti)); end; procedure AddToolTip(TipWnd : hwnd; Control: TWinControl; ID : Cardinal; Rect : TRect; Text : String); var ti: TToolInfo; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.lpszText := PChar(Text); ti.uId := ID; ti.rect := Rect; SendMessage(TipWnd, TTM_ADDTOOL, 0, Integer(@ti)); end; procedure DeleteToolTip(TipWnd : hwnd; Control: TWinControl; ID : Cardinal); var ti: TToolInfo; begin ti.cbSize := SizeOf(ti); ti.uFlags := TTF_TRANSPARENT or TTF_SUBCLASS; ti.hwnd := Control.Handle; ti.uId := ID; SendMessage(TipWnd, TTM_DELTOOL, 0, Integer(@ti)); end; procedure EnableToolTip(TipWnd : hwnd); begin SendMessage(TipWnd, TTM_ACTIVATE, 1, 0); end; procedure DisableToolTip(TipWnd : hwnd); begin SendMessage(TipWnd, TTM_ACTIVATE, 0, 0); end; end.
unit RDORootServer; interface uses SyncObjs, RDOServer, RDOInterfaces; type {$M+} TRDORootServer = class public constructor Create(ConnectionsServer : IRDOConnectionsServer; MaxQueryThreads : integer; QueryCritSection : TCriticalSection; const RootName : string); destructor Destroy; override; private fConnectionsServer : IRDOConnectionsServer; fRDOServer : TRDOServer; private function GetId : integer; public property ConnectionsServer : IRDOConnectionsServer read fConnectionsServer; property RDOServer : TRDOServer read fRDOServer; published property Id : integer read GetId; end; {$M-} implementation // TRDORootServer constructor TRDORootServer.Create(ConnectionsServer : IRDOConnectionsServer; MaxQueryThreads : integer; QueryCritSection : TCriticalSection; const RootName : string); begin inherited Create; fConnectionsServer := ConnectionsServer; fRDOServer := TRDOServer.Create(fConnectionsServer as IRDOServerConnection, MaxQueryThreads, QueryCritSection); fRDOServer.RegisterObject(RootName, integer(self)); fConnectionsServer.StartListening end; destructor TRDORootServer.Destroy; begin fConnectionsServer.StopListening; fRDOServer.Free; inherited end; function TRDORootServer.GetId : integer; begin result := integer(self); end; end.
unit Control.FechamentoExpressas; interface uses FireDAC.Comp.Client, Common.ENum, Model.FechamentoExpressas, Control.Sistemas; type TFechamentoExpressasControl = class private FFechamento : TFechamentoExpressas; public constructor Create; destructor Destroy; override; function Gravar: Boolean; function Localizar(aParam: array of variant): TFDQuery; function GetId(): Integer; function SaveDB(memTable: TFDMemTable): Boolean; function FechamentoExiste(sUniqueKey: String): Boolean; property Expedicao: TFechamentoExpressas read FFechamento write FFechamento; end; implementation { TFechamentoExpressasControl } constructor TFechamentoExpressasControl.Create; begin FFechamento := TFechamentoExpressas.Create; end; destructor TFechamentoExpressasControl.Destroy; begin FFechamento.Free; inherited; end; function TFechamentoExpressasControl.FechamentoExiste(sUniqueKey: String): Boolean; begin Result := FFechamento.FechamentoExiste(sUniqueKey); end; function TFechamentoExpressasControl.GetId: Integer; begin Result := FFechamento.GetID; end; function TFechamentoExpressasControl.Gravar: Boolean; begin Result := FFechamento.Gravar; end; function TFechamentoExpressasControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FFechamento.Localizar(aParam); end; function TFechamentoExpressasControl.SaveDB(memTable: TFDMemTable): Boolean; begin Result := FFechamento.SaveDB(memTable); end; end.
unit mainform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, EditBtn, StdCtrls, process; type { TForm1 } TForm1 = class(TForm) buttonResolveSymbols: TButton; editGDBPath: TFileNameEdit; editProgramPath: TFileNameEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; memoStacktrace: TMemo; procedure buttonResolveSymbolsClick(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.buttonResolveSymbolsClick(Sender: TObject); var GDBProcess: TProcess; GDBOutput: TStringList; Str, StackStr, lCurAddress: string; lAddressPos: SizeInt; i: Integer; StrGdbOutput: String; begin GDBProcess := TProcess.Create(nil); GDBOutput := TStringList.Create; memoStacktrace.Lines.BeginUpdate; try for i := 0 to memoStacktrace.Lines.Count - 1 do begin // Obtain the stack address or skip this line StackStr := memoStacktrace.Lines.Strings[i]; lAddressPos := Pos('$', StackStr); if lAddressPos <= 0 then Continue; lCurAddress := Copy(StackStr, lAddressPos+1, 8); // Run GDB to get the symbol name Str := Format('%s --batch "--eval-command=info symbol 0x%s" %s', [editGDBPath.FileName, lCurAddress, editProgramPath.FileName]); GDBProcess.CommandLine := Str; GDBProcess.Options := GDBProcess.Options + [poWaitOnExit, poUsePipes, poStderrToOutPut]; GDBProcess.Execute; GDBOutput.LoadFromStream(GDBProcess.Output); if GDBOutput.Count >= 1 then StrGdbOutput := GDBOutput.Strings[0] else StrGdbOutput := ''; // Add the symbol name to the memo memoStacktrace.Lines.Strings[i] := Format('%s %s', [StackStr, StrGdbOutput]); end; finally GDBProcess.Free; GDBOutput.Free; memoStacktrace.Lines.EndUpdate; end; end; end.
// Defines several default settings // Original Author: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterDefaultSettings; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, GX_CodeFormatterTypes; function BorlandDefaults: TSettings; implementation function BorlandDefaults: TSettings; begin // Result.Wizard.CapFileName := ''; // Result.Wizard.ToolPosition := 0; // Result.Wizard.Shortcut.First := 0; // Result.Wizard.Shortcut.Second := #0; Result.AlignCommentPos := 40; Result.AlignComments := False; Result.AlignVar := False; Result.AlignVarPos := 20; Result.BlankProc := True; Result.BlankSubProc := False; Result.ChangeIndent := True; Result.CommentFunction := False; Result.CommentUnit := False; Result.FeedAfterSemiColon := True; Result.FeedAfterThen := True; Result.FeedAfterVar := True; Result.FeedBeforeEnd := True; Result.FeedEachUnit := False; Result.FeedElseIf := False; Result.FeedRoundBegin := NewLine; Result.FillNewWords := fmUnchanged; Result.indentBegin := False; Result.IndentCaseElse := False; Result.IndentComments := True; Result.IndentCompDirectives := False; Result.IndentTry := True; Result.IndentTryElse := False; Result.NoFeedBeforeThen := True; Result.NoIndentElseIf := False; Result.RemoveDoubleBlank := True; Result.ReservedCase := rfLowerCase; Result.ShortCut := 0; Result.SpaceColon := spAfter; Result.SpaceComma := spAfter; Result.SpaceEqualOper := spBoth; Result.SpaceLeftBr := spNone; Result.SpaceLeftHook := spNone; Result.SpaceOperators := spBoth; Result.SpacePerIndent := 2; Result.SpaceRightBr := spNone; Result.SpaceRightHook := spNone; Result.SpaceSemiColon := spAfter; Result.StandDirectivesCase := rfLowerCase; Result.UpperCompDirectives := True; Result.UpperNumbers := True; Result.WrapLines := True; Result.WrapPosition := 81; StrCopy(Result.EndCommentOut, '{*)}'); StrCopy(Result.StartCommentOut, '{(*}'); end; end.
unit SOList; interface uses FMX.Layouts, Data.DB, FMX.Forms, System.SysUtils, System.Classes, FMX.Types, FMX.Dialogs, FMX.Controls, System.Diagnostics, FMX.Ani, FMX.InertialMovement, System.Generics.Collections, System.UITypes, System.Types; type TSOList<L: TFmxObject; I: TFrame> = class(TComponent) private FObject: L; FAniCalculations: TAniCalculations; FList: TObjectList<I>; function getCount: Integer; Strict private constructor Create(AOwner: TComponent); public property Count: Integer read getCount; procedure Free; function Clear: TSOList<L,I>; function Items(Index: Cardinal): I; overload; function Items(AName: String): I; overload; function IndexOf(AName: String): Integer; procedure ShowItem(Item: I; ATime: Single=0.4; ADelay: Single=0); procedure ShowHiddenItems(ATime: Single=0.4; ADelay: Single=0); procedure HideItem(Item: I; ATime: Single=0.4); function Load(ASource: TDataset; OnProcess: TProc<TDataset, I> =nil; OnFinish: TProc<TDataset> =nil): TSOList<L,I>; function Add(Item: I; ATime: Single=0.4; ADelay: Single=0): TSOList<L,I>; function Delete(Index: Integer): TSOList<L,I>; function Remove(AName: String): TSOList<L,I>; function ChangeOrder(ASource, ADest: I): TSOList<L,I>; function BeginDragDrop: TSOList<L,I>; function EndDragDrop: TSOList<L,I>; procedure DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); procedure DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); class function New(AOwner: TComponent): TSOList<L,I>; end; implementation { TSOList<L, I> } function TSOList<L, I>.Add(Item: I; ATime, ADelay: Single): TSOList<L, I>; begin Result:= Self; Item.parent := FObject; Item.Position.Y := (Count+1)*(Item.Height+Item.Margins.Top+Item.Margins.Bottom); FList.Add(Item); ShowItem(Item, ATime, ADelay); end; function TSOList<L, I>.BeginDragDrop: TSOList<L,I>; var I: Integer; begin Result := Self; for I := 0 to Count-1 do begin FList[I].DragMode := TDragMode.dmAutomatic; FList[I].OnDragOver := DragOver; FList[I].OnDragDrop := DragDrop; end; end; function TSOList<L, I>.ChangeOrder(ASource, ADest: I): TSOList<L, I>; var IndexSource, IndexDest: Integer; Y: Single; begin IndexSource := FList.IndexOf(ASource); IndexDest := FList.IndexOf(ADest); Y := ASource.position.Y; TAnimator.AnimateFloat(ASource, 'Position.Y', ADest.Position.Y, 0.8, TAnimationType.Out, TInterpolationType.Quintic); TAnimator.AnimateFloat(ADest, 'Position.Y', Y, 0.8, TAnimationType.Out, TInterpolationType.Quintic); FList.OwnsObjects := False; FList[IndexSource]:=ADest; FList[IndexDest]:=ASource; end; function TSOList<L, I>.Clear: TSOList<L, I>; begin {$IFDEF ANDROID or IOS} for var I := Count-1 downto 0 do begin FList[I].DisposeOf; end; {$ENDIF} FList.OwnsObjects := True; FList.Clear; end; constructor TSOList<L,I>.Create(AOwner: TComponent); begin inherited Create(AOwner); FObject := L(AOwner); FList := TObjectList<I>.Create(False); FAniCalculations := TAniCalculations.Create(self); with FAniCalculations do begin Animation := True; BoundsAnimation := True; Averaging := True; AutoShowing := False; DecelerationRate := 1.5; Elasticity := 50; TouchTracking := [ttVertical]; end; if FObject is TCustomScrollBox then TCustomScrollBox(FObject).AniCalculations.Assign(FAniCalculations); end; function TSOList<L, I>.Delete(Index: Integer): TSOList<L, I>; begin Result := Self; if (Index < 0) or (Index >= Count) then raise Exception.Create('Index out of bounds.'); HideItem(FList[Index]); {$IFDEF ANDROID or IOS} FList[Index].DisposeOf; {$ENDIF} FList.OwnsObjects := True; FList.Delete(Index); end; procedure TSOList<L, I>.DragDrop(Sender: TObject; const Data: TDragObject; const Point: TPointF); var LSource, LDest: I; IndexSource, IndexDest: Integer; Y: Single; begin LSource := I(Data.Source); LDest := I(Sender); ChangeOrder(LSource, LDest); end; procedure TSOList<L, I>.DragOver(Sender: TObject; const Data: TDragObject; const Point: TPointF; var Operation: TDragOperation); begin if ((Sender is I) and (Data.Source is I)) then Operation := TDragOperation.Move else Operation := TDragOperation.None; end; function TSOList<L, I>.EndDragDrop: TSOList<L,I>; var I: Integer; begin Result := Self; for I := 0 to Count-1 do begin FList[I].DragMode := TDragMode.dmManual; end; end; procedure TSOList<L,I>.Free; begin if Assigned(FObject) then FObject := nil; if Assigned(FList) then FList.Free; inherited Free; end; function TSOList<L, I>.getCount: Integer; begin result := FList.Count; end; procedure TSOList<L, I>.HideItem(Item: I; ATime: Single); var Index, R: Integer; Y: Single; begin Index := FList.IndexOf(Item); FList.Items[Index].Tag := 0; TAnimator.AnimateFloat(Item, 'Opacity', 0.01, ATime, TAnimationType.Out, TInterpolationType.Linear); TAnimator.AnimateFloatWait(Item, 'Position.X', TLayout(FObject).Width+30, ATime, TAnimationType.In, TInterpolationType.Back); Y:=0; for R := 0 to Count-1 do begin if FList[R].Tag=1 then begin TAnimator.AnimateFloatDelay(FList[R], 'Position.Y', Y, 0.4, ATime*1.2); Y := Y+FList[R].Height+FList[R].Margins.Top+Item.Margins.Bottom; end; end; end; function TSOList<L, I>.IndexOf(AName: String): Integer; var I: Integer; begin Result := -1; for I := 0 to Count-1 do begin if UpperCase(FList[I].Name) = UpperCase(AName) then begin Result := I; break; end; end; end; function TSOList<L, I>.Items(AName: String): I; var Index: Integer; begin Result := nil; Index := IndexOf(AName); if Index >= 0 then Result := Items(Index); end; function TSOList<L, I>.Items(Index: Cardinal): I; begin if Index >= Count then raise Exception.Create(Format('(%s)[%s] Index out of bounds.', [ClassName, Name])); Result := FList[Index]; end; function TSOList<L,I>.Load(ASource: TDataset; OnProcess: TProc<TDataset, I> =nil; OnFinish: TProc<TDataset> =nil): TSOList<L,I>; begin result := self; TThread.CreateAnonymousThread( procedure var Lbm : TBookmark; Item: I; Counter: Integer; begin TThread.Synchronize(TThread.CurrentThread, procedure begin TControl(FObject).Visible := False; TControl(FObject).BeginUpdate; Lbm := ASource.Bookmark; Clear; ASource.First; end); Counter:=0; while not ASource.Eof do begin Item := I.Create(FObject); Item.parent := FObject; Item.name := format('fra%d',[Counter]); Item.Position.Y := Counter*(Item.Height+Item.Margins.Top+Item.Margins.Bottom); FList.Add(Item); TThread.Synchronize(TThread.CurrentThread, procedure begin if Assigned(OnProcess) then OnProcess(ASource, Item); ShowItem(Item, 0.5, 0.3+(Counter*0.1)); end); ASource.Next; Inc(Counter); end; TThread.Synchronize(TThread.CurrentThread, procedure begin ASource.Bookmark := Lbm; TControl(FObject).EndUpdate; TControl(FObject).Visible := True; ShowItem(Item, 0.5, 0.3+(Counter*0.2)); if Assigned(OnFinish) then OnFinish(ASource); end); end) .Start; end; class function TSOList<L,I>.New(AOwner: TComponent): TSOList<L,I>; begin result := Create(AOwner); result.Name := Format('SOList_%s', [AOwner.Name]); end; function TSOList<L, I>.Remove(AName: String): TSOList<L, I>; var Item: I; begin Result := Self; Item := Items(AName); if Item = nil then raise Exception.Create('Item not found.'); HideItem(Item); {$IFDEF ANDROID or IOS} Item.DisposeOf; {$ENDIF} FList.OwnsObjects := True; FList.Delete(indexOf(AName)); end; procedure TSOList<L, I>.ShowHiddenItems(ATime, ADelay: Single); var I, R: Integer; Y: Single; begin for I := Count-1 downto 0 do begin if FList[I].Tag = 0 then ShowItem(FList[I], ATime, ADelay); end; Y:=0; for R := 0 to Count-1 do begin if FList[R].Tag=1 then begin TAnimator.AnimateFloatDelay(FList[R], 'Position.Y', Y, 0.4, ATime*1.2); Y := Y+FList[R].Height+FList[R].Margins.Top+FList[R].Margins.Bottom; end; end; end; procedure TSOList<L, I>.ShowItem(Item: I; ATime: Single; ADelay: Single); var Index, R: Integer; Y, Y2, DelayInc, Bottom: Single; begin Index := FList.IndexOf(Item); DelayInc := 0.4; Item.Position.Y := Index*(FList[Index].Height+FList[Index].Margins.Top+FList[Index].Margins.Bottom); Item.Position.X := TLayout(FObject).Width+30; Item.Opacity := 0.01; Item.Tag := 1; TAnimator.AnimateFloatDelay(Item, 'Opacity', 1, ATime+0.1, ADelay+DelayInc, TAnimationType.Out, TInterpolationType.Linear); TAnimator.AnimateFloatDelay(Item, 'Position.X', 0, ATime, ADelay+DelayInc, TAnimationType.Out, TInterpolationType.Bounce); Y := 0; for R := 0 to Count-1 do begin if FList[R].Visible and (FList[R].Tag=1) then begin TAnimator.AnimateFloatDelay(FList[R], 'Position.Y', Y, 0.4, ADelay); Y := Y+(FList[R].Height+FList[R].Margins.Top+FList[R].Margins.Bottom); end; end; end; end.
unit UnitEditorNotifier; interface uses ToolsApi, DockForm, System.Classes; type TEditorNotifier = class(TNotifierObject, INTAEditServicesNotifier) public procedure DockFormRefresh(const EditWindow: INTAEditWindow; DockForm: TDockableForm); procedure DockFormUpdated(const EditWindow: INTAEditWindow; DockForm: TDockableForm); procedure DockFormVisibleChanged(const EditWindow: INTAEditWindow; DockForm: TDockableForm); procedure EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); procedure EditorViewModified(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); procedure WindowActivated(const EditWindow: INTAEditWindow); procedure WindowCommand(const EditWindow: INTAEditWindow; Command: Integer; Param: Integer; var Handled: Boolean); procedure WindowNotification(const EditWindow: INTAEditWindow; Operation: TOperation); procedure WindowShow(const EditWindow: INTAEditWindow; Show: Boolean; LoadedFromDesktop: Boolean); constructor Create; destructor Destroy; override; end; procedure Register; implementation uses Vcl.Forms, Vcl.Dialogs; var iEditoIndex: Integer; procedure Register; begin Application.Handle := Application.MainForm.Handle; if BorlandIDEServices <> Nil then begin iEditoIndex := (BorlandIDEServices as IOTAEditorServices) .AddNotifier(TEditorNotifier.Create); end; end; { TEditorNotifier } constructor TEditorNotifier.Create; begin end; destructor TEditorNotifier.Destroy; begin inherited; end; procedure TEditorNotifier.DockFormRefresh(const EditWindow: INTAEditWindow; DockForm: TDockableForm); begin ShowMessage('Disparou DockFormRefresh'); end; procedure TEditorNotifier.DockFormUpdated(const EditWindow: INTAEditWindow; DockForm: TDockableForm); begin ShowMessage('Disparou DockFormUpdated'); end; procedure TEditorNotifier.DockFormVisibleChanged(const EditWindow : INTAEditWindow; DockForm: TDockableForm); begin ShowMessage('Disparou DockFormVisibleChanged'); end; procedure TEditorNotifier.EditorViewActivated(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); begin ShowMessage('Disparou EditorViewActivated'); end; procedure TEditorNotifier.EditorViewModified(const EditWindow: INTAEditWindow; const EditView: IOTAEditView); begin ShowMessage('Disparou EditorViewModified'); end; procedure TEditorNotifier.WindowActivated(const EditWindow: INTAEditWindow); begin ShowMessage('Disparou WindowActivated'); end; procedure TEditorNotifier.WindowCommand(const EditWindow: INTAEditWindow; Command, Param: Integer; var Handled: Boolean); begin ShowMessage('Disparou WindowCommand'); end; procedure TEditorNotifier.WindowNotification(const EditWindow: INTAEditWindow; Operation: TOperation); begin ShowMessage('Disparou WindowNotification'); end; procedure TEditorNotifier.WindowShow(const EditWindow: INTAEditWindow; Show, LoadedFromDesktop: Boolean); begin ShowMessage('Disparou WindowNotification'); end; initialization finalization (BorlandIDEServices as IOTAEditorServices).RemoveNotifier(iEditoIndex); end.
unit Test.Automapper; interface uses DUnitX.TestFramework , AutoMapper.Mapper , Test.Models , Test.ModelsDTO ; type [TestFixture] TestTMapper = class strict private const CS_LAST_NAME = 'Иванов'; CS_FIRST_NAME = 'Сергей'; CS_MIDDLE_NAME = 'Николаеивч'; CS_AGE = 26; CS_STREET = 'Гагарина'; CS_NUM_HOUSE = 34; CS_FULL_NAME = CS_LAST_NAME+' '+CS_FIRST_NAME+' '+CS_MIDDLE_NAME+', возраст: 26'; CS_FULL_ADDRESS = 'ул. '+CS_STREET+' д. 34'; CS_OVERRIDE_FULL_NAME = 'Петрович Петр Игнатьевич'; СS_OVERRIDE_ADDRESS = 'ул. Некрасова'; CS_POST = 'Генеральный менеджер по клинигу'; CS_STATUS = 12; strict private FAddress : TAddress; FPerson : TPerson; procedure Configure; procedure ConfigureWithRecords; procedure ConfigureWithAutomap; private procedure CreateAddressDTO(var FAddressDTO: TAddressDTO); procedure CreatePersonDTO(FAddressDTO: TAddressDTO; var FPersonDTO: TPersonDTO); public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure TestConfigure; [Test] procedure TestMap_ObjectToObject; [Test] procedure TestMap_ObjectToRecord; [Test] procedure TestMap_RecordToObject; [Test] procedure TestMap_RecordToRecord; [Test] procedure TestMap_Automap; [Test] procedure TestMap_DefaultExpression; [Test] procedure TestMap_CustomExpression; [Test] procedure TestMap_WithConstructor; [Test] procedure TestMap_WithNestedObject; [Test] procedure TestMap_WithConstructorAndNestedObject; [Test] procedure TestMap_WithOverrideExpression; end; implementation uses System.SysUtils ; procedure TestTMapper.Configure; begin Mapper.Reset; Mapper.Configure(procedure (const cfg: TConfigurationProvider) begin cfg //Default expression .CreateMap<TPerson, TSimplePersonDTO>() //Custom Expression .CreateMap<TPerson, TUserDTO>(procedure (const FPerson: TPerson; out FUserDTO: TUserDTO) begin FUserDTO.FullName := FPerson.LastName +' '+ FPerson.FirstName +' '+ FPerson.MiddleName +', возраст: '+ FPerson.Age.ToString; FUserDTO.Address := 'ул. '+ FPerson.Address.Street +' д. '+ FPerson.Address.NumHouse.ToString; end ) //With constructor .CreateMap<TAddressDTO, TAddress>(procedure (const FAddressDTO: TAddressDTO; out FAddress: TAddress) begin FAddress := TAddress.Create(FAddressDTO.Street, FAddressDTO.NumHouse); end ) //With nested object .CreateMap<TPerson, TPersonDTO>(procedure (const s: TPerson; out d: TPersonDTO) begin d.LastName := s.LastName; d.FirstName := s.FirstName; d.MiddleName := s.MiddleName; d.Age := s.Age; d.Address := mapper.Map<TAddressDTO>(s.Address); d.Post := s.Post; end ) //With constructor and nested object .CreateMap<TPersonDTO, TPerson>(procedure (const FPersonDTO: TPersonDTO; out FPerson: TPerson) begin FPerson := TPerson.Create(FPersonDTO.LastName, FPersonDTO.FirstName, FPersonDTO.MiddleName, FPersonDTO.Age, mapper.Map<TAddress>(FPersonDTO.Address), FPersonDTO.Post); end ) .CreateMap<TAddress, TAddressDTO> end); end; procedure TestTMapper.ConfigureWithAutomap; begin Mapper.Reset; Mapper.Configure(procedure (const cfg: TConfigurationProvider) begin cfg .Settings([TMapperSetting.Automap]) end); end; procedure TestTMapper.ConfigureWithRecords; begin Mapper.Reset; Mapper.Configure(procedure (const cfg: TConfigurationProvider) begin cfg .CreateMap<TAddress, TAddressRecord>() .CreateMap<TAddressRecord, TAddressWriteble>() .CreateMap<TAddressRecord, TNewAddressRecord>() .CreateMap<TAddress, TAddressDTO>() end); end; procedure TestTMapper.CreateAddressDTO(var FAddressDTO: TAddressDTO); begin FAddressDTO := TAddressDTO.Create; FAddressDTO.Street := CS_STREET; FAddressDTO.NumHouse := CS_NUM_HOUSE; end; procedure TestTMapper.CreatePersonDTO(FAddressDTO: TAddressDTO; var FPersonDTO: TPersonDTO); begin FPersonDTO := TPersonDTO.Create; FPersonDTO.LastName := CS_LAST_NAME; FPersonDTO.FirstName := CS_FIRST_NAME; FPersonDTO.MiddleName := CS_MIDDLE_NAME; FPersonDTO.Age := CS_AGE; FPersonDTO.Address := FAddressDTO; end; procedure TestTMapper.Setup; begin FAddress := TAddress.Create(CS_STREET, CS_NUM_HOUSE); FPerson := TPerson.Create(CS_LAST_NAME, CS_FIRST_NAME, CS_MIDDLE_NAME, CS_AGE, FAddress, CS_POST); FPerson.Status := CS_STATUS; end; procedure TestTMapper.TearDown; begin FPerson.Free; FAddress.Free; end; procedure TestTMapper.TestConfigure; begin Configure; Assert.AreEqual(6, Mapper.CountMapPair); end; procedure TestTMapper.TestMap_Automap; var FAddress: TAddress; FAddressRecord: TAddressRecord; begin ConfigureWithAutomap; FAddress := TAddress.Create(CS_STREET, CS_NUM_HOUSE); FAddressRecord := mapper.Map<TAddress, TAddressRecord>(FAddress); Assert.AreEqual(CS_STREET, FAddressRecord.Street); Assert.AreEqual(CS_NUM_HOUSE, FAddressRecord.NumHouse); end; procedure TestTMapper.TestMap_CustomExpression; var FUserDTO: TUserDTO; begin Configure; FUserDTO := mapper.Map<TUserDTO>(FPerson); Assert.AreEqual(CS_FULL_NAME, FUserDTO.FullName); Assert.AreEqual(CS_FULL_ADDRESS, FUserDTO.Address); end; procedure TestTMapper.TestMap_DefaultExpression; var FSimplePersonDTO: TSimplePersonDTO; begin Configure; FSimplePersonDTO := mapper.Map<TSimplePersonDTO>(FPerson); Assert.AreEqual(CS_LAST_NAME, FSimplePersonDTO.Last_Name); Assert.AreEqual(CS_LAST_NAME, FSimplePersonDTO.Last_Name); Assert.AreEqual(CS_FIRST_NAME, FSimplePersonDTO.First_Name); Assert.AreEqual(CS_POST, FSimplePersonDTO.Post); Assert.AreEqual(CS_STATUS, FSimplePersonDTO.Status.Value); { TODO : Добавить возможность устанавливать кастомное приведение типов. } // CheckEquals(CS_MIDDLE_NAME, FSimplePersonDTO.Middle_Name, 'Так как в объекте ресурса MiddleName: Nullable<string>, а в объекте назначения Middle_Mame: string - автоматическое приведение типов стандртными средствами не возможно.'); end; procedure TestTMapper.TestMap_ObjectToObject; var FAddress: TAddress; FAddressDTO: TAddressDTO; begin ConfigureWithRecords; FAddress := TAddress.Create(CS_STREET, CS_NUM_HOUSE); FAddressDTO := mapper.Map<TAddress, TAddressDTO>(FAddress); Assert.AreEqual(CS_STREET, FAddressDTO.Street); Assert.AreEqual(CS_NUM_HOUSE, FAddressDTO.NumHouse); end; procedure TestTMapper.TestMap_ObjectToRecord; var FAddress: TAddress; FAddressRecord: TAddressRecord; begin ConfigureWithRecords; FAddress := TAddress.Create(CS_STREET, CS_NUM_HOUSE); FAddressRecord := mapper.Map<TAddress, TAddressRecord>(FAddress); Assert.AreEqual(CS_STREET, FAddressRecord.Street); Assert.AreEqual(CS_NUM_HOUSE, FAddressRecord.NumHouse); end; procedure TestTMapper.TestMap_RecordToObject; var FAddress: TAddressWriteble; FAddressRecord: TAddressRecord; begin ConfigureWithRecords; FAddressRecord.Street := CS_STREET; FAddressRecord.NumHouse := CS_NUM_HOUSE; FAddress := mapper.Map<TAddressRecord, TAddressWriteble>(FAddressRecord); Assert.AreEqual(CS_STREET, FAddress.Street); Assert.AreEqual(CS_NUM_HOUSE, FAddress.NumHouse); end; procedure TestTMapper.TestMap_RecordToRecord; var FNewAddressRecord: TNewAddressRecord; FAddressRecord: TAddressRecord; begin ConfigureWithRecords; FAddressRecord.Street := CS_STREET; FAddressRecord.NumHouse := CS_NUM_HOUSE; FNewAddressRecord := mapper.Map<TAddressRecord, TNewAddressRecord>(FAddressRecord); Assert.AreEqual(CS_STREET, FNewAddressRecord.Street); Assert.AreEqual(CS_NUM_HOUSE, FNewAddressRecord.Num_House); end; procedure TestTMapper.TestMap_WithConstructor; var FAddress: TAddress; FAddressDTO: TAddressDTO; begin Configure; CreateAddressDTO(FAddressDTO); FAddress := mapper.Map<TAddress>(FAddressDTO); Assert.AreEqual(CS_STREET, FAddress.Street); Assert.AreEqual(CS_NUM_HOUSE, FAddress.NumHouse); end; procedure TestTMapper.TestMap_WithConstructorAndNestedObject; var FPerson: TPerson; FPersonDTO: TPersonDTO; FAddressDTO: TAddressDTO; begin Configure; CreateAddressDTO(FAddressDTO); CreatePersonDTO(FAddressDTO, FPersonDTO); FPerson := mapper.Map<TPerson>(FPersonDTO); Assert.AreEqual(CS_LAST_NAME, FPerson.LastName); Assert.AreEqual(CS_FIRST_NAME, FPerson.FirstName); Assert.AreEqual(CS_MIDDLE_NAME, FPerson.MiddleName.Value); Assert.AreEqual(CS_AGE, FPerson.Age.Value); Assert.AreEqual(CS_STREET, FPerson.Address.Street); Assert.AreEqual(CS_NUM_HOUSE, FPerson.Address.NumHouse); end; procedure TestTMapper.TestMap_WithNestedObject; var FPersonDTO: TPersonDTO; begin Configure; FPersonDTO := mapper.Map<TPersonDTO>(FPerson); Assert.AreEqual(CS_LAST_NAME, FPersonDTO.LastName); Assert.AreEqual(CS_FIRST_NAME, FPersonDTO.FirstName); Assert.AreEqual(CS_MIDDLE_NAME, FPersonDTO.MiddleName.Value); Assert.AreEqual(CS_AGE, FPersonDTO.Age.Value); Assert.AreEqual(CS_STREET, FPersonDTO.Address.Street); Assert.AreEqual(CS_NUM_HOUSE, FPersonDTO.Address.NumHouse); end; procedure TestTMapper.TestMap_WithOverrideExpression; var FUserDTO: TUserDTO; begin Configure; FUserDTO := mapper.Map<TPerson, TUserDTO>(FPerson, procedure (const s: TPerson; out d: TUserDTO) begin d.FullName := CS_OVERRIDE_FULL_NAME; d.Address := СS_OVERRIDE_ADDRESS; end ); Assert.AreEqual(CS_OVERRIDE_FULL_NAME, FUserDTO.FullName); Assert.AreEqual(СS_OVERRIDE_ADDRESS, FUserDTO.Address); end; initialization TDUnitX.RegisterTestFixture(TestTMapper); end.
Program Example13; uses Crt; { Program to demonstrate the TextBackground function. } begin TextColor(White); WriteLn('This is written in with the default background color'); TextBackground(Green); WriteLn('This is written in with a Green background'); TextBackground(Brown); WriteLn('This is written in with a Brown background'); TextBackground(Black); WriteLn('Back with a black background'); readln; end.
unit MdiChilds.SetPriceBase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.StdCtrls, Vcl.CheckLst, Vcl.ExtCtrls, MdiChilds.ProgressForm, GsDocument, MdiChilds.Reg; type TFmSetPricesBase = class(TFmProcess) edtMaterial: TLabeledEdit; btnOpenMaterial: TButton; edtMachines: TLabeledEdit; btnOpenMachine: TButton; clbFiles: TCheckListBox; lblXML: TLabel; JvDragDrop: TJvDragDrop; OpenDialog: TOpenDialog; procedure JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure btnOpenMaterialClick(Sender: TObject); procedure btnOpenMachineClick(Sender: TObject); private procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; public procedure ExecuteBase(Material, Machine: TGsDocument); end; var FmSetPricesBase: TFmSetPricesBase; implementation uses StrUtils; {$R *.dfm} procedure TFmSetPricesBase.btnOpenMachineClick(Sender: TObject); begin if OpenDialog.Execute then edtMachines.Text := OpenDialog.FileName; end; procedure TFmSetPricesBase.btnOpenMaterialClick(Sender: TObject); begin if OpenDialog.Execute then edtMaterial.Text := OpenDialog.FileName; end; procedure TFmSetPricesBase.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var Material, Machine: TGsDocument; begin Assert(edtMaterial.Text <> '', 'Материалы не обнаружены'); Assert(edtMachines.Text <> '', 'Машины не обнаружены'); Material := TGsDocument.Create; Machine := TGsDocument.Create; try try Material.LoadFromFile(edtMaterial.Text); Machine.LoadFromFile(edtMachines.Text); ExecuteBase(Material, Machine); finally Machine.Free; end; finally Material.Free; end; end; procedure TFmSetPricesBase.ExecuteBase(Material, Machine: TGsDocument); var I: Integer; Document: TGsDocument; L: TList; Resource: TGsResource; J: Integer; Element: TGsRow; Code: string; begin L := TList.Create; try Material.Chapters.EnumItems(L, TGsRow, True); Machine.Chapters.EnumItems(L, TGsRow, True); for I := 0 to Self.clbFiles.Count - 1 do begin Document := TGsDocument.Create; try Document.LoadFromFile(clbFiles.Items[I]); for Resource in Document.GetAll<TGsResource> do begin for J := 0 to L.Count - 1 do begin Element := TGsRow(L[J]); Code := StringReplace(Element.Number(True),'21-','',[]); if Code = Resource.Code then begin Resource.SetCostValue(cstPrice, Element.GetCostValue(cstPrice)); if Resource.Kind = rkMashine then Resource.SetCostValue(cstZM, Element.GetCostValue(cstZM)); Break; end; end; end; Document.Save; finally Document.Free; end; end; finally L.Free; end; end; procedure TFmSetPricesBase.JvDragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin Self.clbFiles.Items.Assign(Value); clbFiles.CheckAll(TCheckBoxState.cbChecked); end; begin FormsRegistrator.RegisterForm(TFmSetPricesBase, 'Усрановка цен на ресурсы в сборники', 'Утилиты', False, dpkCustom, '/SETPRICEBASE'); end.
unit uFlashRect; interface type TFlashRect = record private FFlashTop: Integer; FFlashHeigth: Integer; FFlashLeft: Integer; FFlashWidth: Integer; FFlashFontSize: Integer; procedure SetFlashHeigth(const Value: Integer); procedure SetFlashLeft(const Value: Integer); procedure SetFlashTop(const Value: Integer); procedure SetFlashWidth(const Value: Integer); procedure SetFlashFontSize(const Value: Integer); private FScreenTop: Integer; FScreenHeigth: Integer; FScreenLeft: Integer; FScreenWidth: Integer; FScreenFontSize: Integer; procedure SetScreenHeigth(const Value: Integer); procedure SetScreenLeft(const Value: Integer); procedure SetScreenTop(const Value: Integer); procedure SetScreenWidth(const Value: Integer); procedure SetScreenFontSize(const Value: Integer); function GetFlash2ScreenRatio: Double; public property ScreenTop : Integer read FScreenTop write SetScreenTop; property ScreenLeft : Integer read FScreenLeft write SetScreenLeft; property ScreenWidth : Integer read FScreenWidth write SetScreenWidth; property ScreenHeigth: Integer read FScreenHeigth write SetScreenHeigth; property ScreenFontSize: Integer read FScreenFontSize write SetScreenFontSize; procedure RecalcScreenPositions; property Flash2ScreenRatio: Double read GetFlash2ScreenRatio; property FlashTop : Integer read FFlashTop write SetFlashTop; property FlashLeft : Integer read FFlashLeft write SetFlashLeft; property FlashWidth : Integer read FFlashWidth write SetFlashWidth; property FlashHeigth: Integer read FFlashHeigth write SetFlashHeigth; property FlashFontSize: Integer read FFlashFontSize write SetFlashFontSize; end; implementation uses fFlashOffscreen, Math; { TFlashRect } function TFlashRect.GetFlash2ScreenRatio: Double; var fFlashWidth2PanelRatio, fFlashHeight2PanelRatio: Double; begin with frmFlashOffscreen do begin fFlashWidth2PanelRatio := ShockwaveFlash1.Width / Max(frmFlashOffscreen.FlashWidth, 1); fFlashHeight2PanelRatio := ShockwaveFlash1.Height / Max(frmFlashOffscreen.FlashHeight, 1); end; //proportional fix Result := Min(fFlashWidth2PanelRatio, fFlashHeight2PanelRatio); end; procedure TFlashRect.RecalcScreenPositions; begin FScreenHeigth := Round(FFlashHeigth * GetFlash2ScreenRatio); FScreenLeft := Round(FFlashLeft * GetFlash2ScreenRatio); FScreenTop := Round(FFlashTop * GetFlash2ScreenRatio); FScreenWidth := Round(FFlashWidth * GetFlash2ScreenRatio); FScreenFontSize := Round(FFlashFontSize * GetFlash2ScreenRatio); end; procedure TFlashRect.SetFlashFontSize(const Value: Integer); begin if FFlashFontSize = Value then Exit; FFlashFontSize := Value; FScreenFontSize := Round(FFlashFontSize * GetFlash2ScreenRatio); end; procedure TFlashRect.SetFlashHeigth(const Value: Integer); begin if FFlashHeigth = Value then Exit; FFlashHeigth := Value; FScreenHeigth := Round(FFlashHeigth * GetFlash2ScreenRatio); end; procedure TFlashRect.SetFlashLeft(const Value: Integer); begin if FFlashLeft = Value then Exit; FFlashLeft := Value; FScreenLeft := Round(FFlashLeft * GetFlash2ScreenRatio); end; procedure TFlashRect.SetFlashTop(const Value: Integer); begin if FFlashTop = Value then Exit; FFlashTop := Value; FScreenTop := Round(FFlashTop * GetFlash2ScreenRatio); end; procedure TFlashRect.SetFlashWidth(const Value: Integer); begin if FFlashWidth = Value then Exit; FFlashWidth := Value; FScreenWidth := Round(FFlashWidth * GetFlash2ScreenRatio); end; procedure TFlashRect.SetScreenFontSize(const Value: Integer); begin if FScreenFontSize = Value then Exit; FScreenFontSize := Value; FFlashFontSize := Round(FScreenFontSize / GetFlash2ScreenRatio); end; procedure TFlashRect.SetScreenHeigth(const Value: Integer); begin if FScreenHeigth = Value then Exit; FScreenHeigth := Value; FFlashHeigth := Round(FScreenHeigth / GetFlash2ScreenRatio); end; procedure TFlashRect.SetScreenLeft(const Value: Integer); begin if FScreenLeft = Value then Exit; FScreenLeft := Value; FFlashLeft := Round(FScreenLeft / GetFlash2ScreenRatio); end; procedure TFlashRect.SetScreenTop(const Value: Integer); begin if FScreenTop = Value then Exit; FScreenTop := Value; FFlashTop := Round(FScreenTop / GetFlash2ScreenRatio); end; procedure TFlashRect.SetScreenWidth(const Value: Integer); begin if FScreenWidth = Value then Exit; FScreenWidth := Value; FFlashWidth := Round(FScreenWidth / GetFlash2ScreenRatio); end; end.
unit EasyUpdateForm; interface uses Windows , Buttons , Classes , Controls , ExtCtrls , Forms , StdCtrls , SysUtils // , EasyUpdateParamsForm , EasyUpdateSupport // , LocaleMessages ; type TEasyUpdateForm = class(TForm) f_MainPanel: TPanel; f_StatusGroupBox: TGroupBox; f_AutomaticUpdateLabel: TLabel; f_AutomaticUpdateStatusLabel: TLabel; f_NextTimeRunLabel: TLabel; f_NextTimeRunStatusLabel: TLabel; f_LastTimeRunLabel: TLabel; f_LastTimeRunStatusLabel: TLabel; f_LastRunLabel: TLabel; f_LastRunStatusLabel: TLabel; f_SetupParamsLabel: TLabel; f_HelpBitBtn: TBitBtn; f_OnBitBtn: TBitBtn; f_OffBitBtn: TBitBtn; f_RunBitBtn: TBitBtn; f_TaskName: TLabel; f_InvalidateStatusTimer: TTimer; // procedure FormCreate(a_Sender: TObject); // procedure SetupParamsLabelClick(a_Sender: TObject); procedure HelpBitBtnClick(a_Sender: TObject); procedure OnBitBtnClick(a_Sender: TObject); procedure OffBitBtnClick(a_Sender: TObject); procedure RunBitBtnClick(a_Sender: TObject); // procedure InvalidateStatusTimer(a_Sender: TObject); private function AutomaticUpdateStatusToString(const a_Value: Boolean): string; // function NextTimeToString(const a_Value: TDateTime): string; function LastTimeToString(const a_Value: TDateTime): string; // function LastRunStatusToString(const a_Value: Integer): string; private procedure InvalidateStatus; end; var g_EasyUpdateForm: TEasyUpdateForm; implementation {$R *.dfm} var g_LocalFormatSettings: TFormatSettings; procedure TEasyUpdateForm.FormCreate(a_Sender: TObject); begin Caption := GetCurrentLocaleMessage(c_EasyUpdateFormCaption); // f_StatusGroupBox.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormStatusGroupBoxCaption); // f_AutomaticUpdateLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormAutomaticUpdateLabelCaption); f_NextTimeRunLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormNextTimeRunLabelCaption); f_LastTimeRunLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormLastTimeRunLabelCaption); f_LastRunLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormLastRunLabel); // f_HelpBitBtn.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormHelpBitBtnCaption); // f_OnBitBtn.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormOnBitBtnCaption); f_OffBitBtn.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormOffBitBtnCaption); // f_RunBitBtn.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormRunBitBtnCaption); // f_SetupParamsLabel.Caption := GetCurrentLocaleMessage(c_EasyUpdateFormSetupParamsLabelCaption); // f_TaskName.Hint := GetCurrentLocaleMessage(c_EasyUpdateFormTaskNameLabelHintToString); // InvalidateStatus; // f_InvalidateStatusTimer.Enabled := True; end; procedure TEasyUpdateForm.SetupParamsLabelClick(a_Sender: TObject); begin f_InvalidateStatusTimer.Enabled := False; try Hide; try with g_EasyUpdateParamsForm do begin StoreState; // if (ShowModal = mrCancel) then RestoreState; end; finally Show; end; finally f_InvalidateStatusTimer.Enabled := True; end; end; procedure TEasyUpdateForm.HelpBitBtnClick(a_Sender: TObject); begin Application.HelpSystem.ShowTopicHelp('page-setting.htm', ''); end; procedure TEasyUpdateForm.OnBitBtnClick(a_Sender: TObject); begin f_InvalidateStatusTimer.Enabled := False; try TEasyUpdateSupport.Instance.IsAutomaticUpdateEnabled := True; // InvalidateStatus; finally f_InvalidateStatusTimer.Enabled := True; end; end; procedure TEasyUpdateForm.OffBitBtnClick(a_Sender: TObject); begin f_InvalidateStatusTimer.Enabled := False; try TEasyUpdateSupport.Instance.IsAutomaticUpdateEnabled := False; // InvalidateStatus; finally f_InvalidateStatusTimer.Enabled := True; end; end; procedure TEasyUpdateForm.RunBitBtnClick(a_Sender: TObject); begin f_InvalidateStatusTimer.Enabled := False; try f_RunBitBtn.Enabled := False; // with TEasyUpdateSupport.Instance do begin FlushJobSettings; Run; end; finally f_InvalidateStatusTimer.Enabled := True; end; end; procedure TEasyUpdateForm.InvalidateStatusTimer(a_Sender: TObject); begin InvalidateStatus; end; function TEasyUpdateForm.AutomaticUpdateStatusToString(const a_Value: Boolean): string; begin if (a_Value) then Result := GetCurrentLocaleMessage(c_EasyUpdateFormAutomaticUpdateStatusToStringTrue) else Result := GetCurrentLocaleMessage(c_EasyUpdateFormAutomaticUpdateStatusToStringFalse); end; function TEasyUpdateForm.NextTimeToString(const a_Value: TDateTime): string; begin if (a_Value = 0) then Result := GetCurrentLocaleMessage(c_EasyUpdateFormNextTimeToString) else Result := DateTimeToStr(a_Value, g_LocalFormatSettings); end; function TEasyUpdateForm.LastTimeToString(const a_Value: TDateTime): string; begin if (a_Value = 0) then Result := GetCurrentLocaleMessage(c_EasyUpdateFormLastTimeToString) else Result := DateTimeToStr(a_Value, g_LocalFormatSettings); end; function TEasyUpdateForm.LastRunStatusToString(const a_Value: Integer): string; begin if (a_Value = -1) then Result := GetCurrentLocaleMessage(c_EasyUpdateFormLastRunStatusToString) else if (a_Value = -2) then Result := GetCurrentLocaleMessage(c_EasyUpdateFormLastRunStatusIsStillActiveToString) else Result := Format('0x%0.8x', [a_Value]); end; procedure TEasyUpdateForm.InvalidateStatus; var l_IsAutomaticUpdateEnabled: Boolean; begin with TEasyUpdateSupport.Instance do begin l_IsAutomaticUpdateEnabled := IsAutomaticUpdateEnabled; // f_NextTimeRunLabel.Enabled := l_IsAutomaticUpdateEnabled; // with f_NextTimeRunStatusLabel do begin Enabled := l_IsAutomaticUpdateEnabled; Caption := NextTimeToString(NextTimeToRun); end; // f_LastTimeRunLabel.Enabled := l_IsAutomaticUpdateEnabled; // with f_LastTimeRunStatusLabel do begin Enabled := l_IsAutomaticUpdateEnabled; Caption := LastTimeToString(LastTimeToRun); end; // f_LastRunLabel.Enabled := l_IsAutomaticUpdateEnabled; // with f_LastRunStatusLabel do begin Enabled := l_IsAutomaticUpdateEnabled; Caption := LastRunStatusToString(LastRunStatus); end; // f_AutomaticUpdateStatusLabel.Caption := AutomaticUpdateStatusToString(l_IsAutomaticUpdateEnabled); // f_OnBitBtn.Enabled := ((not l_IsAutomaticUpdateEnabled) and (LastRunStatus <> -2)); // f_OffBitBtn.Enabled := (l_IsAutomaticUpdateEnabled and (LastRunStatus <> -2)); f_RunBitBtn.Enabled := (l_IsAutomaticUpdateEnabled and (LastRunStatus <> -2)); // f_TaskName.Caption := TaskName; end; end; initialization GetLocaleFormatSettings(GetThreadLocale, g_LocalFormatSettings); // with g_LocalFormatSettings do begin TimeSeparator := ':'; TimeAMString := ''; TimePMString := ''; ShortTimeFormat := 'hh:mm'; LongTimeFormat := 'hh:mm'; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Angus Robertson, Magenta Systems Ltd Description: Client Cookie Handling, see RFC2109/RFC6265 (RFC2965 is obsolete) Creation: 19 March 2012 Updated: 19 March 2012 Version: 1.02 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1997-2011 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> 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. Overview -------- Provides a memory store for persistent and non-persisent cookies captured from the HTTP SetCookie header, and builds a Cookie header for any stored cookies for a URL. Persistent cookies are saved and re-read from a simple CSV file. OverbyteIcsHttpTst1.pas shows how to handle cookies, very few new lines Updates: 19 Mar 2012 - 1.00 baseline Angus 28 Mar 2012 - 1.01 Arno: StrictDelimiter doesn't exist in Delphi 7 Dec 15, 2012 V1.02 Arno fixed a small bug in GetCookies() when path was empty. Note - needs more testing for domain and path matching Pending - not yet thread safe } unit OverbyteIcsCookies; {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} interface uses Windows, SysUtils, Classes, IniFiles, OverbyteIcsUrl, OverbyteIcsUtils; type TCookie = record // RFC6265 says save this lot (except URL) CName: string; CValue: string; CExpireDT: TDateTime; CDomain: string; CPath: string; CCreateDT: TDateTime; CAccessDT: TDateTime; CHostOnly: boolean; CSecureOnly: boolean; CHttpOnly: boolean; CUrl: string; CPersist: boolean; // don't save following fields CDelete: boolean; CRawCookie: string; // temp for debugging end; TNewCookieEvent = procedure(Sender: TObject; ACookie: TCookie; var Save: Boolean) of object; const ISODateTimeMask = 'yyyy-mm-dd"T"hh:nn:ss' ; PerCookDomain = 0; PerCookPath = 1; PerCookName = 2; PerCookValue = 3; PerCookExpireDT = 4; PerCookCreateDT = 5; PerCookAccessDT = 6; PerCookHostOnly = 7; PerCookSecureOnly = 8; PerCookHttpOnly = 9; PerCookUrl = 10; PerCookTotal = 11; PerCookTitles: array [0..PerCookTotal-1] of string = ( 'Domain','Path','Name','Value','ExpireDT','CreateDT', 'AccessDT','HostOnly','SecureOnly','HttpOnly','URL'); type TIcsCookies = class(TComponent) private { Private declarations } FCookieIdx: THashedStringList; FCookies: array of TCookie; FTotCookies: integer; FNewCookieEvent: TNewCookieEvent; FLoadFileName: string; FAutoSave: boolean; // FLockList: TRTLCriticalSection; protected { Protected declarations } function GetCount: integer; public { Public declarations } constructor Create(Aowner:TComponent); override; destructor Destroy; override; { clear all cookies } procedure ClearAllCookies; { Get a single cookie by sorted index } function Get1Cookie (Idx: integer): TCookie; { rebuild cookie index without expired cookies } procedure RebuildIndex; { add a single cookie, may replace or delete } procedure AddCookie (ACookie: TCookie); { parse a cookie from SetCookie HTTP header } function ParseCookie (const ACookieHdr, AURL: string): TCookie; { add a cookie from SetCookie HTTP header } procedure SetCookie (const ACookieHdr, AURL: string); { find cookies for a domain and path } function GetCookies (const AURL: string): string; { load persistent cookies from string list as CSV } procedure LoadFromList (AList: TStrings); { load persistent cookies from a file as CSV } function LoadFromFile (const AFileName: string): boolean; { save persistent cookies to string list as CSV } procedure SaveToList (AList: TStrings); { save persistent cookies to a file as CSV } function SaveToFile (const AFileName: string; Repl: boolean = true): boolean; published { Published declarations } property Count: integer read GetCount; property AutoSave: boolean read FAutoSave write FAutoSave; property OnNewCookie: TNewCookieEvent read FNewCookieEvent write FNewCookieEvent; end; { get time bias in positive or negative hours to adjust UTC/GMT to local time } function GetLocalBiasUTC: Integer; { convert local date/time to UTC/GMT } function DateTimeToUTC (dtDT: TDateTime): TDateTime; { convert UTC/GMT to local date/time } function UTCToDateTime (dtDT: TDateTime): TDateTime; { convert ASCII ISO time string to Date/Time - no quotes } { yyyy-mm-ddThh:nn:ss (ISODateTimeMask) (time may be missing) } function PackedISOToDT (const ISO: string): TDateTime ; { convert Date/Time to ASCII ISO time string - no quotes } { yyyy-mm-ddThh:nn:ss (ISODateTimeMask) } function DTToPackedISO (D: TDateTime): string ; { convert ASCII cookies date and time to Date/Time - similar to RFC1123 but may have two digit year } { note this function does not currently process the date exactly according to RFC6265 } { Sun, 16-Mar-2014 12:31:40 GMT or Mon, 18-Mar-13 18:53:09 GMT } function Cookie_StrToDate (aDate: String): TDateTime; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { get time bias in positive or negative hours to adjust UTC/GMT to local time } function GetLocalBiasUTC: Integer; var tzInfo : TTimeZoneInformation; begin case GetTimeZoneInformation(tzInfo) of TIME_ZONE_ID_STANDARD: Result := tzInfo.Bias + tzInfo.StandardBias; TIME_ZONE_ID_DAYLIGHT: Result := tzInfo.Bias + tzInfo.DaylightBias; else Result := tzInfo.Bias; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { convert local date/time to UTC/GMT } function DateTimeToUTC (dtDT: TDateTime): TDateTime; begin Result := dtDT + GetLocalBiasUTC / (60.0 * 24.0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { convert UTC/GMT to local date/time } function UTCToDateTime (dtDT: TDateTime): TDateTime; begin Result := dtDT - GetLocalBiasUTC / (60.0 * 24.0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { convert ASCII ISO time string to Date/Time - no quotes } { yyyy-mm-ddThh:nn:ss (ISODateTimeMask) (time may be missing) } function PackedISOToDT (const ISO: string): TDateTime ; var yy, mm, dd: word ; hh, nn, ss: word ; timeDT: TDateTime ; info: string; begin result := 0 ; info := trim (ISO) ; if length (info) < 10 then exit ; if info [5] <> '-' then exit ; yy := atoi (copy (info, 1, 4)) ; mm := atoi (copy (info, 6, 2)) ; dd := atoi (copy (info, 9, 2)) ; if NOT TryEncodeDate (yy, mm, dd, result) then // D6 only begin result := -1 ; exit ; end ; if length (info) <> 19 then exit ; if info [14] <> ':' then exit ; hh := atoi (copy (info, 12, 2)) ; nn := atoi (copy (info, 15, 2)) ; ss := atoi (copy (info, 18, 2)) ; if NOT TryEncodeTime (hh, nn, ss, 0, timeDT) then exit ; // D6 only result := result + timeDT ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { convert Date/Time to ASCII ISO time string - no quotes } { yyyy-mm-ddThh:nn:ss (ISODateTimeMask) } function DTToPackedISO (D: TDateTime): string ; begin result := FormatDateTime (ISODateTimeMask, D) ; end ; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { convert ASCII cookies date and time to Date/Time - similar to RFC1123 but may have two digit year } { note this function does not currently process the date exactly according to RFC6265 } { Sun, 16-Mar-2014 12:31:40 GMT or Mon, 18-Mar-13 18:53:09 GMT } function Cookie_StrToDate (aDate: String): TDateTime; const RFC1123_StrMonth : String = 'JanFebMarAprMayJunJulAugSepOctNovDec'; var Year, Month, Day: Word; Hour, Min, Sec: Word; offset: integer; newDT: TDateTime; begin result := 0; if Length (aDate) < 25 then exit; offset := 6; Day := StrToIntDef(Copy(aDate, offset, 2), 0); offset := offset + 3; Month := (Pos(Copy(aDate, offset, 3), RFC1123_StrMonth) + 2) div 3; offset := offset + 4; if aDate [offset + 2] <> ' ' then begin Year := StrToIntDef(Copy(aDate, offset, 4), 0); offset := offset + 5; end else begin Year := StrToIntDef(Copy(aDate, offset, 2), 0); if Year >= 70 then Year := Year + 1900 else Year := Year + 2000; offset := offset + 3; end; Hour := StrToIntDef(Copy(aDate, offset, 2), 0); offset := offset + 3; Min := StrToIntDef(Copy(aDate, offset, 2), 0); offset := offset + 3; Sec := StrToIntDef(Copy(aDate, offset, 2), 0); TryEncodeDate(Year, Month, Day, Result); TryEncodeTime(Hour, Min, Sec, 0, newDT); Result := Result + newDT; if Pos ('GMT', aDate) > 10 then Result := UTCToDateTime (Result) ;; // convert GMT to local time end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsCookies.Create(Aowner:TComponent); begin inherited Create(AOwner); SetLength (FCookies, 100); FTotCookies := 0; FCookieIdx := THashedStringList.Create; FCookieIdx.Sorted := true; FCookieIdx.Duplicates := dupAccept; FLoadFileName := ''; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TIcsCookies.Destroy; begin if FAutoSave and (FLoadFileName <> '') then SaveToFile(FLoadFileName, true); SetLength (FCookies, 0); FTotCookies := 0; FCookieIdx.Free; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { clear all cookies } procedure TIcsCookies.ClearAllCookies; begin SetLength (FCookies, 0); SetLength (FCookies, 100); FTotCookies := 0; FCookieIdx.Clear; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { how many saved cookies } function TIcsCookies.GetCount: integer; begin result := FCookieIdx.Count; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { get a single cookie by sorted index } function TIcsCookies.Get1Cookie (Idx: integer): TCookie; begin Result.CName := ''; if Idx >= FCookieIdx.Count then exit; Result := FCookies [Integer (FCookieIdx.Objects [Idx])]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { rebuild cookie index without expired cookies } procedure TIcsCookies.RebuildIndex; var cnr: integer ; curDT: TDateTime; key: string; begin FCookieIdx.Clear; curDT := Now ; // ?? should we removed expired records from the array as well? for cnr := 0 to FTotCookies - 1 do begin with FCookies [cnr] do begin if (CName = '') or CDelete then continue; if CPersist and (CExpireDT < curDT) then begin CName := ''; CDelete := true; continue; end; key := CDomain + CPath + CName; end; FCookieIdx.AddObject (key, TObject (cnr)); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { add a single cookie, may replace or delete } procedure TIcsCookies.AddCookie (ACookie: TCookie); var idx, cnr, I: integer ; key: string; begin if ACookie.CName = '' then exit; if ACookie.CDomain = '' then exit; // see if we have this cookie key := ACookie.CDomain + ACookie.CPath + ACookie.CName; idx := -1; if FCookieIdx.Find (key, idx) then begin cnr := Integer (FCookieIdx.Objects [idx]); FCookies [cnr] := ACookie; // replace old cookie if ACookie.CDelete then // delete old cookie begin FCookieIdx.Delete (idx); FCookies [cnr].CName := ''; end; exit; end; // add a new cookie, find first free record cnr := -1; if FTotCookies > 0 then begin for I := 0 to FTotCookies - 1 do begin if (FCookies [I].CName = '') or FCookies [I].CDelete then begin cnr := I ; break; end; end; end; if cnr = -1 then begin cnr := FTotCookies; inc (FTotCookies); end; if FTotCookies >= Length (FCookies) then SetLength (FCookies, FTotCookies+100); FCookies [cnr] := ACookie; FCookieIdx.AddObject (key, TObject (cnr)); end; // Set-Cookie: SID=31d4d96e407aad42; Max-Age=3600; Path=/; Secure; HttpOnly // Set-Cookie: lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT; Path=/; Domain=example.com // Set-Cookie: PREF=ID=8fe7e287d7a86143:FF=0:TM=1331901100:LM=1331901100:S=C2ELFTWvpWggPxhO; expires=Sun, 16-Mar-2014 12:31:40 GMT; path=/; domain=.google.com // Set-Cookie: NID=57=SDHXnvNgjSETCB5vRTJ7JbuqVKjC5dh-L8GGQdgDkhelL85yl6WOB14pc0vlJ09krTzw_4vFWRnoCq0PADUwSF0ztLX1ZgJQt9WHU0UTrnmitxCyyc91Snya2AR9I78k; expires=Sat, 15-Sep-2012 12:31:40 GMT; path=/; domain=.google.co.uk; HttpOnly // Set-Cookie: WebAppTelecom-CodeLook=OwnCode%3D%2526CallTariff%3D100173%2526TariffName%3D24Talk%2BEvening%2B; EXPIRES=Sun, 17 Mar 2013 00:00:00; PATH=/codelook.htm {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF COMPILER10_UP} procedure SetStrictDelimitedText(ALines: TStrings; const AText: string; const ADelimiter: Char); var I, J: Integer; SLen: Integer; begin ALines.Clear; SLen := Length(AText); if SLen = 0 then Exit; J := 1; for I := 1 to SLen do begin if AText[I] = ADelimiter then begin ALines.Add(Copy(AText, J, I - J)); J := I + 1; end else if (I = SLen) and (J < I) then ALines.Add(Copy(AText, J, I - J + 1)); end; end; {$ENDIF} { parse a cookie from SetCookie HTTP header } function TIcsCookies.ParseCookie (const ACookieHdr, AURL: string): TCookie; var Fields: THashedStringList; S, Proto, User, Pass, Host, Port, Path: string; curDT: TDateTime; I, P1, P2: integer; begin with result do begin CRawCookie := ''; CName := ''; CValue := ''; CExpireDT := 0; CCreateDT := 0; CAccessDT := 0; CPersist := false; CDelete := false; end; Fields := THashedStringList.Create; curDT := Now ; try ParseURL (AnsiLowercase (AURL), Proto, User, Pass, Host, Port, Path); if Length (Path) = 0 then Path := '/'; P1 := Posn('/', Path, -1); // last / P2 := Pos('.', Path); // first . if P2 > P1 then Path := Copy (Path, 1, P1); // remove file name P2 := Pos('?', Path); // first . if P2 > 0 then Path := Copy (Path, 1, P2 - 1); // remove query Fields.Delimiter := ';'; Fields.CaseSensitive := false; {$IFDEF COMPILER10_UP} Fields.StrictDelimiter := true; Fields.DelimitedText := ACookieHdr; {$ELSE} SetStrictDelimitedText(Fields, ACookieHdr, ';'); {$ENDIF} if Fields.Count = 0 then exit; if Pos ('=', Fields [0]) = 0 then exit; for I := 0 to Fields.Count - 1 do Fields [I] := Trim (Fields [I]); with result do begin CRawCookie := ACookieHdr; // TEMP for debugging CUrl := AURL; CDelete := false; CName := Fields.Names [0]; CValue := Fields.ValueFromIndex [0]; CPath := AnsiLowerCase (Fields.Values ['Path']); CDomain := AnsiLowerCase (Fields.Values ['Domain']); S := Fields.Values ['Expires']; if S <> '' then begin // cookies dates may have 2 or 4 digit years so RFC1123_StrToDate does not work CExpireDT := Cookie_StrToDate (S); end; S := Fields.Values ['Max-Age']; // Max-Age take precedence over Expires if S <> '' then CExpireDT := curDT + ((1 / SecsPerDay) * atoi (S)); if CExpireDT >= curDT then CPersist := true; if (CExpireDT > 0) and (CExpireDT < curDT) then begin CValue := ''; // cookie value expired CDelete := true; end else begin CCreateDT := curDT; end; CSecureOnly := (Fields.IndexOf('Secure') >= 1); CHttpOnly := (Fields.IndexOf('HttpOnly') >= 1); // check we have a domain and it not third party, or get it from host if CDomain <> '' then begin if CDomain [1] = '.' then Delete (CDomain, 1, 1); if Pos (CDomain, Host) < 0 then // cookie is for our host, not somewhere else begin CName := ''; // ignore cookie exit ; end; end else begin CDomain := Host; CHostOnly := true; end; // should check public suffix list to prevent cookies being set for com, co.uk, etc, over 5,000 entries // clean path of quotes, use path from URL if missing if Length (CPath) = 0 then CPath := Path; if CPath [1] = '"' then Delete (CPath, 1, 1); if CPath [Length (CPath)] = '"' then SetLength (CPath, Length (CPath)-1); if CPath [1] <> '/' then CPath := '/'; end; finally Fields.Free; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { add a cookie from SetCookie HTTP header } procedure TIcsCookies.SetCookie (const ACookieHdr, AURL: string); var ACookie: TCookie; Save: boolean; begin ACookie := ParseCookie (ACookieHdr, AURL); if ACookie.CName = '' then exit; Save := true; if Assigned (FNewCookieEvent) then FNewCookieEvent (Self, ACookie, Save); if NOT Save then exit; AddCookie (ACookie); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { find cookies for a domain and path } function TIcsCookies.GetCookies (const AURL: string): string; var idx, cnr, I: integer; Proto, User, Pass, Host, Port, Path: string; curDT: TDateTime; secure, expireflag: boolean; // pending cookies are supposed to be sorted by name, currently by domain then by name procedure FindCookies (const domain: string); begin if FCookieIdx.Count = 0 then exit; idx := -1; FCookieIdx.Find (domain, idx); // partial match while idx < FCookieIdx.Count do begin cnr := Integer (FCookieIdx.Objects [idx]); with FCookies [cnr] do begin if CDomain <> domain then exit; // finished matching domains if (CExpireDT <= curDT) then expireflag := true; // need to remove cookie in a moment if (Pos (CPath, path) = 1) and ((NOT CPersist) or (CExpireDT > curDT)) then begin // if persistend, check not expired if (NOT CSecureOnly) or (CSecureOnly = secure) then begin if result <> '' then result := result + '; '; result := result + CName + '=' + CValue; CAccessDT := curDT; end; end; end; inc (idx); // look for next name end; end; begin result := ''; expireflag := false; curDT := Now; ParseURL (AnsiLowercase (AURL), Proto, User, Pass, Host, Port, Path); if Path = '' then Path := '/'; secure := (Proto = 'https'); // now build cookie string, removing one node of host name at a time // suggestions for any better algorithm welcome!!! FindCookies (Host); I := Pos ('.', Host); if I >= 2 then begin Host := Copy (Host, I + 1, 999); // remove first node FindCookies (Host); I := Pos ('.', Host); if I >= 2 then begin Host := Copy (Host, I + 1, 999); // remove second node FindCookies (Host); end; end; if expireflag then RebuildIndex; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { load persistent cookies from string list as CSV } procedure TIcsCookies.LoadFromList (AList: TStrings); var I: integer; Fields: TStringList; ACookie: TCookie; curDT: TDateTime; begin ClearAllCookies; if AList.Count <= 1 then exit; curDT := Now ; Fields := TStringList.Create; try Fields.CommaText := AList [0]; // check we have a column name row, ideally we should parse the column names if Fields [PerCookDomain] <> PerCookTitles [PerCookDomain] then exit; if Fields.Count < PerCookTotal then exit; for I := 1 to AList.Count - 1 do begin Fields.CommaText := AList [I]; if Fields.Count < PerCookTotal then continue; with ACookie do begin CDomain := Fields [PerCookDomain]; CPath := Fields [PerCookPath]; CName := Fields [PerCookName]; CValue := Fields [PerCookValue]; CExpireDT := PackedISOToDT (Fields [PerCookExpireDT]); if CExpireDT < curDT then continue; // ignore expired cookie CCreateDT := PackedISOToDT (Fields [PerCookCreateDT]); CAccessDT := PackedISOToDT (Fields [PerCookAccessDT]); CHostOnly := (Fields [PerCookHostOnly]='1'); CSecureOnly := (Fields [PerCookSecureOnly]='1'); CHttpOnly := (Fields [PerCookHttpOnly]='1'); CUrl := Fields [PerCookUrl]; CPersist := true; CDelete := false; CRawCookie := ''; end; AddCookie (ACookie); end; finally Fields.Free; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { load persistent cookies from a file as CSV } function TIcsCookies.LoadFromFile (const AFileName: string): boolean; var Lines: TStringList; begin result := false ; FLoadFileName := AFileName; if NOT FileExists (AFileName) then exit ; Lines := TStringList.Create; try try Lines.LoadFromFile (AFileName); LoadFromList (Lines); Result := true; except end; finally Lines.Free; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { save persistent cookies to string list as CSV } procedure TIcsCookies.SaveToList (AList: TStrings); var I, J, cnr: integer; Fields: TStringList; curDT: TDateTime; begin if NOT Assigned (AList) then AList := TStringList.Create; curDT := Now ; AList.Clear; Fields := TStringList.Create; try for J := 0 to PerCookTotal - 1 do Fields.Add (PerCookTitles [J]); AList.Add (Fields.CommaText); if FCookieIdx.Count = 0 then exit; for I := 0 to FCookieIdx.Count - 1 do begin Fields.Clear; for J := 0 to PerCookTotal - 1 do Fields.Add (''); cnr := Integer (FCookieIdx.Objects [I]); with FCookies [cnr] do begin if NOT CPersist then continue; if CExpireDT < curDT then continue; // ignore expired cookie Fields [PerCookDomain] := CDomain; Fields [PerCookPath] := CPath; Fields [PerCookName] := CName; Fields [PerCookValue] := CValue; Fields [PerCookExpireDT] := DTToPackedISO (CExpireDT); Fields [PerCookCreateDT] := DTToPackedISO (CCreateDT); Fields [PerCookAccessDT] := DTToPackedISO (CAccessDT); Fields [PerCookHostOnly] := IntToStr (Ord (CHostOnly)); Fields [PerCookSecureOnly] := IntToStr (Ord (CSecureOnly)); Fields [PerCookHttpOnly] := IntToStr (Ord (CHttpOnly)); Fields [PerCookUrl] := CUrl; end; AList.Add (Fields.CommaText); end ; finally Fields.Free; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { save persistent cookies to a file as CSV } function TIcsCookies.SaveToFile (const AFileName: string; Repl: boolean = true): boolean; var Lines: TStringList; begin result := false ; if FileExists (AFileName) then begin if NOT Repl then exit; SysUtils.DeleteFile (AFileName); end; Lines := TStringList.Create; try try SaveToList (Lines); Lines.SaveToFile (AFileName); Result := True; except end; finally Lines.Free; end; end; end.
unit PhotoBoxMainFmx1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.TabControl, FMX.StdCtrls, FMX.Objects, FMX.Edit, FMX.Layouts, FMX.Media, FMX.ListBox, FMX.ExtCtrls, FB4D.Interfaces, FB4D.Configuration, CameraCaptureFra1, PhotoThreads1; type TfmxMain = class(TForm) TabControl: TTabControl; tabRegister: TTabItem; tabBox: TTabItem; layFBConfig: TLayout; edtKey: TEdit; Text2: TText; edtProjectID: TEdit; Text3: TText; lblVersionInfo: TLabel; tabCaptureImg: TTabItem; layToolbar: TLayout; lstPhotoList: TListBox; btnCaptureImg: TButton; fraCameraCapture: TfraCameraCapture1; btnPhotoLib: TButton; sptPreview: TSplitter; StatusBar: TStatusBar; lblStatus: TLabel; btnStart: TButton; procedure FormCreate(Sender: TObject); procedure btnCaptureImgClick(Sender: TObject); procedure btnPhotoLibClick(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private fConfig: IFirebaseConfiguration; function GetSettingFilename: string; procedure SaveSettings; procedure OnPhotoCaptured(Image: TBitmap; const FileName: string); procedure OnChangedColDocument(Document: IFirestoreDocument); procedure OnDeletedColDocument(const DeleteDocumentPath: string; TimeStamp: TDateTime); procedure OnListenerError(const RequestID, ErrMsg: string); procedure OnStopListening(Sender: TObject); procedure OnUploaded(Item: TListBoxItem); procedure OnUploadFailed(Item: TListBoxItem; const Msg: string); procedure OnDownloaded(Item: TListBoxItem); procedure OnDownloadFailed(Item: TListBoxItem; const Msg: string); public procedure WipeToTab(ActiveTab: TTabItem); end; var fmxMain: TfmxMain; implementation {$R *.fmx} uses System.IniFiles, System.IOUtils, FB4D.Helpers, FB4D.Firestore; resourcestring rsListenerError = 'Database listener error: %s (%s)'; rsListenerStopped = 'Database listener stopped'; rsUploaded = ' uploaded'; rsUploadFailed = ' upload failed: '; rsDownloaded = ' downloaded'; rsDownloadFailed = ' download failed: '; {$REGION 'Form Handling'} procedure TfmxMain.FormCreate(Sender: TObject); var IniFile: TIniFile; begin IniFile := TIniFile.Create(GetSettingFilename); try edtKey.Text := IniFile.ReadString('FBProjectSettings', 'APIKey', ''); edtProjectID.Text := IniFile.ReadString('FBProjectSettings', 'ProjectID', ''); fraCameraCapture.InitialDir := IniFile.ReadString('Path', 'ImageLib', TPath.GetPicturesPath); finally IniFile.Free; end; TabControl.ActiveTab := tabRegister; {$IFDEF ANDROID} btnPhotoLib.StyleLookup := 'organizetoolbutton'; {$ENDIF} if edtProjectID.Text.IsEmpty then edtProjectID.SetFocus; end; procedure TfmxMain.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; end; function TfmxMain.GetSettingFilename: string; var FileName: string; begin FileName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); result := IncludeTrailingPathDelimiter(TPath.GetHomePath) + FileName + TFirebaseHelpers.GetPlatform + '.ini'; end; procedure TfmxMain.SaveSettings; var IniFile: TIniFile; begin IniFile := TIniFile.Create(GetSettingFilename); try IniFile.WriteString('FBProjectSettings', 'APIKey', edtKey.Text); IniFile.WriteString('FBProjectSettings', 'ProjectID', edtProjectID.Text); IniFile.WriteString('Path', 'ImageLib', fraCameraCapture.InitialDir); finally IniFile.Free; end; end; procedure TfmxMain.WipeToTab(ActiveTab: TTabItem); var c: integer; begin if TabControl.ActiveTab <> ActiveTab then begin ActiveTab.Visible := true; {$IFDEF ANDROID} TabControl.ActiveTab := ActiveTab; {$ELSE} TabControl.GotoVisibleTab(ActiveTab.Index, TTabTransition.Slide, TTabTransitionDirection.Normal); {$ENDIF} for c := 0 to TabControl.TabCount - 1 do TabControl.Tabs[c].Visible := TabControl.Tabs[c] = ActiveTab; end; end; {$ENDREGION} {$REGION 'User Login'} procedure TfmxMain.btnStartClick(Sender: TObject); var Query: IStructuredQuery; begin fConfig := TFirebaseConfiguration.Create(edtKey.Text, edtProjectID.Text); layFBConfig.Visible := false; Query := TStructuredQuery.CreateForCollection(TPhotoThread.cCollectionID); fConfig.Database.SubscribeQuery(Query, OnChangedColDocument, OnDeletedColDocument); fConfig.Database.StartListener(OnStopListening, OnListenerError); WipeToTab(tabBox); end; {$ENDREGION} procedure TfmxMain.btnCaptureImgClick(Sender: TObject); begin fraCameraCapture.StartCapture(OnPhotoCaptured); end; procedure TfmxMain.btnPhotoLibClick(Sender: TObject); begin fraCameraCapture.StartTakePhotoFromLib(OnPhotoCaptured); end; procedure TfmxMain.OnPhotoCaptured(Image: TBitmap; const FileName: string); var Item: TListBoxItem; Upload: TPhotoThread; Thumbnail: TBitmap; begin if TabControl.ActiveTab <> tabBox then WipeToTab(tabBox); Item := TListBoxItem.Create(lstPhotoList); Item.Text := FileName; Thumbnail := TPhotoThread.CreateThumbnail(Image); try Item.ItemData.Bitmap.Assign(Thumbnail); finally Thumbnail.Free; end; lstPhotoList.AddObject(Item); lstPhotoList.ItemIndex := Item.Index; Upload := TPhotoThread.CreateForUpload(fConfig, Image, Item); Upload.StartThread(OnUploaded, OnUploadFailed); end; procedure TfmxMain.OnUploaded(Item: TListBoxItem); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsUploaded); end; procedure TfmxMain.OnUploadFailed(Item: TListBoxItem; const Msg: string); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsUploadFailed + Msg); end; procedure TfmxMain.OnDownloaded(Item: TListBoxItem); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsDownloaded); end; procedure TfmxMain.OnDownloadFailed(Item: TListBoxItem; const Msg: string); begin fraCameraCapture.ToastMsg(Item.Text + ' ' + rsDownloadFailed + Msg); end; procedure TfmxMain.OnChangedColDocument(Document: IFirestoreDocument); var Download: TPhotoThread; begin Download := TPhotoThread.CreateForDownload(fConfig, lstPhotoList, Document); Download.StartThread(OnDownloaded, OnDownloadFailed); end; procedure TfmxMain.OnDeletedColDocument(const DeleteDocumentPath: string; TimeStamp: TDateTime); begin // Todo end; procedure TfmxMain.OnListenerError(const RequestID, ErrMsg: string); begin if not Application.Terminated then fraCameraCapture.ToastMsg(Format(rsListenerError, [ErrMsg, RequestID])); end; procedure TfmxMain.OnStopListening(Sender: TObject); begin if not Application.Terminated then fraCameraCapture.ToastMsg(rsListenerStopped); end; end.
unit NtUtils.Exec.Shell; interface uses NtUtils.Exec; type TExecShellExecute = class(TInterfacedObject, IExecMethod) function Supports(Parameter: TExecParam): Boolean; function Execute(ParamSet: IExecProvider): TProcessInfo; end; implementation uses Winapi.Shell, Winapi.WinUser, NtUtils.Exceptions, NtUtils.Exec.Win32; { TExecShellExecute } function TExecShellExecute.Execute(ParamSet: IExecProvider): TProcessInfo; var ShellExecInfo: TShellExecuteInfoW; RunAsInvoker: IInterface; begin FillChar(ShellExecInfo, SizeOf(ShellExecInfo), 0); ShellExecInfo.cbSize := SizeOf(ShellExecInfo); ShellExecInfo.fMask := SEE_MASK_NOASYNC or SEE_MASK_UNICODE or SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_NO_UI; // SEE_MASK_NO_CONSOLE is opposite to CREATE_NEW_CONSOLE if ParamSet.Provides(ppNewConsole) and not ParamSet.NewConsole then ShellExecInfo.fMask := ShellExecInfo.fMask or SEE_MASK_NO_CONSOLE; ShellExecInfo.lpFile := PWideChar(ParamSet.Application); if ParamSet.Provides(ppParameters) then ShellExecInfo.lpParameters := PWideChar(ParamSet.Parameters); if ParamSet.Provides(ppCurrentDirectory) then ShellExecInfo.lpDirectory := PWideChar(ParamSet.CurrentDircetory); if ParamSet.Provides(ppRequireElevation) and ParamSet.RequireElevation then ShellExecInfo.lpVerb := 'runas'; if ParamSet.Provides(ppShowWindowMode) then ShellExecInfo.nShow := ParamSet.ShowWindowMode else ShellExecInfo.nShow := SW_SHOWNORMAL; // Set RunAsInvoker compatibility mode. It will be reverted // after exiting from the current function. if ParamSet.Provides(ppRunAsInvoker) then RunAsInvoker := TRunAsInvoker.SetCompatState(ParamSet.RunAsInvoker); WinCheck(ShellExecuteExW(ShellExecInfo), 'ShellExecuteExW'); // We use SEE_MASK_NOCLOSEPROCESS to get a handle to the process. // The caller must close it after use. FillChar(Result, SizeOf(Result), 0); Result.hProcess := ShellExecInfo.hProcess; end; function TExecShellExecute.Supports(Parameter: TExecParam): Boolean; begin case Parameter of ppParameters, ppCurrentDirectory, ppNewConsole, ppRequireElevation, ppShowWindowMode, ppRunAsInvoker: Result := True; else Result := False; end; end; end.
unit Entidade.TipoCulto; interface uses SimpleAttributes; type TTIPO_CULTO = class private FDESCRICAO: string; FID: integer; FOBJETIVO: string; procedure SetID(const Value: integer); procedure SetDESCRICAO(const Value: string); procedure SetOBJETIVO(const Value: string); published [PK,AutoInc] property ID:integer read FID write SetID; property DESCRICAO:string read FDESCRICAO write SetDESCRICAO; property OBJETIVO:string read FOBJETIVO write SetOBJETIVO; end; implementation { TTIPO_CULTO } procedure TTIPO_CULTO.SetID(const Value: integer); begin FID := Value; end; procedure TTIPO_CULTO.SetDESCRICAO(const Value: string); begin FDESCRICAO := Value; end; procedure TTIPO_CULTO.SetOBJETIVO(const Value: string); begin FOBJETIVO := Value; 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 uDebugLogging; interface procedure DebugLog(const aMsg : string); procedure DebugFmt(const aFormat: string; const Args: array of const); implementation uses {$IFNDEF FPC} Windows, {$ENDIF} SysUtils; procedure WriteToLog(const aMsg : string); begin {$IFNDEF FPC} OutputDebugString(PChar(aMsg)); {$ENDIF} end; procedure DebugLog(const aMsg : string); begin WriteToLog(aMsg); end; procedure DebugFmt(const aFormat: string; const Args: array of const); var msg : string; begin msg := Format(aFormat, Args); WriteToLog(msg); end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: Application Server Component. This is the communication kernel for the application server. This component handle all the communication work for the application server, keeping track of user connections. A complete application server is made of this somponent, a request broker component and a set of server components. See project SrvTst for a sample application server program. Creation: March 02, 1998 Version: 7.00 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list midware@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1998-2010 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> 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 and or any derived or altered versions for any purpose, excluding commercial applications. You can use this software for personal use only. You may distribute it freely untouched. The following restrictions applies: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. 2. If you use this software in a product, an acknowledgment in the product documentation and displayed on screen is required. The text must be: "This product is based on MidWare. Freeware source code is available at http://www.overbyte.be" 3. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. This notice may not be removed or altered from any source distribution and must be added to the product documentation. Updates: Mar 27, 1998 V1.01 Added ClientWSocket[] indexed property to retrive the client TWSocket reference (helpful for example to display all connected client IP addresses). Apr 10, 1998 V1.02 Accepted the client connection before triggering the OnClientConnected event handler. Apr 14, 1998 V1.03 Changed LongInt to Integer parameter ProcessClientCommand to match function description in TClientWSocket - ApSrvCli.PAS (from Bruce Christensen <brucec@compusmart.ab.ca>) Added a Banner property. May 18, 1998 V1.04 Implemented client timeout functions. May 23, 1998 V1.05 Added comments to describes properties, events and methods. Jun 01, 1998 V1.06 Removed beta status. Changed "legal stuff" to prohibe commercial applications whithout an agreement. Jun 07, 1998 V1.07 Added functionnalities to support encryption and compression Jun 19, 1998 V1.08 DisconnectAll now trigger the OnSessionClosed event for each client. Jul 08, 1998 V1.09 Adapted for Delphi 4 Jul 15, 1998 V1.10 Added TAppServer.FClientClass to allow descendent class to use a custom class for his clients sockets. Aug 17, 1998 V1.11 Added handling for client buffer overflow Added SendStringResponseToClient to correctly format error responses to client (Timeout and overflow) Sep 10, 1998 V1.12 Added RequestCount and ConnectCount property and support Dec 12, 1998 V1.13 Added background exception handling Feb 14, 1999 V1.14 Use runtime dynamic link with winsock, using wsocket functionswhich are linked at runtime instead of loadtime. This allows programs to run without winsock installed, provided program doesn't try to use TWSocket or winsock function without first checking for winsock installation. Added functions AppServerWindowProc, AppServerAllocateHWnd and AppServerDeallocateHWnd to handle private message handling without using the Forms unit (help for writing services or non GUI applications). Added OnBgexception event and related logic. Dec 07, 2000 V1.15 Added 100mS sleep right after a client connect when we run on Windows 2000. Thanks to Thomas Hensle <freevcs@thensle.de>. Mar 03, 2002 V1.16 Added Addr property Mar 23, 2002 V1.17 In ProcessClientCommand, truncate at 1024 bytes for display Mar 28, 2002 V1.18 Made ClientClass a public property Apr 09, 2002 V1.19 Implemented datagram and datagram types feature. This allows a server to send datagram to connected clients. Jul 19, 2002 V1.19 Ignore send exceptions in SendResponseToClient Aug 13, 2002 V1.20 Use CliWsocket.ServerObject reference in LinkClientWSocketAndServerObject and CliSessionClosed. Sep 02, 2002 V1.21 Added FOnServerSObjException event. Sep 08, 2002 V1.22 Changed PChar to Pointer in TProcessRequestEvent and TClientCommandEvent. Sep 26, 2002 V1.23 Added CmdBuf and CmdLen to OnServerSObjException event. Added FunctionCode to error message when a TServerObject crashed. Nov 27, 2002 V1.24 Added ListenBacklog property, default to 5. Sep 27, 2003 V1.25 Fixed ProcessClientCommand to correctly truncate data after Max_Display_len characters.Thanks to Marcel Isler <goodfun@goodfun.org> for finding this bug. Aug 28, 2004 V1.26 Use MWDefs.inc Jun 18, 2005 V2.00 Use TWSocketServer. That's the begining of the SSL enabled version. Sep 13, 2005 V2.01 Propagated FSrvWSocket.OnBgExecption to TAppServer.OnServerBgException (See SrvWSocketBgException). Avoid closing server socket when exception occur during early client connection phase so that the server stay up and running. Oct 03, 2005 V2.02 Added _OSVERSIONINFOA for Delphi 3. Thanks to Rocco Neri <rocco.neri@corael.it> for his help. Oct 23, 2005 V2.03 Updated for Delphi 2006 and BCB 2006 Feb 18, 2007 V2.03 Added SetName and related. Aug 01, 2008 V7.00 Update for ICS-V7 and Delphi 2009. Warning: Unicode not really supported. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteApServer; interface {$I OverbyteMwDefs.inc} uses Windows, Messages, SysUtils, Classes, StdCtrls, ExtCtrls, { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} IcsSSLEAY, IcsLIBEAY, {$ENDIF} OverbyteRBroker, OverbyteRFormat, OverbyteApSrvCli, OverbyteIcsLibrary, OverbyteIcsWSocket, OverbyteIcsWSocketS, OverbyteIcsWinsock, OverbyteIcsWndControl; const ApServerVersion = 700; CopyRight : String = ' TAppServer (c) 1998-2008 F. Piette V7.00 '; // WM_DESTROY_CLIENT_SOCKET = WM_USER + 1; {$IFDEF DELPHI3} type // Missing from Delphi 3 Windows unit _OSVERSIONINFOA = record dwOSVersionInfoSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformId: DWORD; szCSDVersion: array[0..127] of AnsiChar; end; TOSVersionInfoA = _OSVERSIONINFOA; TOSVersionInfo = TOSVersionInfoA; POSVersionInfoA = ^TOSVersionInfoA; POSVersionInfo = POSVersionInfoA; OSVERSIONINFO = _OSVERSIONINFOA; function GetVersionEx(var lpVersionInformation: TOSVersionInfo): BOOL; stdcall; {$ENDIF} type EAppServerException = class(Exception); TClientEvent = procedure (Sender : TObject; CliWSocket : TClientWSocket) of object; TClientCommandEvent = procedure (Sender : TObject; CliWSocket : TClientWSocket; CmdBuf : Pointer; CmdLen : Integer) of object; TClientTimeoutEvent = procedure (Sender : TObject; CliWSocket : TClientWSocket; var CanClose : Boolean) of object; TClientBgException = procedure (Sender : TObject; CliWSocket : TClientWSocket; E : Exception) of object; TProcessRequestEvent = procedure (Sender : TObject; CliWSocket : TClientWSocket; var CmdBuf : Pointer; var CmdLen : Integer) of object; TAppServerBgExceptionEvent = procedure (Sender : TObject; E : Exception) of object; TAppServerSObjExceptionEvent = procedure (Sender : TObject; E : Exception; CmdBuf : Pointer; CmdLen : Integer) of object; TAppServerOption = (asoAutoStart, asoDisplayCommands, asoDisplayClientCount, asoDisplayDatagrams); TAppServerOptions = set of TAppServerOption; TClientWSocketClass = class of TClientWSocket; {:TAppServer component is responsible for client connection, communication and management. It is constitued of a listening TWSocket receiving client connections. For each connection a new TClientWSocket is instanciated. TAppServer work with a linked TRequestBroker which manage to execute client request. } TAppServer = class(TIcsWndControl) protected FAddr : String; FBanner : String; FDisplayMemo : TCustomMemo; FClientCountLabel : TLabel; FRequestCount : LongInt; FConnectCount : LongInt; FRequestBroker : TRequestBroker; FSrvWSocket : TWSocketServer; FClientClass : TClientWSocketClass; FPort : String; // FHandle : HWND; FClientTimeout : LongInt; { in seconds } FTimeoutInterval : LongInt; { in seconds } FTimer : TTimer; {$IFDEF COMPILER12_UP} FSysVersionInfo : _OSVersionInfoW; {$ELSE} FSysVersionInfo : _OSVersionInfoA; {$ENDIF} FListenBacklog : Integer; FMsg_WM_DESTROY_CLIENT_SOCKET : UINT; FOptions : TAppServerOptions; FOnDisplay : TDisplayEvent; FOnClientConnected : TClientEvent; FOnClientClosed : TClientEvent; FOnClientCommand : TClientCommandEvent; FOnClientTimeout : TClientTimeoutEvent; FOnClientBgException : TClientBgException; FOnBeforeSendReply : TClientEvent; FOnAfterSendReply : TClientEvent; FOnBeforeProcessRequest : TProcessRequestEvent; FOnAfterProcessRequest : TProcessRequestEvent; FOnServerBgException : TAppServerBgExceptionEvent; FOnServerSObjException : TAppServerSObjExceptionEvent; procedure AllocateMsgHandlers; override; procedure FreeMsgHandlers; override; function MsgHandlersCount: Integer; override; procedure WndProc(var MsgRec: TMessage); override; procedure CreateSocket; virtual; procedure SetClientClass(const Value: TClientWSocketClass); virtual; procedure Notification(AComponent: TComponent; operation: TOperation); override; procedure SrvWSocketClientConnect(Sender : TObject; Client : TWSocketClient; ErrCode : Word); virtual; procedure SrvWSocketClientDisconnect(Sender : TObject; Client : TWSocketClient; ErrCode : Word); virtual; procedure SrvWSocketBgException(Sender : TObject; E : Exception; var CanClose : Boolean); procedure SendResponseToClient(Dest : TObject; ORB : TRequestBroker; Status : Integer; Response : PAnsiChar; Len : Integer); virtual; procedure SendStringResponseToClient( Dest : TObject; ORB : TRequestBroker; Status : Integer; Response : AnsiString); virtual; procedure ProcessClientCommand(Sender : TObject; CmdBuf : PAnsiChar; CmdLen : Integer); virtual; procedure ProcessClientBgException(Sender : TObject; E : Exception; var CanClose : Boolean); virtual; procedure ProcessClientOverflow(Sender : TObject; var CanAbort : Boolean); virtual; function GetClientCount : Integer; function GetClientWSocket(nIndex : Integer) : TClientWSocket; procedure SetClientTimeout(newValue : LongInt); procedure SetTimeoutInterval(newValue : LongInt); procedure TimerTimer(Sender : TObject); procedure CliTimeout(Sender : TObject; var CanClose : Boolean); virtual; procedure Loaded; override; procedure InternalDisplay(Sender : TObject; const Msg : String); procedure TriggerBgException(E : Exception; var CanClose : Boolean); override; procedure TriggerServerSObjException(E: Exception; CmdBuf : Pointer; CmdLen : Integer); virtual; procedure LinkClientWSocketAndServerObject(ServerObject : TServerObject; Cli : TObject); procedure SetName(const NewName: TComponentName); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {:The start procedure will start the server. The server will accept new client connections. } procedure Start; {:The Stop procedure will stop the server which will no more accept new clients, but will not disconnect already connected clients. } procedure Stop; {:DisconnectAll will disconnect every connected client. Do not confuse with the Stop procedure. } procedure DisconnectAll; {:SendDatagramToClient will send a datagram to the specified client } procedure SendDatagramToClient(ToClient : TObject; const DGramType : AnsiString; Datagram : PAnsiChar; DataLen : Integer); {:SrvWSocket is the underlayng TWSocketServer component. } property SrvWSocket : TWSocketServer read FSrvWSocket; {:ClientCount gives the actual numlber of connected clients. } property ClientCount : Integer read GetClientCount; {:ConnectCount gives the total number of connection received since server startup} property ConnectCount : LongInt read FConnectCount; {:RequestCount gives the total number of request received since server startup} property RequestCount : LongInt read FRequestCount; {:ClientWSocket is an indexed property whose value is the reference to each connected client. } property ClientWSocket[nIndex : Integer] : TClientWSocket read GetClientWSocket; {:The Handle property is the windows handle for the hidden window the component uses for internal messages. } // property Handle : HWND read FHandle; {:The ClientClass property allows the programmer to change the class instanciated for each new client connection. This class is the right place to put data for client session. } property ClientClass : TClientWSocketClass read FClientClass write SetClientClass; published property DisplayMemo : TCustomMemo read FDisplayMemo write FDisplayMemo; property ClientCountLabel : TLabel read FClientCountLabel write FClientCountLabel; property Options : TAppServerOptions read FOptions write FOptions; {:The banner property is the text that is sent to the client when the connection has been established. This banner can be anything because the client ignore it. } property Banner : String read FBanner write FBanner; {:The Addr property allows to select the inteface which will be used to listen to client. The default value is '0.0.0.0' make the component listen on all available interfaces. } property Addr : String read FAddr write FAddr; {:The port property gives the port number used by the server to listen for client connection. It can be a numeric value or a string value which must be present in the 'services' file. You should not use any port number already used in your computer. This default value is 2106. } property Port : String read FPort write FPort; {:ClientTimeout gives the time in seconds before the server disconnect a client without activity. The default value is 300 seconds. } property ClientTimeout : LongInt read FClientTimeout write SetClientTimeout; {:The server periodically check for client timeout. It uses a single TTimer component for this check. The TimeoutInterval is this timer interval and default to 30 seconds. This means that every 30", the server will goes thru the client list and check for timeout. A smaller value gives better accuracy in timeout detection, but produce some overhead, specially if the number of client is large. } property TimeoutInterval : LongInt read FTimeoutInterval write SetTimeoutInterval; {:The server component receive client request, data parameters and send replies to client. But it delegate the request dispatching to a dedicated component: the RequestBroker component. } property RequestBroker : TRequestBroker read FRequestBroker write FRequestBroker; {:The socket component has a connection backlog queue. This gives the number of pending connection requests. Default to 5. } property ListenBacklog : Integer read FListenBacklog write FListenBacklog; {:Sometimes, the server can display some infos about his internal working. Each time the server wants to display that info, it triggers the OnDisplay event. There is no need to have an event handler connected to this event. If you ad an event handler, it is probably to display the messages on the server's user interface, or just to log it into a file. Messages to be displayed can be generate by the TAppServer component or any TServerObject used in the server. } property OnDisplay : TDisplayEvent read FOnDisplay write FOnDisplay; {:This event is triggered when a client connect to the server. It could be used to disconnect unwanted client or any other processing that must be done when a new client connect, such as updating the server user interface to show how many clients are connected. } property OnClientConnected : TClientEvent read FOnClientConnected write FOnClientConnected; {:When a client disconnect, the OnClientClosed event is triggered. The event handler could be used to update the server's user interface or to do any other post-processing or cleaning task. } property OnClientClosed : TClientEvent read FOnClientClosed write FOnClientClosed; {:Clients connects to the server to send commands (also called requests) and wait for server responses. The OnClientCommand is triggered when such a command arrives, before it gets executed. The event handler can use the command for any purpose, it can even change it. } property OnClientCommand : TClientCommandEvent read FOnClientCommand write FOnClientCommand; {:When a client had no more activity during some time specified by the ClientTimeout property, it is automatically disconnected. If this occurs, the OnClientTimeout event is triggred. } property OnClientTimeout : TClientTimeoutEvent read FOnClientTimeout write FOnClientTimeout; {:When an exception is triggered in the background. } property OnClientBgException : TClientBgException read FOnClientBgException write FOnClientBgException; {:The OnBeforeSendReply event is called when a reply is ready to be transmitted to the client. A reply is made of a header and a body which are accessible thru the CliWSocket properties. The event has the possibility to process the header and answer to encrypt or compress them. It can even allocate some memory for holding the processed header and body. Use the OnAfterSendReply to free any allocated memory. The processed data must *not* contains CR/LF pair as it is used by the client to delimit the reply. If processed data has CR/LF, then it must be escaped in some way. } property OnBeforeSendReply : TClientEvent read FOnBeforeSendReply write FOnBeforeSendReply; {:The OnAfterSendReply event is called once the reply header and body has ben written to the internal buffer for sending in the background. It's the right place to deallocate any resource allocated in the OnBeforeSendReply. } property OnAfterSendReply : TClientEvent read FOnAfterSendReply write FOnAfterSendReply; {:The OnBeforeProcessRequest event is triggered just before anything is done with a request received from the client. This is the right place to add code for decryption/decompression. If needed, the event handler can allocate memory or resources and change the values on the arguments (passed by var) to fit the requirement. Allocated resources must be freed from the OnAfterProcessCommand. } property OnBeforeProcessRequest : TProcessRequestEvent read FOnBeforeProcessRequest write FOnBeforeProcessRequest; {:The OnAfterProcessRequest is called when a request has been transformed to a command for execution. It main purpose is to cleanup resources allocated in the OnBeforeProcessRequest event. } property OnAfterProcessRequest : TProcessRequestEvent read FOnAfterProcessRequest write FOnAfterProcessRequest; {:The OnBgException event is triggered when an exception occurs in the background (occuring in an event handler called from the message pump). If not handled, those exceptions are simply ignored. } property OnServerBgException : TAppServerBgExceptionEvent read FOnServerBgException write FOnServerBgException; {:The OnServerSObjException event is triggered when a TServerObject triggers an unhandled exception. } property OnServerSObjException : TAppServerSObjExceptionEvent read FOnServerSObjException write FOnServerSObjException; end; { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} {$I ApServerIntfSsl.inc} {$ENDIF} //procedure Register; implementation var GClientWSocketID : Integer; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} (* procedure Register; begin RegisterComponents('FPiette', [TAppServer {$IFDEF USE_SSL} , TSslAppServer {$ENDIF} ]); end; *) {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF DELPHI3} // Missing from Delphi 3 Windows unit function GetVersionEx; external kernel32 name 'GetVersionExA'; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This function is a callback function. It means that it is called by } { windows. This is the very low level message handler procedure setup to } { handle the message sent by windows to handle messages. } function AppServerWindowProc( ahWnd : HWND; auMsg : Integer; awParam : WPARAM; alParam : LPARAM): Integer; stdcall; var Obj : TObject; MsgRec : TMessage; begin { At window creation asked windows to store a pointer to our object } Obj := TObject(GetWindowLong(ahWnd, 0)); { If the pointer doesn't represent a TAppServer, just call the default } { procedure } if not (Obj is TAppServer) then Result := DefWindowProc(ahWnd, auMsg, awParam, alParam) else begin { Delphi use a TMessage type to pass parameter to his own kind of } { windows procedure. So we are doing the same... } MsgRec.Msg := auMsg; MsgRec.wParam := awParam; MsgRec.lParam := alParam; { May be a try/except around next line is needed. Not sure ! } TAppServer(Obj).WndProc(MsgRec); Result := MsgRec.Result; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This global variable is used to store the windows class characteristic } { and is needed to register the window class used by TWSocket } var AppServerWindowClass: TWndClass = ( style : 0; lpfnWndProc : @AppServerWindowProc; cbClsExtra : 0; cbWndExtra : SizeOf(Pointer); hInstance : 0; hIcon : 0; hCursor : 0; hbrBackground : 0; lpszMenuName : nil; lpszClassName : 'AppServerWindowClass'); {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Allocate a window handle. This means registering a window class the first } { time we are called, and creating a new window each time we are called. } function AppServerAllocateHWnd(Obj : TObject): HWND; var TempClass : TWndClass; ClassRegistered : Boolean; begin { Check if the window class is already registered } AppServerWindowClass.hInstance := HInstance; ClassRegistered := GetClassInfo(HInstance, AppServerWindowClass.lpszClassName, TempClass); if not ClassRegistered then begin { Not yet registered, do it right now } Result := Windows.RegisterClass(AppServerWindowClass); if Result = 0 then Exit; end; { Now create a new window } Result := CreateWindowEx(WS_EX_TOOLWINDOW, AppServerWindowClass.lpszClassName, '', { Window name } WS_POPUP, { Window Style } 0, 0, { X, Y } 0, 0, { Width, Height } 0, { hWndParent } 0, { hMenu } HInstance, { hInstance } nil); { CreateParam } { if successfull, the ask windows to store the object reference } { into the reserved byte (see RegisterClass) } if (Result <> 0) and Assigned(Obj) then SetWindowLong(Result, 0, Integer(Obj)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Free the window handle } //procedure AppServerDeallocateHWnd(Wnd: HWND); //begin // DestroyWindow(Wnd); //end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TAppServer.Create(AOwner: TComponent); begin inherited Create(AOwner); AllocateHWnd; FBanner := 'Welcome to MidWare server'; // FHandle := AppServerAllocateHWnd(Self); // 14/02/99 AllocateHWnd(WndProc); CreateSocket; // FClientList := TList.Create; FClientTimeout := 300; { 5 minutes timeout } FTimeoutInterval := 30; { Check timeout every 30 seconds } FTimer := TTimer.Create(Self); FTimer.Name := 'Timer_AppServer'; FTimer.Enabled := FALSE; FTimer.OnTimer := TimerTimer; FTimer.Interval := FTimeoutInterval * 1000; FOptions := [asoDisplayCommands, asoDisplayClientCount]; FListenBacklog := 5; FSysVersionInfo.dwOSVersionInfoSize := SizeOf(OSVERSIONINFO); GetVersionEx(FSysVersionInfo); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TAppServer.Destroy; begin try // if Assigned(FClientList) then begin // FClientList.Destroy; // FClientList := nil; // end; if Assigned(FSrvWSocket) then begin FSrvWSocket.Destroy; FSrvWSocket := nil; end; if Assigned(FTimer) then begin FTimer.Destroy; FTimer := nil; end; except { Ignore any exception, we cannot handle them } end; // AppServerDeallocateHWnd(FHandle); // 14/02/99 DeallocateHWnd(FHandle); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.CreateSocket; begin FClientClass := TClientWSocket; FSrvWSocket := TWSocketServer.Create(Self); FSrvWSocket.Name := 'AppServer_WSocket'; FSrvWSocket.ClientClass := FClientClass; FAddr := '0.0.0.0'; FPort := '2106'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.Loaded; begin inherited Loaded; if csDesigning in ComponentState then Exit; if (asoDisplayClientCount in FOptions) and Assigned(FClientCountLabel) then FClientCountLabel.Caption := '0'; if asoAutoStart in FOptions then Start; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { All exceptions *MUST* be handled. If an exception is not handled, the } { application will be shut down ! } procedure TAppServer.TriggerBgException( E : Exception; var CanClose : Boolean); begin { First call the error event handler, if any } if Assigned(FOnServerBgException) then begin try FOnServerBgException(Self, E); except end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { All exceptions *MUST* be handled. If an exception is not handled, the } { application will be shut down ! } procedure TAppServer.TriggerServerSObjException( E : Exception; CmdBuf : Pointer; CmdLen : Integer); begin if Assigned(FOnServerSObjException) then begin try FOnServerSObjException(Self, E, CmdBuf, CmdLen); except end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TAppServer.MsgHandlersCount : Integer; begin Result := 1 + inherited MsgHandlersCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.AllocateMsgHandlers; begin inherited AllocateMsgHandlers; FMsg_WM_DESTROY_CLIENT_SOCKET := FWndHandler.AllocateMsgHandler(Self); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.FreeMsgHandlers; begin if Assigned(FWndHandler) then begin FWndHandler.UnregisterMessage(FMsg_WM_DESTROY_CLIENT_SOCKET); end; inherited FreeMsgHandlers; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.WndProc(var MsgRec: TMessage); var CanClose : Boolean; begin try with MsgRec do begin // if Msg = FMsg_WM_DESTROY_CLIENT_SOCKET then // ClientWSocket(lParam).Destroy // else Result := DefWindowProc(Handle, Msg, wParam, lParam); end; except on E:Exception do begin CanClose := TRUE; TriggerBgException(E, CanClose); // ToDo: handle CanClose end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.Notification(AComponent: TComponent; operation: TOperation); begin inherited Notification(AComponent, operation); if operation = opRemove then begin if AComponent = FRequestBroker then FRequestBroker := nil else if AComponent = FSrvWSocket then FSrvWSocket := nil else if AComponent = FClientCountLabel then FClientCountLabel := nil else if AComponent = FDisplayMemo then FDisplayMemo := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.DisconnectAll; var I : Integer; begin for I := FSrvWSocket.ClientCount - 1 downto 0 do FSrvWSocket.Client[0].Close; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.Start; begin if not Assigned(FSrvWSocket) then Exit; FSrvWSocket.Close; FSrvWSocket.Proto := 'tcp'; FSrvWSocket.Port := FPort; FSrvWSocket.Addr := FAddr; FSrvWSocket.Banner := FBanner; FSrvWSocket.OnClientConnect := SrvWSocketClientConnect; FSrvWSocket.OnClientDisconnect := SrvWSocketClientDisconnect; FSrvWSocket.OnBgException := SrvWSocketBgException; FSrvWSocket.ListenBacklog := FListenBacklog; FSrvWSocket.Listen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.Stop; begin if not Assigned(FSrvWSocket) then Exit; FSrvWSocket.Close; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.InternalDisplay(Sender : TObject; const Msg : String); begin try FDisplayMemo.Lines.BeginUpdate; try if FDisplayMemo.Lines.Count > 200 then begin while FDisplayMemo.Lines.Count > 200 do FDisplayMemo.Lines.Delete(0); end; if Assigned(FDisplayMemo) then FDisplayMemo.Lines.Add(Msg); finally FDisplayMemo.Lines.EndUpdate; SendMessage(FDisplayMemo.Handle, EM_SCROLLCARET, 0, 0); end; except end; try if Assigned(FOnDisplay) then FOnDisplay(Sender, Msg); except end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SrvWSocketClientConnect( Sender : TObject; Client : TWSocketClient; ErrCode : Word); var CliWSocket : TClientWSocket; begin CliWSocket := Client as TClientWSocket; { Give a unique name to this client socket } Inc(GClientWSocketID); CliWSocket.Name := Copy(CliWSocket.ClassName, 2, 64) + '_' + Self.Name + '_' + IntToStr(GClientWSocketID); CliWSocket.OnDisplay := InternalDisplay; CliWSocket.OnOverflow := ProcessClientOverflow; CliWSocket.OnCommand := ProcessClientCommand; CliWSocket.OnBgException := ProcessClientBgException; CliWSocket.OnTimeout := CliTimeout; CliWSocket.Banner := String(FBanner); CliWSocket.LineEnd := #13#10; CliWSocket.CommandTimeOut := FClientTimeout / (24 * 3600); if Assigned(FClientCountLabel) and (asoDisplayClientCount in FOptions) then FClientCountLabel.Caption := IntToStr(FSrvWSocket.ClientCount); if Assigned(FOnClientConnected) then begin // Should I move this Sleep outside of the above if ? if FSysVersionInfo.dwMajorVersion = 5 then Sleep(100); // If OS is Windows 2000 then "sleep" for 100 ms FOnClientConnected(Self, CliWSocket); end; { We have a client, we need to check for timeout } if FTimeoutInterval > 0 then FTimer.Enabled := TRUE; Inc(FConnectCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SrvWSocketClientDisconnect( Sender : TObject; Client : TWSocketClient; ErrCode: Word); var CliWSocket : TClientWSocket; begin CliWSocket := Client as TClientWSocket; if Assigned(FOnClientClosed) then FOnClientClosed(Self, CliWSocket); { Remove reference to this CliWSocket from TServerObject } if Assigned(CliWSocket.ServerObject) then begin if Assigned(TServerObject(CliWSocket.ServerObject).OrbDataPtr) then TServerObject(CliWSocket.ServerObject).OrbDataPtr.Tag := nil; end; if (asoDisplayClientCount in FOptions) and Assigned(FClientCountLabel) then FClientCountLabel.Caption := IntToStr(FSrvWSocket.ClientCount - 1); { Do we still need to check for timeout ? } if (FSrvWSocket.ClientCount <= 1) and Assigned(FTimer) then FTimer.Enabled := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.CliTimeout(Sender : TObject; var CanClose : Boolean); var CliWSocket : TClientWSocket; begin CliWSocket := Sender as TClientWSocket; if Assigned(FOnClientTimeout) then FOnClientTimeout(Self, CliWSocket, canClose); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SendResponseToClient( Dest : TObject; ORB : TRequestBroker; Status : Integer; Response : PAnsiChar; Len : Integer); var CliWSocket : TClientWSocket; Header : AnsiString; begin { Verify that the Dest is still in our client list } { It is removed if the client disconnected } if not FSrvWSocket.IsClient(Dest) then Exit; { The client is still there, send the result } CliWSocket := Dest as TClientWSocket; Header := IcsIntToStrA(Status) + ' '; CliWSocket.ReplyHeader := PAnsiChar(Header); CliWSocket.ReplyHeaderLen := Length(Header); CliWSocket.ReplyBody := Response; CliWSocket.ReplyBodyLen := Len; if Assigned(FOnBeforeSendReply) then FOnBeforeSendReply(Self, CliWSocket); try CliWSocket.SendReply; except // Ignore any exception while trying to send data // Client maybe dead ! end; if Assigned(FOnAfterSendReply) then FOnAfterSendReply(Self, CliWSocket); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SendStringResponseToClient( Dest : TObject; ORB : TRequestBroker; Status : Integer; Response : AnsiString); var Buffer : TMWBuffer; begin Buffer := TMWBuffer.Create(nil); try Buffer.DataBufferSize := 256; { Remember, there is AutoExpand } Buffer.WriteFields(TRUE, [Response]); SendResponseToClient(Dest, ORB, Status, Buffer.DataBuffer, Buffer.DataBufferCount); finally Buffer.Destroy; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.ProcessClientOverflow( Sender : TObject; var CanAbort : Boolean); var CliWSocket : TClientWSocket; begin try CliWSocket := Sender as TClientWSocket; if Assigned(FDisplayMemo) then FDisplayMemo.Lines.Add(String(CliWSocket.PeerAddr) + ' Input buffer overflow'); SendStringResponseToClient(CliWSocket, FRequestBroker, 406, 'Input buffer at server overflowed'); except end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SrvWSocketBgException( Sender : TObject; E : Exception; var CanClose : Boolean); begin CanClose := FALSE; TriggerBgException(E, CanClose); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.ProcessClientBgException( Sender : TObject; E : Exception; var CanClose : Boolean); var CliWSocket : TClientWSocket; begin CliWSocket := Sender as TClientWSocket; if Assigned(FOnClientBgException) then FOnClientBgException(Self, CliWSocket, E); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.ProcessClientCommand( Sender : TObject; CmdBuf : PAnsiChar; CmdLen : Integer); const Max_Display_len = 256; var CliWSocket : TClientWSocket; Buffer : AnsiString; BufFct : AnsiString; I : Integer; Ch : AnsiChar; HasDatagram : Boolean; DGramType : AnsiString; begin CliWSocket := Sender as TClientWSocket; if Assigned(FOnBeforeProcessRequest) then FOnBeforeProcessRequest(Self, CliWSocket, Pointer(CmdBuf), CmdLen); if CmdLen <= 0 then begin // OnBeforeProcessRequest handler has cleared command if Assigned(FOnAfterProcessRequest) then FOnAfterProcessRequest(Self, CliWSocket, Pointer(CmdBuf), CmdLen); Exit; end; try HasDatagram := ((CmdLen >= 3) and (CmdBuf[0] = '^')); try if Assigned(FDisplayMemo) and ( ((HasDatagram) and (asoDisplayDatagrams in FOptions)) or ((not HasDatagram) and (asoDisplayCommands in FOptions)) ) then begin if CmdLen < Max_Display_len then InternalDisplay(Self, CliWSocket.PeerAddr + ' ' + String(StrPas(CmdBuf))) else begin // Command is too long, truncate after Max_Display_len characters Ch := CmdBuf[Max_Display_len]; CmdBuf[Max_Display_len] := #0; InternalDisplay(Self, CliWSocket.PeerAddr + ' ' + String(StrPas(CmdBuf))); CmdBuf[Max_Display_len] := Ch; end; end; except end; if Assigned(FOnClientCommand) then FOnClientCommand(Self, CliWSocket, CmdBuf, CmdLen); if HasDatagram then begin { A datagram has been received } DGramType := ''; I := 1; while (CmdBuf[I] <> ' ') and (I < CmdLen) do Inc(I); DGramType := Copy(CmdBuf, 2, I - 1); CliWSocket.DatagramIn(DGramType, CmdBuf + I + 2, CmdLen - I - 2, CmdBuf[I + 1]); //CliWSocket.DatagramIn(CmdBuf + 3, CmdLen - 3, CmdBuf[2]); end else if CliWSocket.Busy then begin SendStringResponseToClient(CliWSocket, FRequestBroker, 405, 'Server object is busy'); CliWSocket.Busy := TRUE; { We are still busy } end else begin CliWSocket.Busy := TRUE; try Inc(FRequestCount); if not Assigned(FRequestBroker) then begin // This should never occurs in a correctly written AppServer // Anyway, if RequestBroker is not assigned, send a valid // answer to client. SendStringResponseToClient(CliWSocket, FRequestBroker, 501, 'No request broker available'); end else begin FRequestBroker.OnLinkClientWSocketAndServerObject := LinkClientWSocketAndServerObject; FRequestBroker.OnAskClientWSocketToSendDatagram := SendDatagramToClient; FRequestBroker.BrokeRequest(Self, CmdBuf, CmdLen, CliWSocket, SendResponseToClient); end; except on E:Exception do begin TriggerServerSObjException(E, CmdBuf, CmdLen); // Extract FunctionCode from CmdBuf, at most 64 characters BufFct := ''; if CmdBuf <> nil then begin I := 0; while (I < CmdLen) and (I < 64) and (CmdBuf[I] <> ' ') do Inc(I); BufFct := Copy(CmdBuf, 1, I); end; Buffer := 'ServerObject crashed. Function "' + BufFct + '". ' + AnsiString(E.ClassName + ': ' + E.Message); { Replace all CR or LF by spaces } for I := 1 to Length(Buffer) do if Buffer[I] in [#13, #10] then Buffer[I] := ' '; SendStringResponseToClient(CliWSocket, FRequestBroker, 404, Buffer); end; end; end; finally if Assigned(FOnAfterProcessRequest) then FOnAfterProcessRequest(Self, CliWSocket, Pointer(CmdBuf), CmdLen); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.LinkClientWSocketAndServerObject( ServerObject : TServerObject; Cli : TObject); begin if Cli is TClientWSocket then begin if not Assigned(ServerObject) then begin TClientWSocket(Cli).OnDatagramAvailable := nil; TClientWSocket(Cli).OnDataSent := nil; TClientWSocket(Cli).ServerObject := nil; end else begin TClientWSocket(Cli).OnDatagramAvailable := ServerObject.DatagramAvailable; TClientWSocket(Cli).OnDataSent := ServerObject.DataSent; TClientWSocket(Cli).ServerObject := ServerObject; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SendDatagramToClient( ToClient : TObject; const DGramType : AnsiString; Datagram : PAnsiChar; DataLen : Integer); var CliWSocket : TClientWSocket; Header : AnsiString; EscChar : AnsiChar; P : PAnsiChar; I, J : Integer; begin if Length(DGramType) = 0 then raise EAppServerException.Create( 'SendDatagramToClient: DGramType is empty'); for I := 1 to Length(DGramType) do begin if not (DGramType[I] in ['A'..'Z', 'a'..'z', '0'..'9', '_']) then raise EAppServerException.Create( 'SendDatagramToClient: ' + 'DGramType contains an invalid character'); end; if (not Assigned(ToClient)) or (not (ToClient is TClientWSocket)) then raise EAppServerException.Create( 'SendDatagramToClient: Unsupported destination type'); // Convert anonymous destination to easier type to handle CliWSocket := TClientWSocket(ToClient); // Hard coded delimiter. Could be a property... EscChar := #127; // Allocate memory for the buffer if not Assigned(CliWSocket.DatagramOutBuffer) then begin if DataLen > (CliWSocket.DatagramOutBufferSize - 3) then CliWSocket.DatagramOutBufferSize := DataLen + 3; GetMem(P, CliWSocket.DatagramOutBufferSize); CliWSocket.DatagramOutBuffer := P; end; // Escape characters in datagram (same mechanism as implemented in TMWBuffer) I := 0; J := 0; while I < DataLen do begin // Check if we have enough place for an EscChar, a Char and a nul if (J + 3) > CliWSocket.DatagramOutBufferSize then begin // Need to enlarge buffer (2KB increment) CliWSocket.DatagramOutBufferSize := CliWSocket.DatagramOutBufferSize + 2048; P := CliWSocket.DatagramOutBuffer; ReallocMem(P, CliWSocket.DatagramOutBufferSize); CliWSocket.DatagramOutBuffer := P; end; if Datagram[I] = EscChar then begin CliWSocket.DatagramOutBuffer[J] := EscChar; Inc(J); CliWSocket.DatagramOutBuffer[J] := EscChar; end else if Datagram[I] = #13 then begin CliWSocket.DatagramOutBuffer[J] := EscChar; Inc(J); CliWSocket.DatagramOutBuffer[J] := 'C'; end else if Datagram[I] = #10 then begin CliWSocket.DatagramOutBuffer[J] := EscChar; Inc(J); CliWSocket.DatagramOutBuffer[J] := 'L'; end else if Datagram[I] = #0 then begin CliWSocket.DatagramOutBuffer[J] := EscChar; Inc(J); CliWSocket.DatagramOutBuffer[J] := 'N'; end else CliWSocket.DatagramOutBuffer[J] := Datagram[I]; Inc(I); Inc(J); end; CliWSocket.DatagramOutBuffer[J] := #0; Header := '^' + DGramType + ' ' + EscChar; CliWSocket.ReplyHeader := PAnsiChar(Header); CliWSocket.ReplyHeaderLen := Length(Header); CliWSocket.ReplyBody := CliWSocket.DatagramOutBuffer; CliWSocket.ReplyBodyLen := J; if Assigned(FOnBeforeSendReply) then FOnBeforeSendReply(self, CliWSocket); CliWSocket.PutDataInSendBuffer(CliWSocket.ReplyHeader, CliWSocket.ReplyHeaderLen); CliWSocket.PutDataInSendBuffer(CliWSocket.ReplyBody, CliWSocket.ReplyBodyLen); CliWSocket.PutStringInSendBuffer(#13+#10); CliWSocket.Send(nil, 0); if Assigned(FOnAfterSendReply) then FOnAfterSendReply(self, CliWSocket); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TAppServer.GetClientCount : Integer; begin Result := FSrvWSocket.ClientCount end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TAppServer.GetClientWSocket(nIndex : Integer) : TClientWSocket; begin if (nIndex >= 0) and (nIndex < FSrvWSocket.ClientCount) then Result := FSrvWSocket.Client[nIndex] as TClientWSocket else Result := nil; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SetTimeoutInterval(newValue : LongInt); begin if newValue <= 0 then newValue := 0; if FTimeoutInterval = newValue then Exit; FTimeoutInterval := newValue; if FTimeoutInterval > 0 then FTimer.Interval := FTimeoutInterval * 1000 else FTimer.Enabled := FALSE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SetClientTimeout(newValue : LongInt); var I : Integer; begin if newValue < 0 then newValue := 0; if FClientTimeout = newValue then Exit; FClientTimeout := newValue; for I := FSrvWSocket.ClientCount - 1 downto 0 do begin TClientWSocket(FSrvWSocket.Client[I]).CommandTimeout := FClientTimeout / (24 * 3600); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.TimerTimer(Sender : TObject); var I : Integer; begin if FTimeoutInterval > 0 then FTimer.Enabled := TRUE; for I := FSrvWSocket.ClientCount - 1 downto 0 do TClientWSocket(FSrvWSocket.Client[I]).CheckCommandTimeout; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SetClientClass(const Value: TClientWSocketClass); begin FClientClass := Value; FSrvWSocket.ClientClass := FClientClass; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppServer.SetName(const NewName: TComponentName); begin inherited SetName(NewName); if Assigned(FSrvWSocket) then FSrvWSocket.Name := 'WSocketServer_' + NewName; if Assigned(FTimer) then FTimer.Name := 'Timer_' + NewName; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { You must define USE_SSL so that SSL code is included in the component. } { To be able to compile the component, you must have the SSL related files } { which are _NOT_ freeware. See http://www.overbyte.be for details. } {$IFDEF USE_SSL} {$I ApServerImplSsl.inc} {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit infosistemas.business.mail; interface uses System.Classes, System.SysUtils, infosistemas.model.exceptions, infosistemas.view.messages, IdSMTP, IdSSLOpenSSL, IdMessage, IdText, IdGlobalProtocols, IdAttachmentFile, IdExplicitTLSClientServerBase, XML.XMLDoc, XML.XMLIntf, infosistemas.system.winshell; type TMailSender = class(TObject) private FHost, FUserName, FPassword, FSenderAccount, FSenderName: string; FSubject, FAttachmentsFolder: string; FPort: integer; procedure LoadConfigurations; public constructor Create(const AttachmentsFolder: string); reintroduce; destructor Destroy; override; procedure SendMail(const MailData, Email, AttachmentFile: string); property Host: string read FHost; property Port: integer read FPort; property UserName: string read FUserName; property Password: string read FPassword; property SenderAccount: string read FSenderAccount; property SenderName: string read FSenderName; property Subject: string read FSubject; end; {Class helper para métodos que extendem a classe TMailSender, que deve permanecer focada apenas no envio de mensagens.} TMailHelper = class helper for TMailSender function CreateAttachmentFile(CustomerData: string): string; function IsValidMail(const MailAddress: string): boolean; end; implementation { TMailSender } constructor TMailSender.Create(const AttachmentsFolder: string); begin self.FAttachmentsFolder := AttachmentsFolder; inherited Create; end; destructor TMailSender.Destroy; begin inherited Destroy; end; procedure TMailSender.LoadConfigurations; begin //Carrega as configurações necessária para o envio de emails. //to-do: carregar isso a partir de um repositório externo: arquivo, registry etc. FHost := 'smtp.gmail.com'; FPort := 465; FuserName := 'EmailDeEnvio@gmail.com'; FPassword := 'Senha do e-mail'; FSenderAccount := 'EmailDeEnvio@gmail.com'; FSenderName := 'Nome do remetente'; FSubject := 'Assunto no envio de e-mail'; end; procedure TMailSender.SendMail(const MailData, Email, AttachmentFile: string); var lSSL: TIdSSLIOHandlerSocketOpenSSL; lSMTP: TIdSMTP; lMessage: TIdMessage; lText: TIdText; begin //Envia um email para um cliente com os seus dados cadastrados. if Email.Trim = '' then raise EInvalidMailInfo.Create(TMessagesConst.InvalidHostMail); if MailData.Trim = '' then raise EInvalidMailInfo.Create(TMessagesConst.InvalidMailData); lSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); try self.LoadConfigurations; lSMTP := TIdSMTP.Create(nil); lMessage := TIdMessage.Create(nil); try lSSL.SSLOptions.Method := sslvSSLv23; lSSL.SSLOptions.Mode := sslmClient; lSMTP.IOHandler := lSSL; lSMTP.AuthType := satDefault; lSMTP.UseTLS := utUseImplicitTLS; lSMTP.Host := self.Host; lSMTP.Port := self.FPort; lSMTP.Username := self.UserName; lSMTP.Password := self.Password; lMessage.From.Address := self.SenderAccount; lMessage.From.Name := self.SenderName; lMessage.ReplyTo.EMailAddresses := lMessage.From.Address; lMessage.Recipients.Add.Text := Email; //to-do: implementar na classe a capacidade de múltiplos destinatários. {lMessage.Recipients.Add.Text := 'QuemIraReceber02@email.com'; lMessage.Recipients.Add.Text := 'QuemIraReceber03@email.com';} lMessage.Subject := self.Subject; lMessage.Encoding := meMIME; lMessage.ContentType := 'multipart/mixed'; //do not localize! lText := TIdText.Create(lMessage.MessageParts); lText.ContentType := 'text/plain; charset=iso-8859-1'; lText.Body.Add('Seguem os seus dados cadastrais:'); lText.Body.Add(MailData); //Anexa o arquivo XML gerado no email que será enviado. {ATENÇÃO: esse trecho está dando crash no método "GetMIMETypeFromFile", que faz parte do código do INDY. Pesquisando na WEB vi queo problema não ocorria no INDY9 e foi inserido no INDY10. Não foi possível estudar e resolver o problema. } if FileExists(AttachmentFile) then begin //lMessage.ContentType := GetMIMETypeFromFile(AttachmentFile); //TIdAttachmentFile.Create(lMessage.MessageParts, AttachmentFile); end; try //to-do: para testar, descomentar as próximas linhas e usar parâmetros reais. //lSMTP.Connect; //lSMTP.Authenticate; //lSMTP.Send(lMessage); except begin //to-do: mapear nos métodos "Connect", "Authenticate" e "Send" os // exceptions que podem ocorrer e tratar aqui. {on E: Exception1 do begin end; on E: Exception2 do begin end;} end; end; finally lSMTP.Free; lMessage.Free; end; finally lSSL.Free; UnLoadOpenSSLLibrary; end; end; { TMailHelper } function TMailHelper.CreateAttachmentFile(CustomerData: string): string; var aList: TStringList; aFileName: string; XMLDocument: TXMLDocument; NodeCustomer, NodeData: IXMLNode; begin //Cria um arquivo XML com os dados a serem enviados ao cliente. Result := ''; aList := TStringList.Create; XMLDocument := TXMLDocument.Create(nil); aList.Text := CustomerData; try XMLDocument.Active := True; NodeCustomer := XMLDocument.AddChild('Cliente'); NodeData := NodeCustomer.AddChild('Dados'); NodeData.ChildValues['CPF'] := aList.Values['CPF']; NodeData.ChildValues['Identidade'] := aList.Values['Identidade']; NodeData.ChildValues['Nome'] := aList.Values['Nome']; NodeData.ChildValues['Telefone'] := aList.Values['Telefone']; NodeData.ChildValues['Email'] := aList.Values['Email']; NodeData.ChildValues['CEP'] := aList.Values['CEP']; NodeData.ChildValues['Logradouro'] := aList.Values['Logradouro']; NodeData.ChildValues['Numero'] := aList.Values['Numero']; NodeData.ChildValues['Bairro'] := aList.Values['Bairro']; NodeData.ChildValues['Cidade'] := aList.Values['Cidade']; NodeData.ChildValues['UF'] := aList.Values['UF']; NodeData.ChildValues['PAIS'] := aList.Values['PAIS']; NodeData.ChildValues['Complemento'] := aList.Values['Complemento']; if TShellFolders.FolderExists(self.FAttachmentsFolder) then begin aFileName := self.FAttachmentsFolder + aList.Values['CPF'] + '.xml'; XMLDocument.SaveToFile(aFileName); Result := aFileName; end; finally if Assigned(aList) then FreeAndNil(aList); if Assigned(XMLDocument) then begin XMLDocument.Active := False; //FreeAndNil(XMLDocument); end; end; end; function TMailHelper.IsValidMail(const MailAddress: string): boolean; begin //Valida de forma simples a estrutura do endereço de caixa de email. // Caracteres inválidos não existem em MailAddress. Result := (MailAddress.Trim <> '') and not (MailAddress.Contains(' ')) and not (LowerCase(MailAddress).Contains('ä')) and not (LowerCase(MailAddress).Contains('ö')) and not (LowerCase(MailAddress).Contains('ü')) and not (LowerCase(MailAddress).Contains('ß')) and not (LowerCase(MailAddress).Contains('[')) and not (LowerCase(MailAddress).Contains(']')) and not (LowerCase(MailAddress).Contains('(')) and not (LowerCase(MailAddress).Contains(')')) and not (LowerCase(MailAddress).Contains(':')) and not (LowerCase(MailAddress).Contains('ç')); if not Result then Exit; // @ existe em MailAddress e está em uma "posição" válida. Result := (MailAddress.Contains('@')) and not (MailAddress.StartsWith('@')) and not (MailAddress.EndsWith('@')); if not Result then Exit; //"." (ponto) existe em MailAddress e está em uma "posição" válida. Result := (MailAddress.Contains('.')) and not (MailAddress.StartsWith('.')) and not (MailAddress.EndsWith('.')); end; end.
unit SetGPSPositionUnit; interface uses SysUtils, BaseExampleUnit; type TSetGPSPosition = class(TBaseExample) public procedure Execute(RouteId: String); end; implementation uses GPSParametersUnit, EnumsUnit; procedure TSetGPSPosition.Execute(RouteId: String); var ErrorString: String; Parameters: TGPSParameters; begin Parameters := TGPSParameters.Create(); try Parameters.Format := TFormatDescription[TFormatEnum.Xml]; Parameters.RouteId := RouteId; Parameters.Latitude := 55.6884868; Parameters.Longitude := 12.5366426; Parameters.Course := 70; Parameters.Speed := 60; Parameters.DeviceType := TDeviceTypeDescription[TDeviceType.AndroidPhone]; Parameters.MemberId := 1; Parameters.DeviceGuid := 'HK5454H0K454564WWER445'; Route4MeManager.Tracking.SetGPS(Parameters, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then WriteLn('SetGps success') else WriteLn(Format('SetGps error: "%s"', [ErrorString])); finally FreeAndNil(Parameters); end; end; end.
Program a5; { This program compares sorting methods. Your job is to fill in code for the Radix Sort procedure below} uses QueueADT; const MAX = 100000; type KeyType = integer; ArrayIndex = 1..MAX; SortingArray = array[ArrayIndex] of KeyType; (************************************ HEAP SORT ***********************************) (* SiftUp(A,i,n) preconditions: A is an array, [i..n] is the range to be reheapified. postconditions: A[i..n] has been reheapified using the SiftUp algorithm found in program 13.10 *) procedure SiftUp(var A: SortingArray; i,n: integer); var j: ArrayIndex; RootKey: KeyType; NotFinished: Boolean; begin RootKey := A[i]; j := 2*i; NotFinished := (j<=n); while NotFinished do begin if j<n then if A[j+1]>A[j] then j := j+1; if A[j] <= RootKey then NotFinished := FALSE else begin A[i] := A[j]; i := j; j := 2*i; NotFinished := (j<=n) end end; A[i] := RootKey end; (* HeapSort(A,n) preconditions: A is an array of size n storing values of type KeyType postconditions: A has been sorted using the HeapSort algorithm found in program 13.10 *) procedure HeapSort(var A: SortingArray; n: integer); var i: integer; Temp: KeyType; begin for i := (n div 2) downto 2 do SiftUp(A,i,n); for i := n downto 2 do begin SiftUp(A,1,i); Temp := A[1]; A[1] := A[i]; A[i] := Temp end end; (************************************ QUICK SORT ***********************************) (* Partition(A,i,j) preconditions: A is an array, and [i..j] is a range of values to be partitioned postconditions: A[i..j] has been partitioned using the Partition algorithm found in program 13.15 *) procedure Partition(var A: SortingArray; var i,j: integer); var Pivot, Temp: KeyType; begin Pivot := A[(i+j) div 2]; repeat while A[i]<Pivot do i := i+1; while A[j]>Pivot do j := j-1; if i<=j then begin Temp := A[i]; A[i] := A[j]; A[j] := Temp; i := i+1; j := j-1 end; until i>j end; (* QuickSort(A,m,n) preconditions: A is an array, and [m..n] is a range of values to be sorted postconditions: A[m..n] has been sorted using the QuickSort algorithm found in program 13.14 *) procedure QuickSort(var A: SortingArray; m,n: integer); var i,j: integer; begin if m<n then begin i := m; j := n; Partition(A,i,j); QuickSort(A,m,j); QuickSort(A,i,n) end end; (************************************ RADIX SORT ***********************************) (* Power(x,n) preconditions: x and n are integers postconditions: returns x^n HINT: you may need this when you are isolating the digits in RadixSort *) function power(x,n: integer): integer; var i, result: integer; begin result := 1; for i := 1 to n do result := result * x; power := result end; (* RadixSort(A,n) preconditions: A is an array of size n postconditions: A[1..n] has been sorted using the RadixSort algorithm *) procedure RadixSort(var A: SortingArray; n: integer); var Buckets: array[0..9] of Queue; i, j, Digit, DigitValue: integer; begin {Initialize the 10 queues} for i := 0 to 9 do Create(Buckets[i]); {Do the main loop once for each of the 5 digits} For Digit := 0 to 4 do begin { Place each element from A into the appropriate bucket (queue)} For i := 1 to n do begin {Get the value of the digit} DigitValue := A[i] div power(10,Digit) mod 10; {Place the digit in the appropriate queue} Enqueue(Buckets[DigitValue],A[i]) end; { Empty the buckets back into the array A starting at array index i=1 } i := 1; {Loop over each bucket} for j := 0 to 9 do {Empty each queue into the next positions in the array} while not IsEmpty(Buckets[j]) do begin {Dequeue an element and put it in the array} A[i] := DeQueue(Buckets[j]); {Increment the array index} i := i + 1 end end; {Destroy each of the queues - actually this is not necessary for the current Queue implementation for i := 0 to 9 do Destroy(Buckets[i])} end; (************************************ EXTRA STUFF ***********************************) (* MakeRandomArray(A,n) preconditions: n is the size of array to create postconditions: A[1..n] has been initialized with random numbers in the range 1..MAXINT *) procedure MakeRandomArray(var A: SortingArray; n: integer); var i: integer; begin for i := 1 to n do A[i] := Random(MAXINT); end; (* PrintArray(A,n) preconditions: A is an array of size n postconditions: A[1..n] is printed to the screen *) procedure PrintArray(var A: SortingArray; n: integer); var i: integer; begin writeln; for i := 1 to n do write(A[i],' '); writeln end; (* IsSorted(A,n) preconditions: A is an array of size n postconditions: Returns TRUE if A[1..n] is sorted in ascending order. Returns FALSE otherwise *) function IsSorted(var A: SortingArray; n: integer): boolean; var i: integer; begin IsSorted := TRUE; for i := 2 to n do if A[i]<A[i-1] then IsSorted := FALSE end; (************************************ EXTRA STUFF ***********************************) var A: SortingArray; {Array to sort} n, {Number of elements in array} choice, {User input} i, {counter} t, {Number of trials} correct: integer; {Number of correct runs} begin randomize; {initialize the random number seed} repeat writeln; writeln('1. HeapSort an Array,'); writeln('2. QuickSort an Array,'); writeln('3. RadixSort an Array,'); writeln('4. Test HeapSort,'); writeln('5. Test QuickSort,'); writeln('6. Test RadixSort,'); writeln('7. quit'); writeln; readln(choice); case choice of 1,2,3: begin Writeln('This option creates a random array and sorts it'); Writeln; Write('How many elements in the array?'); readln(n); MakeRandomArray(A,n); Writeln; Writeln('The random array: '); if n<=100 then PrintArray(A,n) else Writeln('*** too big to print ***'); Writeln; Write('Press Enter to sort'); readln; case choice of 1: begin HeapSort(A,n) end; 2: begin QuickSort(A,1,n) end; 3: begin RadixSort(A,n) end; end; writeln; Writeln('The sorted array: '); if n<=100 then PrintArray(A,n) else Writeln('*** too big to print ***'); Writeln; if (IsSorted(A,n)) then Write('"IsSorted" returned TRUE.') else Write('"IsSorted" returned FALSE.'); readln; end; 4,5,6: begin Writeln('This option tests a sorting algorithm on a bunch of arrays.'); Writeln; Write('How many elements in each array?'); readln(n); Write('How many tests do you want to do?'); readln(t); correct := 0; for i := 1 to t do begin MakeRandomArray(A,n); case choice of 4: begin HeapSort(A,n) end; 5: begin QuickSort(A,1,n) end; 6: begin RadixSort(A,n) end; end; if IsSorted(A,n) then correct := correct + 1; end; writeln; writeln('IsSorted returned TRUE ',correct,' times in ',t,' trials.'); readln; end; end; until (choice = 7); end.